text:
Q: How to configure Hibernate 5 SessionFactoryBean for using HikariCP? Where should I configure connection pool for spring + hibernate application?
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="edu.khai.education.entity"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
        </props>
    </property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:tcp://localhost/~/test"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
</bean>

<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

I want to use org.hibernate.hikaricp.internal.HikariCPConnectionProvider and I don't have a problem to configure it in Hibernate application, but I don't know how to integrate it with Spring.

A: Spring uses DataSource bean to create a lot of infrastructure code e.g. JdbcTemplate or Spring Data JPA @Repository.
Replace the current data source implementation org.apache.commons.dbcp2.BasicDataSource with the com.zaxxer.hikari.HikariDataSource class. Change the current properties to match the HikariCP configuration.


text:
Q: Permission Denied to Upload Django i'm try upload file with django(xlsx) this is my code:
myfile = request.FILES['document']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)

on the model i have setup the folder "media" to uploads, get this error:
Permission denied: '/var/www/html/inventariosRG/media/my_file.xlsx'

this error i'm try fixed with this:
  PATH = 'media/'
  myfile = request.FILES['document']
  try:
     import subprocess
     RUTA_ABSOLUTA = os.path.join(os.path.dirname(os.path.dirname(__file__)),PATH)
     subprocess.Popen('sudo chmod -R 777 '+RUTA_ABSOLUTA, shell=True)
  except Exception as e:
     raise Exception ("Error ",e)
 fs = FileSystemStorage()
 filename = fs.save(myfile.name, myfile)

this code only show the same error "permission denied..." please i'm try set the permission by command on django, any suggest thanks..!!

A: These answers probably relate and are better than 777-ing:
Django - Media upload [Errno 13] Permission denied
A file from the internet is owned by user 'www-data:www-data' and that user has tightly restricted permissions (because files from the internet might be bad.) Your Django media/ folder needs to be accessible and writeable to the www-data user, so making that owner the user is appropriate.
Also, I'm not a sysadmin by any means and I may be speaking from unrecognized ignorance, but building the use of sudo into your Django application seems like a big security risk to me.
I can see a use for a 'config' script, that ensures a new deployment rolls out correctly, but keep that script and your Django code well separated from files from the internet. You could add your script to /etc/sudoers to give it the authority it needs (but remember to edit sudoers with visudo) if there was some reason to automate it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Schrödinger's equation - Time reversal While reading a book about interactions I've come to this paragraph:

In the Schrodinger representation, the state function satisfies the equation $$\mathrm{i}\frac{\partial}{\partial t}\phi(t,x)=H\phi(t,x).$$
Invariance requires the transformed wave function $\mathcal{T}\phi(t,x)$ to satisfy the same equation with $t$ replaced by $t^\prime=-t$. The question is, how is $\mathcal{T}\phi(t,x)$ related to $\phi(t,x)$?
The simplest possible postulate, $\mathcal{T}\phi(t,x)=\phi(-t,x)$, leads to $$\mathrm{i}\frac{\partial}{\partial (-t)}\phi(-t,x)=-H\phi(-t,x)$$

How exactly did we get the minus on the right hand side?
The way I think it should go is if we reverse the time and replace all $t$ by -$t$, we get $-t$ in all arguments of the wavefunction  and one minus in the derivative with respect to time. Where does the 4th minus on the right hand side of the equation come from?
The only explanation I could somehow come up with is that we only changed $t$ to $-t$ inside the argument of wave function and left the derivative untouched and only then mulitplied the whole equation by ($-1$) to get the minus in derivative.
What am I missing? :(

A: *

*The Schrödinger equation is not necessarily symmetric under time reversal. For a time reversal operator $\mathcal{T}$, we have $$\mathrm{i}\hbar\frac{\partial}{\partial t}\mathcal{T}\psi(x,t)=H\mathcal{T}\psi(x,t)$$ only when $$\left[H,\mathcal{T}\right]=0.$$

*Consider an observable $A$. We have $$\mathcal{T}A\mathcal{T}^{-1}=A'.$$ We require that the following relations hold:
a) Correspondence of position: $$\mathcal{T}x\mathcal{T}^{-1}=x^\prime=x$$
b) Correspondence of momentum (the sign change is because in a classical sense, the particle would be moving in the opposite direction under time reversal): $$\mathcal{T}p\mathcal{T}^{-1}=p^\prime=-p$$
c) Commutation relation: $$[x_i,p_j]=\mathrm{i}\hbar\delta_{i,j}\Rightarrow\mathcal{T}[x_i,p_j]\mathcal{T}^{−1}=[x_i^\prime,p_j^\prime]=[x_i,−p_j ]=−[x_i,p_j]$$
So, $$\mathcal{T}(\mathrm{i}\hbar\delta_{i,j})\mathcal{T}^{-1}=-\mathrm{i}\hbar\delta_{i,j}\Rightarrow\mathcal{T}\mathrm{i}\mathcal{T}^{-1}=-\mathrm{i}.$$
This suggests that we 'construct' the time reversal operator in the following manner, using some linear unitary operator $U$ and an antiunitary operator $\mathcal{K}$ which performs complex conjugation here: $$\mathcal{T}=U\mathcal{K};\quad\mathcal{K}\mathrm{i}\mathcal{K}^{-1}=-\mathrm{i}.$$ In other words, the time-reversal operation in quantum mechanics involves both complex conjugation and negating the time: $$t\rightarrow -t;\quad \mathrm{i}\rightarrow-\mathrm{i}.$$
Let $t^\prime=-t$, such that $\mathcal{T}\psi(x,t)=\psi^\prime(x,t^\prime)$. Note that this is not the same definition as the quoted section in the question; we do not take $\psi(x,t^\prime)=\psi^\prime(x,t^\prime)$ (I suppose that there may be additional commentary regarding that equation beneath the sections included in the quotation). Requiring that $\psi^\prime(x,t^\prime)$ is a solution to the corresponding Schrödinger equation, \begin{align}\mathrm{i}\hbar\frac{\partial}{\partial t^\prime}\psi^\prime(x,t^\prime)=H\psi^\prime(x,t^\prime)&\Leftrightarrow\mathrm{i}\hbar\frac{\partial}{\partial t^\prime}\mathcal{T}\psi(x,t)=H\mathcal{T}\psi(x,t)\\\mathcal{T}\mathrm{i}\hbar\mathcal{T}^{-1}\mathcal{T}\frac{\partial}{\partial t}\mathcal{T}^{-1}\mathcal{T}\psi(x,t)&=\mathcal{T}H\mathcal{T}^{-1}\mathcal{T}\psi(x,t)\\U\mathcal{K}(\mathrm{i}\hbar)U^{-1}\mathcal{K}^{-1}U\mathcal{K}\left(\frac{\partial}{\partial t}\right)U^{-1}\mathcal{K}^{-1}\psi^\prime(x,t^\prime)&=\mathcal{T}H^\prime\mathcal{T}^{-1}\psi^\prime(x,t^\prime)\\&=H^\prime\psi^\prime(x,t^\prime)=H\psi^\prime(x,t^\prime)\end{align}Thus,$$\boxed{-\mathrm{i}\hbar\frac{\partial}{\partial t}\psi^\prime(x,t^\prime)=H\psi^\prime(x,t^\prime);\quad-\mathrm{i}\hbar\frac{\partial}{\partial t}\mathcal{T}\psi(x,t)=H\mathcal{T}\psi(x,t).}\tag{A}$$Equation (A) holds irrespective of $[H,\mathcal{T}]$.

A: The minus sign on the right is an error. The time reversed wave function obeys the conjugate Schrödinger equation.

A: I think that quoted paragraph is a little ambiguous - as I understand it, when you apply the time reversal operator, you're changing $t \to -t$ and taking the complex conjugate of the whole equation, so the $i$ on the l.h.s. gains a minus sign that's moved to the Hamiltonian.


text:
Q: Redux middleware returning callbacks not state object I'm new to Redux and I have some confusing questions:
1.
The official docs says when using middleware, each the middleware function can return other than new state object(next(action)), such as function or Promise(even without using redux-thunk). If this is the case, how can this callback or promise be later reached in the code? Just call it in chaining manner after dispatch(actionCreater)?
In the above situation, the function callback is returned rather than an object, then how is it handled through the chaining middlewares?
2.
Kind of extension from 1st question, if there are more than 2 middlewares and several middlewares return callback instead of state, are these callbacks all available to use? I mean, to use them, just call it like dispatch(actionCreater).CALLBACK_NAME()?
If the callbacks have incidently the same name, how this can be handled?

A:
then how is it handled through the chaining middlewares?

I think the chaining is just stopped. For example, looking at redux-thunk's code, if an action is a function, the result of that function is returned, and next is not called; so all the following middlewares are not processing this action.
I think it's logical, because most of the middlewares expect action to be object instead of function. If this function-type action is passed along, those middlewares would broke.

how can this callback or promise be later reached in the code?

I think you have to handle it right away after calling dispatch, pretty much what you described "Just call it in chaining manner after dispatch(actionCreater)".
Like the redux-thunk example
dispatch(makeASandwichWithSecretSauce('My partner')).then(() => {
  console.log('Done!');
});

if there are more than 2 middlewares and several middlewares return
  callback instead of state, are these callbacks all available to use?

I think, the answer is "no". Because the chaining is stopped. If any special action is handled by a certain middleware, that action cannot be passed by calling next, otherwise the special action might break other normal middlewares.
So I guess there are several solutions:

*

*Only use one type of special middleware, so there won't be conflicts.

*If more than one special middleware, manually compose all these middlewares, make it a new middleware, then send the new one into redux applyMiddleware.

*Use some more generic/robust middleware that could handle complex async behavior, like redux-saga.
The idea of 2 maybe like this
const manually = store => next => action => {
  if (typeof action === 'function') {
    const promise = thunk(action);
    const promise2 = anotherThunk(action);

    // this is also tricky, because action is a function, you have to make a new object
    const whatToPass = {
      type: 'what is this', // depends on your need?
      // any other data?
    };
    next(whatToPass); // chaining goes on

    // maybe return this, but maybe not good,
    // because every promise needs to resolve to trigger the 'then'
    return Promise.all([
      promise,
      promise2,
    ]);
  }
  return next(action);
}

A: redux middleware give store as parameter of middleware, you can use that for getting state. You can use store.getState() for getting state. Middleware callbacks structure are as below....
const customMiddleware = store => next => action => {
   const result = next(action);
   console.log("State", store.getState());
   console.log("Action", action.type);
   return result;
}

where store is the redux store, next works same as store.dispatch, action is the action which currently executed.

A: I think this question pretty much asked a same kind of question I was encountered. And sadly, nothing clear answer exists yet.


text: Q: How to visually mark a "mandatory" form input widget? What is the recommended way of (visually) marking a GwtMaterialDesign widget (in a form) as mandatory? (By mandatory I mean the usual "a user has to enter/select a value.")


text:
Q: Temporarily changing a variable's value in Python Python 3.4 provides this neat tool to temporarily redirect stdout:
# From https://docs.python.org/3.4/library/contextlib.html#contextlib.redirect_stdout
with redirect_stdout(sys.stderr):
    help(pow)

The code is not super-complicated, but I wouldn't want to write it over and over again, especially since some thought has gone into it to make it re-entrant:
class redirect_stdout:
    def __init__(self, new_target):
        self._new_target = new_target
        # We use a list of old targets to make this CM re-entrant
        self._old_targets = []

    def __enter__(self):
        self._old_targets.append(sys.stdout)
        sys.stdout = self._new_target
        return self._new_target

    def __exit__(self, exctype, excinst, exctb):
        sys.stdout = self._old_targets.pop()

I'm wondering if there's a general way to use the with statement to temporarily change the value of a variable. Two other use cases from sys are sys.stderr and sys.excepthook.
In a perfect world, something like this would work:
foo = 10
with 20 as foo:
    print(foo) # 20
print (foo) # 10

I doubt we can make that work, but maybe something like this is possible:
foo = 10
with temporary_set('foo', 20):
    print(foo) # 20
print (foo) # 10

I can sort of getting this working by rooting around in globals(), but it's nothing anyone would choose to use.
UPDATE: while I think my "foo = 10" examples clarified what I'm trying to do, they do not convey an actual use case. Here are two:

*

*Redirect stderr, much like redirect_stdout

*Temporarily change sys.excepthook. I do a lot of development interactively, and when I add something to excepthook (by wrapping the original function in one of my own, say, to log exceptions using the logging module), I generally want it to get removed at some point. That way I won't have more and more copies of my function wrapping itself. This question confronts a closely related problem.

A: Building on the answer by @arthaigo,
a more concise version is:
import contextlib

@contextlib.contextmanager
def temporary_assignment(object, new_value):
  old_value = eval(object)
  globals()[object] = new_value
  yield
  globals()[object] = old_value

A: I just found another clever way to do this, using a unittest.mock, documented here.
It's quite general, as one can specify a dictionary with many variables:
import unittest.mock
a = b = 1
with unittest.mock.patch.dict(locals(), a=2, b=3):
  print(a, b)  # shows 2, 3
print(a, b)  # shows 1, 1

Also, it works even if the variables are not previously defined in the current scope.
with unittest.mock.patch.dict(locals(), c=4):
  assert 'c' in locals()
assert 'c' not in locals()

A: I normally use this custom attr_as context manager:
from contextlib import contextmanager

@contextmanager
def attr_as(obj, field:str, value) -> None:
    old_value = getattr(obj, field)
    setattr(obj, field, value)
    yield
    setattr(obj, field, old_value)

You can then use it with the exact same set of arguments you'd use for setattr in attr_as.
class Foo:
    def __init__(self):
        self.x = 1

foo = Foo()
with attr_as(foo, 'x', 2):
    print(foo.x)

bar = 3
with attr_as(sys.modules[__name__], 'bar', 4):
    print(bar)

Note, if you need to preserve the existence/nonexistence of the attribute rather than just the value, that's also possible with just a few more lines:
from contextlib import contextmanager

@contextmanager
def attr_as(obj, field:str, value) -> None:
    old_exists = hasattr(obj, field)
    if old_exists:
        old_value = getattr(obj, field)
    setattr(obj, field, value)
    yield
    if old_exists:
        setattr(obj, field, old_value)
    else:
        delattr(obj, field)

A: I know this question is kind of old, but as I came around the same problem, here is my solution:
class test_context_manager():
    def __init__(self, old_object, new_object):
        self.new = new_object
        self.old = old_object
        self.old_code = eval(old_object)
    def __enter__(self):
        globals()[self.old] = self.new
    def __exit__(self, type, value, traceback):
        globals()[self.old] = self.old_code

It's not pretty as it makes heavy use of global variables, but it seems to work.
For example:
x = 5
print(x)
with test_context_manager("x", 7):
    print(x)

print(x)

Result:
5
7
5

or with functions:
def func1():
    print("hi")

def func2():
    print("bye")

x = 5
func1()
with test_context_manager("func1", func2):
    func1()

func1()

Result:
hi
bye
hi

A: How about a closure?
i.e.
#!/usr/bin/python

def create_closure(arg):
    var = arg

    def hide_me():
        return var

    return hide_me

x = 10
clo = create_closure(x)

x *= 2
x2 = clo()
x += 1

print "x: {0}".format(x)
print "x2: {0}".format(x2)

This yields:
x: 21
x2: 10

And since this is a closure, it could be substantially expanded to preserve a whole bunch of other variables and state, and then either used purely in the closure form going forward, or used as the slate from which to restore state later once you're done.


text:
Q: Share Contact List in Outlook 2010 using LDAP Our company would like to share our contact list in Outlook 2010. However, as we do not have Exchange, we cannot use the share contact feature in Outlook 2010.
We would like to use LDAP to share our contact list as stated in this website:
https://kb.wisc.edu/wiscmail/page.php?id=13789
As far as I know, if I add a new contact in Outlook, LDAP would not sync with it and thus I need to edit it on web. But, may I know if Outlook could get the latest contact list on LDAP server after I amend the list?
Or is there any other good suggestion for share contact list in Outlook 2010?
Thanks for any advice!

A: To answer your question, yes, Outlook can retrieve an up-to-date user list from your Active Directory server, but it will not happen immediately after you add\delete a user, and it's only a one way sync from Active Directory -> Outlook. An update is triggered every 24 hours (by default), in which the contact list would be synced with the users existing under the Search Base you specified in Step #10 (of the link you provided).
That being said, for contacts you wish to share, you should just be adding them as users to Active Directory, instead of adding them directly to your contact list in Outlook. You'll experience the noted latency in seeing newly added users (same goes for users that you delete as well), but it's nice only having to add them in one place, and they can then be shared amongst all of your users.

A: You can keep your contacts in Microsoft Outlook or Outlook Express with the addind, from your LDAP server with
https://github.com/fquiroz01/LDAPSyncOutlook/
Install the App in the computer with Microsoft Outlook or Windows Mail the App keep contacts sync with the LDAP server and mail client contacts.


text:
Q: How to implement the cross-product transformation in Google's wide-and-deep model Having read the paper on wide and deep models for recommender systems, I'm interested in trialing something similar. I'm struggling however to conceptualize how the cross-product transformation they used in the paper was done. The tutorial for the DNNLinearCombinedClassifier demonstrates the use of tensorflow.feature_columns.crossed_columns to perform that transformation, however that implementation only makes sense in a one-to-one relationship between the two columns to be crossed (I.E. when creating the crossed column "workclass_x_education",  for each sample in the dataset there is only one value for workclass and one value for education). In Google's paper they say that:

The wide component consists of  the  cross-product transformation  of  user  installed  apps and impression apps

and additionally that:

Each example corresponds to one impression.  The label is app acquisition: 1 if the impressed app was installed, and 0 otherwise.

From that I gather that each sample is a single impression and that there's a feature for "impressed app" which details the app that this impression was marketing. In that context, there can't then be a single feature for "installed app", because a user might have hundreds of installed apps at the time of the impression. This is confusing, because the figures in the paper do imply that it is a single feature:

Should I interpret that "User Installed App" Categorical Feature not as a single feature, but actually as their dataset having a feature-per-app with a binary flag denoting whether the user has that app installed or not, and that to replicate this functionality in tensorflow I'd need to do something like...

app_list = ['app1', 'app2', 'app3', 'app4', ...]
installed_app_features = ['app1_installed', 'app2_installed', 'app3_installed', 'app4_installed', ...]

impressed_app = tf.feature_column.categorical_column_with_vocabulary_list(key='impressed_app', vocabulary_list=app_list)

installed_apps = []

crossed_features = []

for app in installed_app_features:
    feature = tf.feature_column.categorical_column_with_vocabulary_list(key='app', vocabulary_list=[0,1])
    installed_apps.append(feature)
    crossed_features.append(
        tf.feature_column.crossed_column(
            [impressed_app, feature],
            100
        )
    )

...or am I just completely missing something and need to think about this in a different way?
Many thanks in advance for any help offered.
Dan


text:
Q: "None saw this coming." - Is it grammatically correct? I understand I can say No one saw it coming but wonder if it is okay to say "None saw it coming."?
Also, is the punctuation correct in the end of the last statement?

A: To me, None is synonymous with Not One or with Not Any. It follows that None, like One and Any, may be considered respectively singular or plural, depending on context. Your sentence makes sense from all these viewpoints, although Saw is both singular and plural, so we need not debate the verb form, as we might if your example included "none is/are ..." There is no need for a question mark because there is no explicit question in the statement "I ... wonder ..."


text:
Q: Ruby on Rails Custom Generators with multiple sub generators Hi I was trying to generate a custom generator, So my here my custom generators is Myinitializer, which has myinitializer inside it. But I wanted to have more generators inside it, like the Rails and TestUnit has. I went thought https://guides.rubyonrails.org/generators.html but i could not find how to create these sub generators or whatever they are called. I tried creating a new file inside the generated directory (/lib/generator/myinitializer) but it does not do the sub generator thing.
rails -g
Rails:
  application_record
  assets
  channel
  ...
  system_test
  task

ActiveRecord:
  active_record:application_record

Myinitializer:
  myinitializer

TestUnit:
  test_unit:channel
  test_unit:generator
  test_unit:mailbox
  test_unit:plugin

So what i wanted to have something like:
MyInitializer:
  myinitializer
  anothergeneratorhere

A: You can wrap your generators with a common module to get the namespace (sub-generator) effect you are after.
module Foo
  class Bar < Rails::Generators::Base
    ...
  end
end

will result in a generator called foo:bar.

A: What rmlockerd explained only half answered my question, Here's what worked:
I created the custom generators using rails g generator g1 and rails g generator g2 and organized them into the following directory structure:
# directory: /lib/generators
λ tree
.
└── gorking_generators
    ├── g1
    │   ├── g1_generator.rb
    │   ├── templates
    │   └── USAGE
    └── g2
        ├── g2_generator.rb
        ├── templates
        └── USAGE

The content of the files are as follows:
# file: g1_generator.rb
module GorkingGenerators
  module Generators
    class G1Generator < Rails::Generators::NamedBase
      source_root File.expand_path('templates', __dir__)
    end
  end
end
# file: g2_generator.rb
module GorkingGenerators
  module Generators
    class G2Generator < Rails::Generators::NamedBase
      source_root File.expand_path('templates', __dir__)
    end
  end
end

After this, I am able to see the generators in place when using rails g:
GorkingGenerators:
  gorking_generators:g1
  gorking_generators:g2

I can then use them using:
rails g gorking_generators:g1


text:
Q: What is difference between closed-set and open-set classification problem? What is difference between closed-set and open-set classification problem? Please explain in terms of face recognition problem.

A: Open-set classification is a problem of handling unknown classes that are not contained in the training dataset, whereas traditional classifiers assume that only known classes appear in the test environment.


text:
Q: How does PSModulePath environment property get composed? This question is related to my other post - Using both desktop Powershell 5.1 and Powershell Core 6.1
Basically the root of the evil is that when I open a desktop Powershell and check $env:PSModulePath I see PS.Core module path there.
Please, observe:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\me> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17763.503
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.503
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

PS C:\Users\me> $env:PSModulePath -split ';'
C:\Users\me\Documents\PowerShell\Modules
C:\Program Files\PowerShell\Modules
c:\program files\powershell\6\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
PS C:\Users\me>

Notice c:\program files\powershell\6\Modules.
Now when I inspect the Environment variables in the Control Panel I see a different picture:
User

System

I do not even have the $PROFILE script:
PS C:\Users\me> Test-Path $PROFILE
False
PS C:\Users\me>

As one can see PS.Core 6.1 module path is not mentioned in the Control Panel, yet it is found in the actual PSModulePath environment variable.
So, my question is - how is PSModulePath truly composed?
I could not find it in the Microsoft documentation (I mean I did find it is an environment variable, but as one can see there is more to it). I must be missing something obvious.
EDIT 1
I opened Process Explorer and checked the environment of the parent process - explorer.exe. Its PSModulePath is:
C:\Users\mkharitonov\Documents\PowerShell\Modules
C:\Program Files\PowerShell\Modules
c:\program files\powershell\6\Modules
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

But after killing the explorer.exe and running it again, I can see the PS.Core module path disappeared. And so reopening the Powershell shows proper module path.
I suppose when I installed PS.Core 6.1 it modified the environment of the explorer.exe somehow. Or was it VS Code? Anyway, restarting the explorer fixes the issue.
I will have to dig into it and open a bug either to PS.Core or VS Code.

A: When PowerShell starts up it'll attempt to set the PSModulePath env var by:

*

*Reading the existing value of %PSModulePath% from the host process

*Reading default module paths for the current user and for all users from the host application's config

*If on Windows, reading the %windir%\system32 module folder as well

*Update the value of $env:PSModulePath by combining all three

If you see an unexpected value in there, pwsh.exe might have simply inherited it frmo the parent process and it's included in step 1


text:
Q: The '>' operator can not be applied to instances of type 'int' and 'int' I am getting the error in the title when I try and compile the below code as part of an app in AIDE. The code below is from Apache WordUtils (I don't want to import a whole library for a single thing), but I also get the error in other code. It used to work fine, but I then updated AIDE, and it stopped working. It has no suggestions in the "Fix" option (not even "Delete"), and seems to happens with all my for loops. I get the error with both < and >, but not ==.
I know there is already a similar question here, but it did not have any accepted answers, and the suggested solutions did not work for me.
I have tried refreshing the build, removing the spaces, and defining variables outside the loops. However, none of those have worked. I have also tried reinstalling AIDE, and reverting to an older version, but the code will not work.
Problematic code:
public static String capitalize(String str, char[] delimiters) {
    int delimLen = (delimiters == null ? -1 : delimiters.length);
    if (str == null || str.length() == 0 || delimLen == 0) {
        return str;
    }
    int strLen = str.length();
    StringBuffer buffer = new StringBuffer(strLen);
    boolean capitalizeNext = true;
    for (int i = 0; i < strLen; i++) {
        char ch = str.charAt(i);

        if (isDelimiter(ch, delimiters)) {
            buffer.append(Character.toLowerCase(ch));
            capitalizeNext = true;
        } else if (capitalizeNext) {
            buffer.append(Character.toTitleCase(ch));
            capitalizeNext = false;
        } else {
            buffer.append(ch);
        }
    }
    return buffer.toString();
}
private static boolean isDelimiter(char ch, char[] delimiters) {
    if (delimiters == null) {
        return Character.isWhitespace(ch);
    }
    for (int i = 0, isize = delimiters.length; i < isize; i++) {
        if (ch == delimiters[i]) {
            return true;
        }
    }
    return false;
}

A: I eventually figured it out. What I did was uninstall AIDE, delete the entire "/sdcard/.aide" directory, and delete the "build" folder in the project, along with a .gitignore file that was there for some reason. It seems like I needed to do all of them at once, because none worked on their own.


text:
Q: how to modify nargs( of optparse-add_option) from User input(raw_input)? This Question is continuation of old question @: how to access nargs of optparse-add_action?
As that question was answered for what it was in-tented.
Brief:
Suppose if I am using add_option utility like below:
parser.add_option('-c','--categories', dest='Categories', nargs=4 )

Is there a way to modify nargs of add_option() from user input using raw_input.?
EDIT:
I will give a clear difference between my "previous question need" and "this question need".
First question case:
My script will ask for user inputs if user has provided no inputs, i.e.,He has just run
#./commandparser.py

Second Question case requirement is:
when i run my script ./commandparser.py -c abc bac cad
it throws error: commandparser.py: error: -c option requires 4 arguments and exit the script.
Instead of throwing error and exit the script. I want some mechanism so that it asks user to input remaining arguments i.e., 4th argument without exiting the script.

A: Are you, by any chance, trying to accept a variable number of values for this option?  That is, use the 'rawinput' to set nargs, which is then used to parse the command line?
The optparse documentation has an example of using a custom callback to handle a variable number of values:
https://docs.python.org/2/library/optparse.html#callback-example-6-variable-arguments
argparse, on the other hand, does allow a variable number of values, with nargs values like '?' (0 or 1), '+' (1 or more), '*' (0 or more).

Since I'm more conversant with argparse I'll sketch out an interactive script to handle your revised requirement:
import argparse
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-c', '--categories', nargs='+', help='4 categories', default=[])
args = parser.parse_args()
print(args)
categories = args.categories
while len(categories)<4:
    print(parser.format_usage())
    x = raw_input('enter %s categories: '%(4-len(categories))).split()
    categories.extend(x)
print('categories', categories)

If 'categories' are the only arguments, you could replace all of the argparse stuff (or optparse) with categories = sys.argv[1:], or [2:] if you still expect the '-c' flag.

Or using optparse (adapted from the docs example for variable length callback):
def vararg_callback(option, opt_str, value, parser):
     value = []
     for arg in parser.rargs:
         # stop on --foo like options
         if arg[:2] == "--" and len(arg) > 2:
             break
         # stop on -a (ignore the floats issue)
         if arg[:1] == "-" and len(arg) > 1:
             break
         value.append(arg)
     del parser.rargs[:len(value)]
     setattr(parser.values, option.dest, value)

def use_opt():
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-c','--categories', dest='categories', action="callback", callback=vararg_callback)
    (options, args) = parser.parse_args()
    print options, args
    return options, args, parser

args, rest, parser = use_opt()


text:
Q: Using windows ftp command to login with ssh key I have google but found that what I want to do is possible using a third-party software, but can anyone answer this question:
I'm trying to ftp to linux server running sftp. I'm tryinh to connect to it automatically using a batch script. I have accomplish this using the command:
ftp -i -s:"Path to a text file containing FTP commands"

This works find however now I need to use a ssh key to authenticate is this possible using this method and no third-party software?
This is a sample of the text file being passed to the ftp command:
open "IP of server"
username
password
mget *
bye

A: Take a look at this very excellent tutorial on how to set up ssh keys so you do not have to use a password: http://www.linuxproblem.org/art_9.html.  That will give you background on the process.
This assumes both client and server are running some flavor of unix (OSX included)!
If they are not (in your case), or if you have a non-standard configuration, then there is a pretty high probability that you will need to use third party software to hold the keys.
Once that is set up, you should use sftp instead of ftp.


text:
Q: How to turn on DisplayPort I have Thinkpad T430 with NVIDIA NVS 5400M and Intel HD Graphics 4000.
I installed the bumblebee and nvidia-current, but Ubuntu still doesn't recognise external monitor connected DisplayPort

A: It may be that the digital output (the displayport) is driven directly by the nvidia card. This is the case with my W520 (see the blog post here). Bumblebee is designed primarily to render graphics on the nvidia card and output them on the laptop display through the intel card, not to drive external monitors with the nvidia card. Probably the most simple work around is described here (not sure if it will still work on the T430 and the intel driver included with the latest version of ubuntu though).
You may be able to use the VGA port (that was the case with the 420), or you may be able to switch to using the nvidia card for both the external and thinkpad displays in the BIOS menu. This will impact battery life though.


text:
Q: Visual Studio 2015 doesn't read ArcGIS 10.2.2 advanced license I have an ArcGIS 10.2.2 Advanced License installed. I have Visual Studio 2015 installed. When I open my form I assign.
public frmMain()
{
    // this must be the first object created
    try
    {
            ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.Desktop);
            init = new AoInitializeClass();
            init.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
    }
    catch (Exception)
    {
        MessageBox.Show("Unable to obtain license. Application will be shut down.");
        Environment.Exit(1);
   }

    InitializeComponent();
}

However when I check for the license name, I get a Basic license.
ArcGIS 10.2.2 was installed when I inherited the computer, and I installed Visual Studio 2015 C#.
Would anyone have any idea on why my advanced license would show as a Basic license in C#?

A: ArcObjects .Net SDK for ArcGIS 10.2.x requires Visual Studio 2010 or 2012.  Visual Studio 2015 isn't supported for 10.2.x
See ArcObjects SDK 10.2.x system requirements - Scroll to bottom of page for info on ArcObjects SDK for the Microsoft .NET Framework.

Also:

*

*ArcObjects for 10.3.x requires VS 2012 or VS 2013

*ArcObjects for 10.4.x requires VS 2013 or VS 2015

A: Got Visual Studio 2015 to read an ArcGIS 10.2.2 Advanced License. Even though I have always used ESRI.ArcGIS.RuntimeManager.BindLicense() and things worked.  This time had to use ESRI.ArcGIS.RuntimeManager.Bind().  I also uninstalled ArcReader which I was reading an Advanced License for.
public frmMain()
{
    // this must be the first object created
    try
    {
        ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.Desktop);
        init = new AoInitializeClass();
        init.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
    }
    catch (Exception)
    {
        MessageBox.Show("Unable to obtain license. Application will be shut down.");
        Environment.Exit(1);
    }

    InitializeComponent();
}

to
public frmMain()
{
    // this must be the first object created
    try
    {
        ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
        init = new AoInitializeClass();
        init.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
    }
    catch (Exception)
    {
        MessageBox.Show("Unable to obtain license. Application will be shut down.");
        Environment.Exit(1);
    }

    InitializeComponent();
}


text:
Q: How to play specific start and end duration in HTML5 audio? I got a audio duration which is 5 minutes = 5:00, but it's too long to listen whole audio, so I got a tag which is from example 2:00 minutes to 3:00 minutes, So what I want to do is play the tag in the HTML5 audio which mean play from 2:00 minutes to 3:00 minutes.
Here is what I found how to play the start duration
$('#audio').bind('canplay', function() {
  this.currentTime = 29; // jumps to 29th secs
});

Update
Here is my code
 <audio id="audio" controls="controls" class="span4">
  <source src="file/test.mp3" type="audio/ogg">
  <source src="file/test.mp3" type="audio/mpeg">
  <source src="file/test.mp3" type="audio/wav">
  Your browser does not support the audio element. Please try other browser
</audio>

Here is my tag sample

AJAX
$('.start_tag').click(function() {
    var sec =  $(this).attr('data-id');
    var file =  $(this).attr('data-file');
    show_tag(sec,file);
});

function show_tag(sec,file)
{
    $.ajax({
        type: "POST",
        url: config.base_url + 'index.php/qm/show_tag',
        data : {
            sec : sec,
            file : file,
        },
        success : function(data) {
            $('.show_tag').empty().append(data);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown);
        }
    });

}

Ajax Posted Data
  function show_tag()
    {
        $sec = $this->input->post('sec');
        $record_filename = $this->input->post('file');
        $table = '
Tagged File
';
        $table .= '<audio id="audio" controls="controls" class="span4 video1">';
        $table .= '<source src="'.base_url().'file/'.$record_filename.'" type="audio/ogg">';
        $table .= '<source src="'.base_url().'file/'.$record_filename.'" type="audio/wav">';
        $table .= '<source src="'.base_url().'file/'.$record_filename.'" type="audio/mpeg">';
        $table .= 'Your browser does not support the audio element. Please try other browser';
        $table .= '</audio>';
        $table .= '';

/*      $table .= '';
         */

        echo $table;
    }

What I did was when click the start tag, it's will go to the current audio time

A: You can listen to the timeupdate event and pause the video once it has reached a currentTime of 3 minutes.
$('#audio').bind('timeupdate', function () {
    if (this.currentTime >= 180) this.pause();
}

Here's a list of events you can listen for on a media element:
MDN


text:
Q: Ошибка "type viewcontroller does not conform to protocol vkdelegate"
type viewcontroller does not conform to protocol vkdelegate.

и правильно ли я делаю logout?
class ViewController: UIViewController, VKDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        VK.configure(appID: "5720982", delegate: self)
    }

    func vkWillAuthorize() -> [VK.Scope] {
        //Called when SwiftyVK need autorization permissions.
        return [.offline] //an array of application permissions
    }

    func vkDidAuthorizeWith(parameters: Dictionary<String, String>) {
        let userId = parameters["user_id"]!

        let req = VK.API.Users.get([VK.Arg.userId: userId])
        req.httpMethod = .GET
        req.successBlock = { response in
            let id = response.array![0]["id"].intValue
            let firstName = response.array![0]["first_name"].stringValue
            let lastName = response.array![0]["last_name"].stringValue

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "mainPage") as! mainView
            self.navigationController?.pushViewController(vc, animated: true)

            print(id)
            print(firstName)
            print(lastName)
        }
        req.errorBlock = {
            error in print(error)
        }
        req.send()
    }

    func vkDidUnauthorize(id: Int) {
    /*    let logoutUrl = URL(string: "http://api.vk.com/oauth/logout")
        let request = URLRequest(url: logoutUrl!)
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)*/
        //Called when user is log out.
    }

    @IBAction func signInTouchUp(_ sender: UIButton) {
        VK.logIn()
    }

}

A: У вас неправильная подпись в didUnauthorize - там не должно быть входного параметра (а у вас Int)
func vkDidUnauthorize()


text:
Q: How to render image from servlet in docx4j generated docx This question is very similar to this question but relates to docx4j instead of flying saucer.
I'm using docx4j to render an xhtml document to docx through a servlet which returns the generated docx document. The xhtml document features an image which is requested from another servlet. The image servlet checks who is logged in before returning the appropriate image. The code below shows how the image is requested:

My problem is that the http request for the image is from the XHTMLImporter (I think) and not the logged in user so the image servlet doesn't know who's logged in and therefore the desired image is not returned.
I'm currently using the code below to render the xhtml document:
XHTMLImporter.setHyperlinkStyle("Hyperlink");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
ndp.unmarshalDefaultNumbering();

wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert(xhtmlDocAsString, null, wordMLPackage));

In flying saucer I was able to use a ReplacedElementFactory but that doesn't seem to be something docx4j uses. Is there a way to replace elements during the conversion process?

A: Oh what fun I've had! I have a convoluted, complex and crazy solution and I know @JasonPlutext will provide a very simple and obvious solution that I overlooked.
Here it is. This code generates the word document to an output stream:
        outputStream = response.getOutputStream();

        XHTMLImporter.setHyperlinkStyle("Hyperlink");

        // Create an empty docx package
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

        NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
        wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
        ndp.unmarshalDefaultNumbering();

        // Convert the XHTML, and add it into the empty docx we made
        List<Object> wmlObjects = getWmlObjects(wordMLPackage, xhtmlDocumentAsString);
        wordMLPackage.getMainDocumentPart().getContent().addAll(wmlObjects);

        SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
        saver.save(outputStream);

The method getWmlObjects is my own which simulates the XHTMLImporter.convert method but does everything itself with a lot of reflection. It basically injects a couple of objects to override the default Docx4jUserAgent and Docx4jReplacedElementFactory objects in the DocxRenderer (which is a field of the Importer instance). See below:
private List<Object> getWmlObjects(WordprocessingMLPackage wordMLPackage, String xhtmlDocumentAsString) {

    try {
        DocxRenderer renderer = new DocxRenderer();

        // override the user agent
        FieldAccessUtils.setField(renderer, "userAgent", new ProfileImageDocx4jUserAgent());

        // override the replaced element factory
        Docx4jDocxOutputDevice outputDevice = (Docx4jDocxOutputDevice) FieldAccessUtils.getField(renderer,
                "_outputDevice");
        renderer.getSharedContext().setReplacedElementFactory(
                new ProfileImageDocx4jReplacedElementFactory(outputDevice));

        // build the XHTMLImporter instance as it does in XHTMLImporter.convert but with our new renderer

        XHTMLImporter importer; // = new XHTMLImporter(wordMLPackage);
        Constructor<XHTMLImporter> constructor = XHTMLImporter.class
                .getDeclaredConstructor(WordprocessingMLPackage.class);
        constructor.setAccessible(true);
        importer = constructor.newInstance(wordMLPackage);
        constructor.setAccessible(false);

        FieldAccessUtils.setField(importer, "renderer", renderer);

        InputSource is = new InputSource(new BufferedReader(new StringReader(xhtmlDocumentAsString)));
        Document dom = XMLResource.load(is).getDocument();

        renderer.setDocument(dom, null);
        renderer.layout();

        // use reflection to do: importer.traverse(renderer.getRootBox(), FieldAccessUtils.getField(importer, "imports"), null);
        Method traverseMethod = importer.getClass().getDeclaredMethod("traverse", Box.class, List.class,
                TableProperties.class);
        traverseMethod.setAccessible(true);
        traverseMethod.invoke(importer, renderer.getRootBox(), FieldAccessUtils.getField(importer, "imports"), null);
        traverseMethod.setAccessible(false);

        return (List<Object>) FieldAccessUtils.getField(importer, "imports");

    } catch (SecurityException e) {
        getLogger().error(ExceptionUtils.getStackTrace(e));
    } catch (NoSuchMethodException e) {
        getLogger().error(ExceptionUtils.getStackTrace(e));
    } catch (IllegalArgumentException e) {
        getLogger().error(ExceptionUtils.getStackTrace(e));
    } catch (IllegalAccessException e) {
        getLogger().error(ExceptionUtils.getStackTrace(e));
    } catch (InvocationTargetException e) {
        getLogger().error(ExceptionUtils.getStackTrace(e));
    } catch (InstantiationException e) {
        getLogger().error(ExceptionUtils.getStackTrace(e));
    }

    try {
        // plan B
        return XHTMLImporter.convert(xhtmlDocumentAsString, null, wordMLPackage);
    } catch (Docx4JException e) {
        getLogger().error(ExceptionUtils.getStackTrace(e));
    }

    return null;
}

Then I just have my two customised classes ProfileImageDocx4jUserAgent (which does the donkey work):
public class ProfileImageDocx4jUserAgent extends Docx4jUserAgent {

    /**
     * Replace the image where the DisplayUserPic servlet is being called.
     *

     * From overridden method javadoc:
     *

     * {@inheritDoc}
     */
    @Override
    public Docx4JFSImage getDocx4JImageResource(String uri) {

        if (StringUtils.contains(uri, "DisplayUserPic")) {

            InputStream input = null;
            try {

                input = ...;
                byte[] bytes = IOUtils.toByteArray(input);
                return new Docx4JFSImage(bytes);

            } catch (IOException e) {
                getLogger().error(ExceptionUtils.getStackTrace(e));
            } catch (ServiceException e) {
                getLogger().error(ExceptionUtils.getStackTrace(e));
            } finally {
                IOUtils.closeQuietly(input);
            }

            return super.getDocx4JImageResource(uri);

        } else {
            return super.getDocx4JImageResource(uri);
        }
    }
}

And ProfileImageDocx4jReplacedElementFactory (which gets the iText stuff to ignore the image at this point... otherwise there's an error logged but it still works fine):
public class ProfileImageDocx4jReplacedElementFactory extends Docx4jReplacedElementFactory {

    /**
     * Constructor.
     *
     * @param outputDevice
     *            the output device
     */
    public ProfileImageDocx4jReplacedElementFactory(Docx4jDocxOutputDevice outputDevice) {
        super(outputDevice);
    }

    /**
     * Forces any images which use the DisplayUserPic servlet to be ignored.
     *

     * From overridden method javadoc:
     *

     * {@inheritDoc}
     */
    @Override
    public ReplacedElement createReplacedElement(LayoutContext layoutContext, BlockBox blockBox,
            UserAgentCallback userAgentCallback, int cssWidth, int cssHeight) {

        Element element = blockBox.getElement();
        if (element == null) {
            return null;
        }

        String nodeName = element.getNodeName();
        String src = element.getAttribute("src");
        if ("img".equals(nodeName) && src.contains("DisplayUserPic")) {
            return null;
        }

        // default behaviour
        return super.createReplacedElement(layoutContext, blockBox, userAgentCallback, cssWidth, cssHeight);
    }
}

I guess the docx4j guys will probably build something into docx4j to handle this sort of case but for the moment (I think) this seems to be a good work around


text:
Q: vb.net convert string into map In my VB.Net project I am getting data from MySQL database in the following format:
[{"v":2.283175588,"p":"PASS"},{"v":2.373615284,"p":"PASS"},{"v":2.345711042,"p":"PASS"},{"v":2.365022001,"p":"PASS"}]'

I need to extract min and max value of v.


text:
Q: How to emulate Mac OS 8 (in a way that supports CD-ROMs) I am trying to install old software on my either one of my Macs (Powerbook G4 and iMac 21.5 from 2011).
This software contains old fonts in a very rare format, which I would like to be able to watch / install / convert (eventually).
I have tried opening the font files in OS X with almost every font program available (FontBook, FontDoctor, FontForge, FontLab, Fontographer, TransType4...) and have come to believe that they can only be viewed on an older system for which they were designed.
I opened another discussion about how one might open these rare / old file formats on today's machines but it doesn't seem to be possible.
So, the software I am trying to install is on three different CD-ROMS hat are designed for Mac OS 6/7/8.
I have two partitions on the Powerbook, one with OS X 10.3 that can run Classic (Mac OS 9.2), and one with OS X 10.5.3 (most recent possible system for this machine), this way I can go back and forth systems.
When I try to launch the installer CD in the Classic environment, the top menu bar becomes grey and Classic freezes, so I think this CD can only run on machines earlier than 9.2 / 9.0, such as 7 or 8.
On the iMac, I have SheepShaver with OS 9, Basilisk with OS 7 and Mini vMac.
None of these recognise the CD ("disk is unreadable).
If I create a .DMG copy of the CD, or a copy of the files, I can open and run the Installer successfully in the beginning (with Sheepshaver / System 9 and Basilisk II / System 7), but after a few registration steps, the installer program asks me to insert the CD and fails to recognise it. (I tried starting these emulators when the CD was already in the drive, no chance.)

I believe I could go and buy one of these old clamshell Apple laptop that runs 8.2 but I'd like to do without.
I also considered installing 8.0 with original install CDs into SheepShaver, but people online say Sheepshaver / Basilisk are usually touchy when it comes to recognise CD-ROMs.
EDIT:
Here's what fontographer does:

EDIT (2): I found out how to solve this problem.
Here's how: I created three read/write disk images, one for each install CD, using Disk Utility in OS X.
Then using BasiliskII, I added each .dmg file to my preferences window.
Upon restart, all three CDS showed up and could be used without the CD.
(In my previous efforts, I had not tried to convert each CD into a .DMG file or didn't know how to add them as drives into Basilisk.)
Thanks for the help! Can someone please mark it as "solved" if you have clearance.

A: You need to use a CD/DVD Authoring software like Toast to mount the image inside the emulated classic Mac (SheepShaver). The CD mounter that is built in is not good enough to trick software that looks for the original disk. Software like Toast Mounter can though.

A: From your question, are you implying that OSX has no problem opening and reading the CD-ROM but then doesn't recognize the format of the font files?
The question I would have is what format is the CD-ROM? Is it ISO-9660 or some other format that perhaps needed a special driver back in the Mac OS days? I can't say I'm necessarily aware of the variations, but I struggle to think of why it wouldn't be recognized by the emulators if it was a standard format with appropriate drivers.
That all being said, if the problem is that you want to use the font files on the CD-ROM and OSX recognizes them, why not copy them to your OSX machine and then burn them to another CD? Better yet, I think you can access an OSX directory from Basilisk so why not just copy the files there?


text:
Q: Projects feature with attachments from one coordinate system to another I'm trying to projects a feature with attachments from one coordinate system to another without loosing the attachments.
I'm using the GeoTagged Photos To Points function to create a point feature class which also contains the photos as attachments.
Unfortunately this function does not provide an option to reproject the output feature class. And if I use the project_management function, I lose the attachments.
Minimal example:
import arcpy
arcpy.env.maintainAttachments = True
# maintainAttachments work for the following function:
# - Append
# - Copy
# - Copy Features
# - Copy Rows
# - Feature Class To Feature Class
# - Merge
# - Table To Table
arcpy.GeoTaggedPhotosToPoints_management(folder, photo_gps, "", "ALL_PHOTOS", "ADD_ATTACHMENTS")
arcpy.Project_management(photo_gps, photo_gps_proj, out_coordinate_system)

But unfortunately photo_gps_proj do not contains the attachments !
How can I project photo_gps and keep the attachments ?

A: I've found a solution by myself:
I reproject my original feature (oFC) to obtain the projected feature (pFC), then I change the projection system of oFC and I copy the shape of pFC:
# Reprojection
sr = arcpy.SpatialReference(2056) #define the new projection
arcpy.Project_management (featurename, featurename+'_proj', sr,'CH1903+_To_WGS_1984_1') # create the projected feature
arcpy.DefineProjection_management(featurename, sr) #change the projection of the original feature

# Replace the shape of oFC with the shape of pFC
edit = arcpy.da.Editor(arcpy.env.workspace)
edit.startEditing(False, True)
edit.startOperation()

with arcpy.da.SearchCursor(featurename+'_proj', ["GUID", "SHAPE@"]) as cursor1:
    for row1 in cursor1:
        with arcpy.da.UpdateCursor(featurename, ["GUID", "SHAPE@"]) as cursor2:
            for row2 in cursor2:
                if row1[0] == row2[0]:
                    row2[1] = row1[1]
                    cursor2.updateRow(row2)

edit.stopEditing(True)

arcpy.RecalculateFeatureClassExtent_management(featurename)

# Delete the unecessary feature:
if arcpy.Exists(featurename+'_proj'):
    arcpy.Delete_management(featurename+'_proj')

Work like a charm.


text:
Q: Python / GPyOpt: Optimizing only one argument I´m currently trying to find the minimum of some function f(arg1, arg2, arg3, ...) via Gaussian optimization using the GPyOpt module. While f(...) takes many input arguments, I only want to optimize a single one of them. How do you do that?
My current "solution" is to put f(...) in a dummy class and specify the not-to-be-optimized arguments while initializing it. While this is arguably the most pythonesque way of solving this problem, it`s also way more complicated than it has any right to be.
Short working example for a function f(x, y, method) with fixed y (a numeric) and method (a string) while optimizing x:
import GPyOpt
import numpy as np

# dummy class
class TarFun(object):
    # fix y while initializing the object
    def __init__(self, y, method):
        self.y = y
        self.method = method
    # actual function to be minimized
    def f(self, x):
        if self.method == 'sin':
            return np.sin(x-self.y)
        elif self.method == 'cos':
            return np.cos(x-self.y)

# create TarFun object with y fixed to 2 and use 'sin' method
tarFunObj = TarFun(y=2, method='sin')
# describe properties of x
space = [{'name':'x', 'type': 'continuous', 'domain': (-5,5)}]
# create GPyOpt object that will only optimize x
optObj = GPyOpt.methods.BayesianOptimization(tarFunObj.f, space)

There definitely has to be a simpler way. But all the examples I found optimize all arguments and I couldn't figure it out reading the code on github (I though i would find the information in GPyOpt.core.task.space , but had no luck).

A: I would check out the partial function from the functools standard library.  It allows you to partially specify a function, so for example:
import GPyOpt
import numpy as np
from functools import partial

def f(x, y=0):
    return np.sin(x - y)

objective = partial(f, y=2)
space = [{'name': 'x', 'type': 'continuous', 'domain': (-5, 5)}]

opt = GPyOpt.methods.BayesianOptimization(
    objective, domain=space
)

A: GPyOpt supports this natively with context. You describe the whole domain of your function, and then fix values of some of the variables with a context dictionary when calling optimization routine. API looks like that:
myBopt.run_optimization(..., context={'var1': .3, 'var2': 0.4})

More details can be found in this tutorial notebook about contextual optimization.


text:
Q: Form-based HTTP digest authentication I'm about to embark on POC using Javascript to simulate the digest authentication steps between client and server. I'm ok on an individual request but what about requests during the entire session.
Specifically, I'm wondering how the browser would handle subsequent requests once the login is successful. Is the browser clever enough to remember the necessary headers used during the login exchange, even though this occurred in Javascript, so that it can continue to use the same nonce and increment the nc as appropriate.

A: If Digest Auth is not a hard requirement I would suggest using a Token Authentication strategy, it works well for browser apps.  If you are writing a "single page app" that is going to talk to an API, you can read this article of mine for more information: Token Based Authentication for Single Page Apps (SPAs)


text:
Q: Find the coefficient of term independent of x in (1+x+7/x)^7 Find the coefficient of term independent of x in the expansion of $(1+x+7/x)^7$.

This is my attempt. I found the number of ways by which we can create a term independent of x.
If we take all the 1's from each bracket, there are $7C7$ ways to do that. Next we take 1 "x"from a bracket and 1 "7/x" from another bracket and take 1 from the remaining brackets, there are $7C1.6C1.7$ ways to do that. Next we take 2"x" from two brackets and 2 "7/x" from another two brackets and take 1 from the remaining brackets, there are $7C2.5C2$ ways to do that. Similarly we take 3"x" from three brackets and 3 "7/x" from other three brackets and take 1 from the remaining brackets, there are $7C3.4C3$ ways to do that.
We add all these 5 terms to get the required coefficient.
But my answer is much lesser than what is given in the textbook.
What case I missed? Did I count wrong?

A: Your answer of $1+\binom{7}{1}\binom{6}{1}7+\binom{7}{2}\binom{5}{2}7^2+\binom{7}{3}\binom{4}{3}7^3=58605$ is correct for finding the coefficient of the constant term in the expansion of $(1+x+\frac{7}{x})^\color{red}{7}$.  wolframalpha
The error is on the books part, either having a typo in the problem statement or having made a mistake in the solution itself.  The calculations in the solution are correct for the different problem of finding the coefficient of the constant term in the expansion of $(1+x+\frac{7}{x})^{\color{red}{11}}$ (note the different exponent).


text:
Q: Reading a directory and listing the files it contains I need to write the class in PHP. Input takes the path (directory name). The class has two methods:

*

*files - returns an array of file names of this directory.

*table - returns a generated html table with a list of files in this directory.

How do I do this?

A: You don't need to create a class for this.  In fact, you should not.  That is overly complex and entirely unnecessary.
If you need to read the list of files in a directory, you have three options: readdir, glob, or  DirectoryIterator.
If you need to read the list of files in a directory, and all the directories inside of it, then you want to use RecursiveDirectoryIterator.
There are adequate usage examples on the linked documentation pages.
Using these, you can get your list'o'files and build your HTML.

A: Very simple example of class.
class MyFiles {

    public static function files($path) {
        // Logic used to get the files found at path and return an array
        // Just use the built-in functionality of PHP
        $filesArray = array();

        if (!is_dir($path)) {
            return $filesArray;
        }

        $dir  = opendir($path);
        while (false !== ($filename = readdir($dir))) {
            if (!is_dir($filename)) {
                $filesArray[] = $filename;
            }
        }

        return $filesArray;
    }

    public static function table($path) {
        $files = self::files($path);
        $c_files = count($files);

        if ($c_files == 0) {
            return "

No files at $path

";
        }

        $table = "";
        for ($i = 0; $i < $c_files; $i++) {
            $table .= "
{$files[$i]}
";
        }

        return "

$table

";
    }

}

$fileTable = MyFiles::table('/my/path/with/files');

A: I think it is good to create a class for such functionaliteit, because you can much better predict its behaviour and work around subtle changes in PHP over different versions. Also, you can create different classes to read lists of files from other locations like a database or csv file.
In this case, I extended a renderer class from the base class, because I figured the rendering shouldn't be part of the base class. In fact, it might be better to create a separate class for this that uses any descendant of Folder to render it. But I'll leave it to you to figure out what suits you best.
<?
class Folder
{
    private $folder = '';
    public function getFolder()
    {
        return $this->folder;
    }
    protected function setFolder($value)
    {
        $this->folder = (string)$folder;
    }

    public __construct($folder)
    {
        this->setFolder($folder);
    }

    public function readFileNames()
    {
        $folder = (string)$this->getFolder();
        if ($folder === '')
        {
            throw new exception("Folder name is empty");
        }
        if (is_dir($folder) !== true)
        {
            throw new exception("'$folder' is not a directory.");
        }
        $dir = @opendir($this->folder);
        if ($dir === false)
        {
            throw new exception("Cannot open directory '$folder'.");
        }
        $result = array();
        while (false !== ($fileName = readdir($dir)))
        {
            if (is_file($fileName) === true)
            {
                $result[] = $fileName;
            }
        }
        return $result;
    }

    public function readFiles()
    {
        $fileNames = $this->readFileNames();
        $fileNames = array_flip($fileNames);
        foreach($fileNames as $fileName=>&$fileContents)
        {
            if (false === ($file = @readFile($fileName)))
            {
                $fileContents = null;
            }
            else
            {
                $fileContents = $file;
            }
        }
    }
}

class FolderTableRenderer extends Folder
{
    public function renderTable()
    {
?>

File name

<?
        foreach ($this->readFileNames() as $fileName)
        {
?>

<?=$fileName?>

<?
        }
?>

<?
    }
}


text:
Q: Не открывается проект в NetBeans
В общем, хочу я создать лаунчер для своего проекта в майнкрафт. Хочу запустить свой проект, и после этого должен открыться лаунчер, но он не открывается. Внизу мне прописывается причина этого(красным выделил). Переводил это дело в интернете, но не особо понял, в чём проблема.  Может быть кто-то знает и понимает это? Помогите, пожалуйста

A: При загрузке у вас возникает ошибка NullPointerException и возникает она на 31 строке файла MainClass.jave. Это значит, что на этой строке происходит манипуляции с объектом, который равен null.
На этой строке у вас написано
stream.close();

99%, что stream равен null. Соответственно попытка вызвать метод у null приводит к исключению.
Переменная stream у вас инициализируется на 19 строке
InputStream stream = Starter.class.getResourceAsStream("/net/launcher/theme/favivon.png");

В документации к методу getResourceAsStream() сказано

Returns:
  A InputStream object or null if no resource with this name is found

Или в переводе

Возвращает:
  Объект InputStream или null если ресурс с таким именем не найден

Вот вам и ответ.

*

*Программа не нашла ресурс /net/launcher/theme/favivon.png

*Вы сразу не проверили полученный результат

*Вы получили NullPointerException когда попытались обратиться к объекту


text:
Q: Creating Bar Chart - Adding Rows I am trying to create a bar chart from a google spreadsheet. I do not want to manually add each column and row so it seems that this example should work and automate that process with the for loop.
The example below is from https://sites.google.com/site/appsscripttutorial/chart-services/bar-chart
The error shows "Row has too many cells. Should be at most as the columns number."
function doGet(){
  //Get the data from spreadsheet
  ssID ='SpreadsheetID';//Change it to yours
  var SS = SpreadsheetApp.openById('ssID');
  var sheet = SS.getSheets()[0];
  var data = sheet.getRange('A1:G7').getValues();

  //Build data table
  var dataTable = Charts.newDataTable();

  //Add Column types
  dataTable.addColumn(Charts.ColumnType.STRING, data[0][0]);
  for(var i=1; i<data[0].length-1; i++){
    dataTable.addColumn(Charts.ColumnType.NUMBER, data[0][i]);
  }

  //Add rows
  for(var j=1; j<data.length; j++){
    dataTable.addRow(data[j]);
    Logger.log(data[j])
  }

  //Create and build chart
  var chart = Charts.newBarChart()
      .setDataTable(dataTable)
      .setTitle("Sales by store")
      .build();

  var app = UiApp.createApplication().setTitle("AST Chart");
  app.add(chart)
  return app;
}

A: You've selected a range 'A1:G7'. That's 7 columns by 7 rows. Now, you start building your dataTable by adding columns.
1: dataTable.addColumn(Charts.ColumnType.STRING, data[0][0]);
2-6: for(var i=1; i<data[0].length-1; i++)
See, data[0].length is equal to 7, and the loop goes through 1, 2, 3, 4, 5, all numbers less than 6.
Then when you start adding data rows, there aren't enough columns in the dataTable, and you get the error you've seen. (It is pretty clear now, isn't it?)
To fix it, change your loop upper bound.
//Add Column types
dataTable.addColumn(Charts.ColumnType.STRING, data[0][0]);
for(var i=1; i<data[0].length; i++) {
  dataTable.addColumn(Charts.ColumnType.NUMBER,data[0][i]);
}

... or loop over all columns, making type decisions inside the loop...
//Add Column types
for(var i=0; i<data[0].length; i++) {
  if (i == 0) {
    dataTable.addColumn(Charts.ColumnType.STRING,data[0][i]);
  }
  else {
    dataTable.addColumn(Charts.ColumnType.NUMBER,data[0][i]);
  }
}

... or same thing, but using the ternary operator to reduce the code...
//Add Column types
for(var i=0; i<data[0].length; i++){
  dataTable.addColumn(
     i==0 ? Charts.ColumnType.STRING : Charts.ColumnType.NUMBER,
     data[0][i]);
}

There are many other ways you could do this, but whichever you choose, just make sure you cover the full range of values that you need to.


text:
Q: Compiling (for prett-printing) a query that has a PostgreSQL `interval` bind parameter Please see the code for making a PG query like
SELECT generate_series('2022-11-04T17:58:10.087517'::timestamp, '2022-11-11T17:58:10.087526'::timestamp, '1 day') AS ts
from datetime import datetime, timedelta

import sqlalchemy as sa
from sqlalchemy import TypeDecorator, TIMESTAMP as SA_TIMESTAMP
from sqlalchemy.dialects import postgresql

class TIMESTAMP(TypeDecorator):
    impl = SA_TIMESTAMP

    def process_literal_param(self, value, dialect):
        if isinstance(value, unicode):
            return value
        else:
            return value.strftime("'%Y-%m-%d %H:%M:%S.%f'")

_period_start_param = sa.bindparam("period_start", type_=TIMESTAMP)
_period_end_param = sa.bindparam("period_end", type_=TIMESTAMP)
_period_unit_param = sa.bindparam("period_unit")

_series = sa.func.generate_series(_period_start_param, _period_end_param, _period_unit_param)
_select_series = sa.select(_series.label("ts"))

params = {
    _period_start_param.key: datetime.utcnow() - timedelta(days=7),
    _period_end_param.key: datetime.utcnow(),
    _period_unit_param.key: "1 day"
}

pretty_sql_query = _select_series.params(params).compile(dialect=postgresql.dialect(),
                                                        compile_kwargs={"literal_binds": True})
print(unicode(pretty_sql_query))

produces next error:
...
runtime/lib/python2.7/site-packages/sqlalchemy/sql/compiler.py:2497: in render_literal_bindparam
    return self.render_literal_value(value, bindparam.type)
runtime/lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/base.py:2290: in render_literal_value
    value = super(PGCompiler, self).render_literal_value(value, type_)
runtime/lib/python2.7/site-packages/sqlalchemy/sql/compiler.py:2512: in render_literal_value
    return processor(value)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

value = '1 day'

    def process(value):
        raise exc.CompileError(
>           "Don't know how to render literal SQL value: %r" % value
        )
E       CompileError: Don't know how to render literal SQL value: u'1 day'

value      = '1 day'

runtime/lib/python2.7/site-packages/sqlalchemy/sql/sqltypes.py:3216: CompileError

How can I render the _period_unit_param?
UPDATE:
As a temporary solution, I defined a "custom" NullType that processes all literal values as a simple quoted text:
class _IntervalType(NullType):
    def literal_processor(self, dialect):
        def process(value):
            return "\'{}\'".format(value)

        return process

_period_unit_param = sa.bindparam("period_unit", type_=_IntervalType)

It seems to work but smells a bit fishy.


text:
Q: Determine cluster directory from Postgres service Is it possible to determine the cluster directory being used by a Postgres server, from the server itself -- i.e. the service, (under Windows) was started by something like:
C:\foo\postgres.exe -D "D:\emr\data"

Is there a SELECT query or function one can make to the running server to retrieve the value D:\emr\data?

A: SELECT setting FROM pg_settings WHERE name = 'data_directory'

A: (For completeness)
And even shorter:
SHOW data_directory;


text:
Q: bad substitution ${line ::-1} i have this code and while it works perfect but i have an error in line virusarray[i]=${line ::-1}

testFile.sh: line 57: ${line ::-1}: bad substitution

this kind of error. Everyone who knows?
declare -a virusarray
i=0

while read line; do

#Reading each line by omitting backslash escape
virusarray[i]=${line ::-1}
# echo $line
((i=i+1))
done < $virusfile

A: Yes, it is indeed invalid syntax. Take out the space:
virusarray[i]=${line::-1}

...or even better, rewrite your loop entirely. Assuming you're using a bash release too old to support mapfile or readarray:
while IFS= read -r line; do
  virusarray+=( "${line%?}" )
done <virusfile

${line%?} serves the same purpose as ${line::-1} (dropping the last character), but does so more portably, because it doesn't require bash-only extensions to shell syntax.


text:
Q: How can I group a set split by change in a field with respect to an order? I have a set of records.
ID Value
1 a
2 b
3 b
4 b
5 a
6 a
7 b
8 b

And I would like to group them like so.
MIN(ID) MAX(ID) Value
1 1 a
2 4 b
5 6 a
7 8 b

I'm vaguely aware of oracle over() analytical function which looks to be the right direction, but I don't know what this problem is called much less how to solve it.

A: Probably an easier way, but this may help to start. I ran it on Postgres, but should work (maybe with a minor tweak) on Oracle. The inner most query puts the previous value on each row. We can use that to detect a grouping change (when value does not equal previous value). Every time there is a group change, we flag it with a "1". Sum these group changes and we now have a group id which increments every time there is a value change. Then we can perform our normal group by function.
create table x(id int, value varchar(1));

insert into x values(1, 'a');
insert into x values(2, 'b');
insert into x values(3, 'b');
insert into x values(4, 'b');
insert into x values(5, 'a');
insert into x values(6, 'a');
insert into x values(7, 'b');
insert into x values(8, 'b');

SELECT MIN(id), MAX(id), value
  FROM ( SELECT id
               ,value
               ,previous_value
               ,SUM( CASE WHEN value = previous_value THEN 0 ELSE 1 END ) OVER(ORDER BY id) AS group_id
           FROM ( SELECT id
                        ,value
                        ,COALESCE( LAG(value) OVER(ORDER BY id), value )  previous_value
                    FROM x
                    ORDER BY id
                ) y
       ) z
  GROUP BY group_id, value
  ORDER BY 1, 2;

 min | max | value
-----+-----+-------
   1 |   1 | a
   2 |   4 | b
   5 |   6 | a
   7 |   8 | b
(4 rows)


text:
Q: How can I rate Apple's Podcast.app in the iTunes App Store? This is very odd and I just noticed this for the first time, but it seems, apple is not allowing ratings from customers for its own Postcast.app.
The entire section "Ratings and reviews" is absent for the podcast app:
https://itunes.apple.com/app/podcasts/id525463029
Other apps do have ratings and reviews. Below two screenshots: 1. showing podcasts app without the section in question and 2. showing soundcloud (as example) with the "Ratings and review" section.
I find this disturbing and unsettling. Apple does not allow ratings for it's own software or what? Can someone enlighten me about what's happening here?

A: From what I have been able to gather, it looks like the Podcasts App and the iBooks app are the only apps made by Apple that don't have a ratings button. I am guessing since the Podcasts app (and iBooks) are automatically installed on your iPhone or iPad in iOS 8, and are also installable from the app store on earlier versions of iOS, they most likely just omitted it because you can't delete them in iOS 8. Just like you can't rate Apps like Messages or Phone on your iPhone.


text:
Q: Reuse code first model between different clients I have a code first model that I'm using in a project. But now I have other projects that are going to use the same model. Of course, I don't want to duplicate the model in all projects so the idea is to encapsulate the model in a separate assembly. So far so good, until you also want to "enhance " the model for some project like adding a ctor with some specific paramaters.
Using partial classes doesn't work as it needs to be part of the same assembly. Using inheritance doesn't really work either as entities of the model has ICollection to other entities, so how to make this work ? Am i going in the right direction ?
Not sure I'm very clear, so please be patient ;-)

A: If you need to have shared model, you really need to place it in separate assembly and this assembly must contain everything you need in all projects. So if you need additional constructor you must add that constructor to the shared assembly. If you don't want to affect other projects dependent on that assembly you must increment the version of the shared assembly (and use strong name).


text:
Q: php preg_replace need help I have created a function to search through strings and replace keywords in those strings with links. I am using
preg_replace('/\b(?<!=")(?<!=\')(?<!=)(?<!=")(?<!>)(?<!>)' . $keyword . '(?!</a)(?!</a)\b', $newString, $row);

which is working as expected. The only issue is that if someone had a link like this
Luxury Automobile sales

Automobile being our $keyword in this example.
It would end up looking like
Luxury Automobile Sales

You can understand my frustration.
Not being confident in regex I thought I would ask if anyone here would know a solution.
Thanks!

A: How about a proper HTML parser like DOMDocument?
$html = 'Luxury Automobile sales';
$dom  = new DomDocument;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('a');
foreach ($nodes as $node)
{
  $node->nodeValue = str_replace('Automobile', 'Cars', $node->nodeValue);
  echo simplexml_import_dom($node)->asXML();
}

Is not a problem to get element attribute too
foreach ($nodes as $node)
{
  $attr = $node->getAttributeNode('href');
  $attr->value = str_replace('Automobile', 'keyword', $attr->value);
  echo simplexml_import_dom($node)->asXML();
}


text:
Q: How do I update the parent JSON from child I'm writing a React code in which I need to upload a CSV file, on click of a button, Create a new column, once I update a value there, update the JSON passed from parent to child. Currently, I'm able to upload files, create a column, edit the data and see the updated data in the child component.
However, I'm unable to understand how can I send it back to the parent. I should be able to see the updated date when I click Get Final Data button. How can I send back data from child to parent?
Here is my code:
LoadFiles.js (parent)
import { useEffect, useState } from "react";
import RenderTable from "./RenderTable";
import Tab from "@mui/material/Tab";
import TabContext from "@mui/lab/TabContext";
import TabList from "@mui/lab/TabList";
import TabPanel from "@mui/lab/TabPanel";

const Load = () => {
  const [files, setFiles] = useState([]);
  const [allData, setAllData] = useState([]);
  const [isDone, setIsDone] = useState(false);
  const [processingData, setProcessingData] = useState(false);
  const [value, setValue] = useState("1");
  const [csvArray, setCsvArray] = useState([]);

  const handleTabChange = (event, newValue) => {
    setValue(newValue);
  };

  const processCSV = (str, fileName, delim = ",") => {
    const headers = str.slice(0, str.indexOf("\r\n")).split(delim);
    const rows = str.slice(str.indexOf("\r\n") + 1, str.length).split("\r\n");
    let nArray = rows.map((row) => {
      const values = row.split(delim);
      const eachObj = headers.reduce((obj, header, i) => {
        obj[header] = values[i];
        return obj;
      }, {});
      return eachObj;
    });
    createKeys(nArray, fileName);
  };

  const createKeys = async (data, fileName) => {
    const dataToSet = {
      fileName: fileName,
      keys: Object.keys(data.length ? data[0] : {}),
      values: data.filter((o) => Object.keys(o).length)
    };
    console.log(JSON.stringify(dataToSet));
    setAllData((prev) => [...prev, dataToSet]);
  };

  useEffect(() => {
    if (
      (files.length >= 1 && files.length === allData.length && !isDone) ||
      processingData
    ) {
      setIsDone(true);
    }
  }, [allData, isDone, files, processingData]);

  useEffect(() => {
    console.log(JSON.stringify(csvArray));
  }, [csvArray]);

  const handleUpload = (e) => {
    Array.from(files).forEach((file) => {
      const currFile = file;
      const reader = new FileReader();
      reader.onload = (e) => {
        const text = e.target.result;
        processCSV(text, file.name.split(".").slice(0, -1).join("."));
      };
      reader.readAsText(currFile);
    });
  };
  const handleChange = (e) => {
    e.preventDefault();
    setFiles(e.target.files);
  };
  const processData = (e) => {
    var currData = allData;
    setAllData([]);
    currData.forEach((item) => {
      let rowWithSum = item.values.map((item1) => {
        let newCol = item1["Rank"];
        return {
          ...item1,
          "New Col": newCol
        };
      });
      createKeys(rowWithSum, item.fileName);
      setProcessingData(true);
    });
  };

  const getLink = () => {
    console.log(JSON.stringify(allData));
  };

  return (

        <form id="csv-form">
          <input
            type="file"
            accept=".csv"
            id="csvFile"
            multiple
            onChange={(e) => handleChange(e)}
          />
          <button
            onClick={(e) => {
              e.preventDefault();
              handleUpload();
            }}
          >
            Upload your csv
          </button>
        </form>
        <button
          className="processData"
          onClick={(e) => {
            e.preventDefault();
            processData();
          }}
        >
          Processdata
        </button>
        <button
          onClick={(e) => {
            e.preventDefault();
            getLink();
          }}
        >
          Get Final Data
        </button>

      {isDone && allData.length >= 1 && (
        <TabContext value={value}>
          <TabList onChange={handleTabChange}>
            {files.length >= 1 &&
              [...allData].map((item1, idx) => (
                <Tab label={item1.fileName} value={`${idx + 1}`} />
              ))}
          </TabList>
          {files.length >= 1 &&
            [...allData].map((item1, idx) => (
              <TabPanel value={`${idx + 1}`}>
                <RenderTable
                  keys={item1.keys}
                  csvArray={item1.values}
                  setCsvArray={setCsvArray}
                ></RenderTable>
              </TabPanel>
            ))}
        </TabContext>
      )}

  );
};

export default Load;

RenderTable.js (child)
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { useEffect, useState } from "react";

const RenderTable = ({ csvArray, setCsvArray, keys }) => {
  const [csvArrayState, setCsvArrayState] = useState(() => csvArray);

  const handleBlur = (e) => {
    e.currentTarget.classList.add("noBorder");
    e.currentTarget.classList.remove("border");
    setCsvArray(csvArrayState);
  };

  useEffect(() => {
    setCsvArrayState(csvArray);
  }, [csvArray]);

  const handleChange = (e) => {
    e.preventDefault();
    e.currentTarget.readOnly = false;
    e.currentTarget.classList.remove("noBorder");
    e.currentTarget.classList.add("border");
  };

  return (
    <TableContainer component={Paper}>

        <TableHead>
          <TableRow>
            {keys.map((item, idx) => (
              <TableCell key={idx}>{item}</TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {csvArray.map((item, i) => (
            <TableRow>
              {keys.map((key, idx) =>
                key === "New Col" ? (
                  <TableCell>
                    <input
                      class="noBorder"
                      type="true"
                      readOnly="true"
                      value={csvArrayState[i]["New Col"]}
                      onChange={(e) => {
                        const updatedRankFields = csvArrayState.map(
                          (r, rIdx) => {
                            if (rIdx === i) {
                              return { ...r, "New Col": e.target.value };
                            } else {
                              return r;
                            }
                          }
                        );
                        setCsvArrayState(updatedRankFields);
                      }}
                      onBlur={(e) => handleBlur(e)}
                      onClick={(e) => handleChange(e)}
                    ></input>
                  </TableCell>
                ) : (
                  <TableCell> {item[key]} </TableCell>
                )
              )}
            </TableRow>
          ))}
        </TableBody>

    </TableContainer>
  );
};

export default RenderTable;

How can I do this? Here is codesandbox link of the same. I've added the files under /Files.


text:
Q: Why does the 741 op-amp saturate to the top rail when inputs both grounded? I created the following circuit in MultiSim:

It shows a typical 741 op-amp with voltage rails connected to +/-5V and both inputs grounded. With (for all intents and purposes) equal voltages at the inputs, I would expect the output voltage either to be 0V, or very close to it (perhaps ~800mV or less).
Instead the op-amp saturates at the positive rail (or at least maximum Vout). Why not the negative rail? Why not 0V?
Would connecting pins 1 or 5 have an effect?
Regards

A: You're also not taking into account the input offset voltage. This is a factor present in all non-ideal op-amps, and can be modelled as such:

The 741 series of op-amp may require you to "null" the input offset voltage, so even if you apply an identical voltage to both terminals, without any feedback or nulling on the terminals, I'd expect it to rail in one direction or the other.
Remember, op-amps have very very high open-loop gain (106dB in this case or about 200,000). The worst case input offset voltage for this op-amp is 6mV, or even 7.5mV across the whole temperature range. This offset voltage will be amplified by the open-loop gain of the amplifier, yielding an output voltage of 1200V! Obviously the op-amp cannot output this, so it simply rails in one direction, or the other.
As a general rule, unless you're using them as comparators, op-amps aren't usually used in open-loop configurations. The high open-loop gain serves the purpose of linearizing the closed-loop gain through negative feedback (but this is probably above the scope of this answer).
image credit:
https://www.allaboutcircuits.com/textbook/semiconductors/chpt-8/op-amp-practical-considerations/


text:
Q: Why traced sql statement has invalid format? On the laravel 9 site, I have some debugging tool in the boot method of app/Providers/AppServiceProvider.php, like
$str = $query->sql;
\Log::info(' -1 $query->sql::');
\Log::info($query->sql);
$str = str_replace('?', '%s', $str);
$str = sprintf($str, ...$bindings);

\Log::info(' -2 $sql::');
\Log::info($str);

and running request :
$docs = Doc::getById(1)
    ->where('is_passed', false)
    ->where('user_name', 'like', '%John Doe%')
    ->get();

I can see SQL statement:
SELECT *
  FROM `docs`
  WHERE `docs`.`id` = 1     AND `is_passed` =      AND `user_name` like %John Doe%

When I try to copypaste it into SQL editor I got 2 errors:
`is_passed` =

and
`user_name` like %John Doe%

is "0" and '*' are not used in $str var.
How that can be fixed?
Thanks in advance!


text:
Q: connecting python to sql server using pyodbc How to connect python to SQL Server using pyodbc until now  I wrote the below script but the system crash and display error:
I tried to connect the script to the localhost sql server and  i had a successful connection but when I tried on the server on the same network it did crash
code:
import pyodbc
import pandas as pd

conn = pyodbc.connect(
                    ENGINE='sql_server.pyodbc',
                    driver='SQL Server',
                    NAME='testDB',
                    SERVER ='WIN-CMUH9TBNL53',
                    DSN='pythonDSN',
                    PORT='1433',
                    UID='test',
                    PWD="test",

                    )
cursor = conn.cursor()
sql_query=pd.read_sql_query('select * from testDB.dbo.t1',conn)
print(sql_query)
print(type(sql_query))

error:
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)')


text:
Q: Textbox autocomplete source With a combobox in winforms I am able to add items that can be a custom class and what is shown in the combo is the result of the ToString() method of that class
I would ideally like to have similar behaviour with the autocomplete of a TextBox, but it seems to me that you must provide an AutoCompleteStringCollection for this. Is anyone aware of a way I can associate an int value with each string in the AutoCompleteSource for the textbox?
Edit - I cannot simply look up for the int based upon the selected string because they may be strings in the textbox autocomplete that are the same

A: Here is a possible solution; a bit of a hack, but it might help you out.
If you add the numbers to the string in a way that is both acceptable to the users and easily reconizable/removeable you can test for it in the KeyUp event, extract the index and clean up the Text.
So a string could look like this
New York City          <<01>>

and you wouldn't have much trouble to get at the index and removing the markup..
Look at this answer by Hans who deals with detecting the (fake) KeyDown that gets fired. You can adapt this to deal with the KeyUp so you won't interfere with the normal editing.
But to reiterate, this makes no sense, if for the choice of the user the strings have a meaning and not their, say, position..


text:
Q: Array - get the character position of the word on the line number I have an arrayList and it holds the contents of a file I read in. I just need help figuring out to get it to display the position of each word on that line for each line. (later I am to write a function that ignores the // and everything that follows that.
Desired output:
Line 1, Char/Position 1, Program
Line 1, Position 2 , Twenty:
Line 2, Position 3, int
and so on..
current out put reads:
Line Number: 0 line reads:  // This program should print the number 20.
Line Number: 1 line reads:  program Twenty:
Line Number: 2 line reads:    int a;
Line Number: 3 line reads:    int b;
Code:
public class Lex_functions {

    ArrayList < String > list = new ArrayList < String > ();
    int lineNum = 0;
    int charNum = 0;
    int totalLines = 0;

    void readFile() throws FileNotFoundException {
        File f = new File("ab.txt");
        FileReader fr = null;
        try {
            fr = new FileReader(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }
        BufferedReader infile = new BufferedReader(fr);
        String line = "";
        boolean done = false;
        try {
            while (!done) {
                line = infile.readLine();
                if (line == null) {
                    done = true;
                } else {
                    list.add(line);
                }
            }
            infile.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        for (String item: list) {
            //System.out.println(item);

            while (lineNum <= (list.size() - 1)) {

                System.out.println("Line Number: " + lineNum + " " + "line reads: " + " " + list.get(lineNum));
                //  System.out.println(list.size());
                lineNum++;
                charNum++;

                //System.out.println();

            }

            // System.out.println(list.indexOf(4));
            //System.out.println(list[0]);

            // System.out.println("Index of Program: "+list.get(2));
        } //end readfelil
    }

}

A: So, I'm not exactly sure of what you want to do because the way you displayed the wanted output is not readable, and you did not give us the content of the file to display.
But if I understood well, if you have the following array :
{"Hello world"}, {"Have a good day"}
what you want to display should be :

*

*Word : Hello, Line number : 0, Word number 0

*Word : world,  Line number : 0, Word number 1

*Word : Have, Line number : 1, Word number 0

*Word : a, Line number : 1, Word number 1

*Word : good, Line number : 1, Word number 2

*Word : day, Line number : 1, Word number 3

So, to begin with there is an easy way to read all lines of a file into an Array List :
/**
     * Read a file and put all its content into a String List
     * @param fileName file path
     * @return
     */
    public static ArrayList<String> readFileInList(String fileName){
        List<String> lines = Collections.emptyList();
        try {
            lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        } catch (IOException e) {
            // do something
            e.printStackTrace();
        }
        return (ArrayList<String>) lines;
    }

Next is the way you do your loop...
for (String item: list) {
            //System.out.println(item);

            while (lineNum <= (list.size() - 1)) {

                System.out.println("Line Number: " + lineNum + " " + "line reads: " + " " + list.get(lineNum));
                //  System.out.println(list.size());
                lineNum++;
                charNum++;

            }

        }

What you do is essentially imbricating 2 loops that go through the same items. Facts are that a String is a list of char, so what you want to do is iterating through your String.
A String can also be divided into substrings with regex, creating a list of words :
/**
     * Parse the string (the line) into words. All spaces and dots are kept.
     *
 The following string
     *

     *
"Hello, my name is Blanc! I'm a student. Can you help me? Thanks."

     *

     *  will be parsed as :
     *
 "|Hello, |my |name |is |Blanc!| |I'm |a |student.| |Can |you |help |me?| |Thanks.|"
     * @param input the string to parse
     * @return the words of the input as an array
     * @see String#split(String)
     */
    public static String[] parseInputToWordsArray(String input) {
        return input.split("(?<= )|(?<=\\.)|(?<=\\?)|(?<=!)");
    }

Next you want to go through the lines of your array and their list of words to print the output (not tested but should work) :
ArrayList <String> list = new ArrayList();
        int lineNum;

        for (lineNum = 0; lineNum<list.size(); lineNum++) {
            int wordNum;
            String[] word = parseInputToWordsArray(list.get(lineNum));
            for(wordNum = 0; wordNum < word.length; wordNum++){
                System.out.println("Word : "+word[wordNum]+", Line Number : " + lineNum + ", Word Number: " + " " + wordNum);
            }

        }

Hope it could help