text:
Q: Error Updating Python3 pip AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms' I'm having an error when installing/updating any pip module in python3. Purging and reinstalling pip and every package I can thing of hasn't helped. Here's the error that I get in response to running python -m pip install --upgrade pip specifically (but the error is the same for attempting to install or update any pip module):
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3/dist-packages/pip/__main__.py", line 16, in <module>
    from pip._internal.cli.main import main as _main  # isort:skip # noqa
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/cmdoptions.py", line 24, in <module>
    from pip._internal.exceptions import CommandError
  File "/usr/lib/python3/dist-packages/pip/_internal/exceptions.py", line 10, in <module>
    from pip._vendor.six import iteritems
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 65, in <module>
    vendored("cachecontrol")
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored
    __import__(modulename, globals(), locals(), level=0)
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/CacheControl-0.12.6-py2.py3-none-any.whl/cachecontrol/__init__.py", line 9, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/CacheControl-0.12.6-py2.py3-none-any.whl/cachecontrol/wrapper.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/CacheControl-0.12.6-py2.py3-none-any.whl/cachecontrol/adapter.py", line 5, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/requests-2.22.0-py2.py3-none-any.whl/requests/__init__.py", line 95, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/urllib3-1.25.8-py2.py3-none-any.whl/urllib3/contrib/pyopenssl.py", line 46, in <module>
  File "/home/patrick/.local/lib/python3.8/site-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/home/patrick/.local/lib/python3.8/site-packages/OpenSSL/crypto.py", line 3268, in <module>
    _lib.OpenSSL_add_all_algorithms()
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 72, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 32, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 12, in <module>
    import os, glob, subprocess, os.path, time, pwd, sys, requests_unixsocket
  File "/usr/lib/python3/dist-packages/requests_unixsocket/__init__.py", line 1, in <module>
    import requests
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/requests-2.22.0-py2.py3-none-any.whl/requests/__init__.py", line 95, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/urllib3-1.25.8-py2.py3-none-any.whl/urllib3/contrib/pyopenssl.py", line 46, in <module>
  File "/home/patrick/.local/lib/python3.8/site-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/home/patrick/.local/lib/python3.8/site-packages/OpenSSL/crypto.py", line 3268, in <module>
    _lib.OpenSSL_add_all_algorithms()
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'

Original exception was:
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3/dist-packages/pip/__main__.py", line 16, in <module>
    from pip._internal.cli.main import main as _main  # isort:skip # noqa
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/cmdoptions.py", line 24, in <module>
    from pip._internal.exceptions import CommandError
  File "/usr/lib/python3/dist-packages/pip/_internal/exceptions.py", line 10, in <module>
    from pip._vendor.six import iteritems
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 65, in <module>
    vendored("cachecontrol")
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored
    __import__(modulename, globals(), locals(), level=0)
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/CacheControl-0.12.6-py2.py3-none-any.whl/cachecontrol/__init__.py", line 9, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/CacheControl-0.12.6-py2.py3-none-any.whl/cachecontrol/wrapper.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/CacheControl-0.12.6-py2.py3-none-any.whl/cachecontrol/adapter.py", line 5, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/requests-2.22.0-py2.py3-none-any.whl/requests/__init__.py", line 95, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/urllib3-1.25.8-py2.py3-none-any.whl/urllib3/contrib/pyopenssl.py", line 46, in <module>
  File "/home/patrick/.local/lib/python3.8/site-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/home/patrick/.local/lib/python3.8/site-packages/OpenSSL/crypto.py", line 3268, in <module>
    _lib.OpenSSL_add_all_algorithms()
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'

I'm running Ubuntu 20.04 in WSL. Python openssl is already installed.
sudo apt install python3-openssl
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-openssl is already the newest version (19.0.0-1build1).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

My assumption is that I need to re-install some stuff, but I'm not sure what. I've tried the obvious stuff like python3-openssl, libssl-dev, libffi-dev, and python3-pip itself and python3 alltogether.

A: As version 39.0.0 presented this bug, downgrading the cryptography package solves this, without purging or touching your OS.
pip install cryptography==38.0.4 to downgrade from 39.0.0 which presented this error
EDIT per @thomas
The error is a result of incompatibility between cryptography and pyopenssl, so if possible, also upgrading to openssl>22.1.0 should work

A: I figured it out. What I needed to do was to purge the apps, and delete ~/.local/lib/python3.8. This was the step that I'd been missing.
So in the end, the fix was:
sudo apt purge python3 python3-pip python3-openssl
rm -rf ~/.local/lib/python3.8
sudo apt install libssl-dev libffi-dev python3 python3-pip python3-openssl

Then, I could run python -m pip install --upgrade pip without error.
This solution is only suitable for Ubuntu in WSL.
It's what I run, but follow up for other users has confirmed that it can completely break any installed desktop environments.

A: Another solution would be to simply pip remove the pyOpenSSL and then install it again:
pip uninstall pyOpenSSL
pip install pyOpenSSL


text:
Q: Rendering to an offscreen view and saving a screenshot There are a variety of questions about saving an offscreen view to a bitmap, and I've followed all to no avail, which is why I don't think this is a  duplicate of either.
Background
My app offers two different views of the same data. Both of these views are presented using custom views that work as designed (One uses a SurfaceView, which is a pain in the butt for this kind of thing). There is a requirement to share this data as an image that includes both views (Only one view is visible to the user at a time, they can switch between the views). For an improved user experience and so that the same image is generated for the same data regardless of the device used, this data is to be contained in a bitmap (well, PNG) of fixed size, every time.
Method
In order to accomplish the above, I've

*

*Created fragment_screenshot_generator.xml layout below: (A horizontal LinearLayout with width and height set to match_parent that contains 2 FrameLayouts each with a height of match_parent and layout_weight of 1. Each takes half the screen. For testing purposes they have a translucent background (red & green respectively)

*Created a DialogFragment (progress dialog) that is supposed to do this work in the background and automatically dismiss once the screenshot is saved to file (returning the file to the parent fragment)

*While the dialog is being created, I inflate fragment_screenshot_generator.xml and setup the two view types in each of the FrameLayouts. The exact same code is used here as what generates the original user visible views.

*The View is then rendered onto a canvas, backed by a bitmap

*The bitmap is compressed to a file

Problem
Nothing but the view background is rendered onto the bitmap. I suspect I'm missing a call somewhere to tell the root of fragment_screenshot_generator.xml that "it's all good" so that the views inside it would render. I've tried posting to the layout root, but it's very unpredictable, takes very long at times, and still draws nothing but transparency. Do I have to attach this layout to a window? Can I attach it to the current window without showing it? Do you see anything missing in my code?
Notes
I've tried

*

*Enabling drawing cache before the draw call. No fix. It's deprecated anyway.

*Generating the bitmap directly from the view's draw cache. No fix. Throws a NullPointerException because the getDrawingCache method returns a null. Still deprecated anyway.

*Rendering the exact same view onscreen (as a part of the dialog layout) and saving that to bitmap. It works, but the SurfaceView portion is empty. This is expected because SurfaceView is essentially a 'hole'. I suspect the PixelCopy API won't suffer from this.

*I've removed background execution from the code below for simplicity. So don't yell at me for running this all on the main thread! :)

Code
fragment_screenshot_generator.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="horizontal">

    <FrameLayout
        android:id="@+id/view_1"
        android:background="#4f00"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <FrameLayout
        android:id="@+id/view_2"
        android:background="#40f0"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

ScreenshotGeneratorDialogFragment#onCreateDialog
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    viewModel = ViewModelProviders.of(activity!!).get(DetailViewModel::class.java)

    val parameter1 = viewModel.dataTypeOne.value!!.parameter1
    val parameter2 = viewModel.dataTypeOne.value!!.parameter2

    screenshotView = View.inflate(context, R.layout.fragment_screenshot_generator, null).apply {
        measure(View.MeasureSpec.makeMeasureSpec(SCREENSHOT_WIDTH, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(SCREENSHOT_HEIGHT, View.MeasureSpec.EXACTLY))
        layout(0, 0, measuredWidth, measuredHeight)

        setupViewTypeOne(findViewById(R.id.view_1)!!, parameter1, parameter2)
        setupViewTypeTwo(findViewById(R.id.view_2)!!, parameter1, parameter2, viewModel.plotData.value)
        layout(0, 0, measuredWidth, measuredHeight)
    }

    dialogView = View.inflate(context, R.layout.dialog_screenshot_generator, null).apply {
        findViewById<TextView>(R.id.progress_label)!!.setText(R.string.preparing_screenshots)
    }

    val dialog = AlertDialog.Builder(context!!)
            .setView(dialogView)
            .create()

    dialog.setOnShowListener { capture() }

    return dialog
}

ScreenshotGeneratorDialogFragment#capture
private fun capture():File {
    var bitmap = Bitmap.createBitmap(screenshotView.measuredWidth, screenshotView.measuredHeight, Bitmap.Config.ARGB_8888)
    var canvas = Canvas(bitmap)
    canvas.drawColor(0xffffffff.toInt())
    screenshotView.draw(canvas)

    // Saving to SDcard for testing. This will move to cache dir.
    val file = File.createTempFile("share-", ".png", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))

    file.outputStream().use {
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, it)
    }

    return file
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Primefaces datatable selected row not working using viewscope I am using JSF 2.0 and Primefaces 3.4.2, I have a datatable populated using lazy load.
When I view scope for managedbean, then datatable selectedRow gives null pointer exception.
If I use session scope then I could get selectedRow in managedbean.
I am using CDI Spring annotations for specifying scope. I have used this method to create view scope.
Update 1
I have noticed another thing is using view scope when I paginate to second page and then comes back to first page, then I could get the selectedRow. If I select a row without paginating then I get null pointer exception.
JSF Page
<p:dataTable id="dataTable" var="req" lazy="true" value="#{emp.lazyModel}"
                paginator="true" rows="10"
                             selection="#{emp.selectedRequest}"
                            selectionMode="single">
          <p:ajax event="rowSelect" listener="#{emp.onRowSelect}" />

ManagedBean
@Named("emp")
@Scope("view")
public class EmployeesManagedBean implements Serializable {

    @PostConstruct
    public void init() {
        initTable();
    }

    private void initTable() {
        lazyModel = new LazyRequestDataModel(requestList, requestService);
    }

    public LazyDataModel<Employee> getLazyModel() {
        return lazyModel;

    }

I am getting nullpointer exception at this line in onRowSelect method
 Emp emp = (Emp) event.getObject());
 System.out.println(emp.getEmpNo() );

Full error stacktrace
java.lang.NullPointerException
    at net.test.managed.bean.RequestManagedBean.onRowSelect(RequestManagedBean.java:134)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:187)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:52)
    at org.primefaces.event.SelectEvent.processListener(SelectEvent.java:40)
    at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:106)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:760)
    at javax.faces.component.UIData.broadcast(UIData.java:1071)
    at javax.faces.component.UIData.broadcast(UIData.java:1093)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3730)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)

A: I have managed to resolve this issue by using @ViewAccessScoped which is supported in CDI. Add the dependency in maven or directly download from http://myfaces.apache.org/extensions/cdi/download.html and put it in classpath.
<dependency>
    <groupId>org.apache.myfaces.extensions.cdi.core</groupId>
    <artifactId>myfaces-extcdi-core-api</artifactId>
    <version>1.0.5</version>
    <scope>compile</scope>
</dependency>

One small problem still remains i.e. when application is deployed for the first time, I still do not get selected row value, for the subsequent selections I am able to get selected row value.

A: I think you have to provide rowKey attribute on datatable, if you want to work with selection.


text:
Q: Type for JSON field on Type-GraphQL I'm defining a custom input field on type-graphql of type JSON. We're using Prisma as well. I tried with Prisma.JsonValue, Prisma.JsonObject and JSON but I get this errors. any suggestion will be welcome

A: You can't directly use Prisma-generated models as type definitions in TypeGraphQL. You will need to create custom classes as shown in the TypeGraphQL docs (with @ObjectType(), @InputType() etc decorators).
There is a third party library for generating TypeGraphQL types from Prisma called typegraphql-prisma which you could consider. However, in my opinion it's easier to define the classes manually.
Furthermore, I'm not sure what you mean by JsonValue. If you need to pass arbitrary JSON data, perhaps you could stringify your JSON object and pass it as a String?


text:
Q: How can I get a value stored inside an NSObject retrieved from Firebase? I am trying to append my Locale custom class that have some properties,
// here is my locale
    struct Locale: Decodable {
        var nomeLocale: String
        var isActive: Bool
    }

to an array with values retrieved from firebase like so:
@State var array: [Locale] = []

ref.child("locali").child(userID!).observe(.value, with: { snapshot in
    guard let value = snapshot.value as? [String : NSObject] else {
        print("error with the guard first")
        return
    }
    for locale in value {
        locali.append(Locale(nomeLocale: locale.key, isActive: // here I have to get the nested object ))
    }
}

)}
The data that i receive back from Firebase (the value) is the following:
["Pizzeria da Jonny": {
     isActive = 0;
 },
 "Locanda da Pino": {
     isActive = 1;
 }]

I can successfully retrieve the nomeLocale as shown before this way:
for locale in value {
    locali.append(Locale(nomeLocale: locale.key /*, isActive: locale.value*/))
}

But the problem (at least for me) is getting the nested property of isActive inside of the value response, I can't just do `locale.value.isActive


text:
Q: Pandas read_sql with multiple parameters and lists I've the following script:
now = dt.datetime.now()
date_filter = now - timedelta(days=3)
list_ids = [1,2,3]
dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = connection.cursor(buffered=True)
query = ('''
SELECT *
FROM (SELECT * FROM myTable1 WHERE id in {%s}
WHERE date >= %s;
''')
df = pd.read_sql_query(query, connection,params=(list_ids,date_filter,))

And I want to have two filters on my query:
1) List all the IDs that I've on list_ids
2) Filter only the dates before date_filter.
The second Filter I can do it, but when I try with the list I got:
pandas.io.sql.DatabaseError: Execution failed on sql

What I am doing wrong?

A: Because IN clause receives multiple values, you need to adjust prepared statement with requisite number of placeholders, %s, and then unpack list for parameters with func(*list). Plus no subquery is needed for both WHERE clauses.
query = '''SELECT * FROM myTable1
           WHERE id in (%s, %s, %s) AND date >= %s;
        '''

df = pd.read_sql_query(query, connection, params=(*list_ids, date_filter))

For dynamic placeholders equal to length of list, integrate a str.join:
placeholders = ", ".join(["%s" for _ in list_ids])

query = '''SELECT * FROM myTable1
           WHERE id in ({}) AND date >= %s;
        '''.format(placeholders)

df = pd.read_sql_query(query, connection, params=(*list_ids, date_filter))

A: The accepted answer suggests creating a %s placeholder for every item in the list of ids. But that's not necessary.
Each of the Python MySQL db packages supports passing lists or tuples into parameters. It'll figure out how to "expand" the list into the appropriate SQL before sending it off to the database.
Here's a complete example with pymysql:
import pymysql
import pandas

with pymysql.connect(
    host='',
    user='',
    passwd='',
    db='',
) as conn:
    data = pandas.read_sql(
        sql="select * from my_table where id in %(my_ids)s",
        con=conn,
        params={'my_ids': [1, 2, 3,]},
    )

(As an aside, and it's been many years since the OP's question, and so I think this specific point isn't particularly useful to future readers, but I'm pretty sure the SQL error he received was more mundane. He's missing a closing parens at the end of this phrase: FROM (SELECT * FROM myTable1 WHERE id in {%s}, and shouldn't have curly braces around %s)


text:
Q: Script fails to fetch all the names available in a link I'm trying to fetch the names of all the hostels available in the following link. The thing is the names are generated dynamically and that is reason I can't grab them using get requests. However, when I issue a post requests with appropriate payload then I can fetch the name from it's landing page. Trouble comes up when i click on the show more records button as I can see an extra field 'lr': '87' in payload is being added and I can't manage to use that in the right way.
Website address
The numbers incremented when i click on the show more records button are like 87,227,384,457 and so on.
Here is what I've tried to parse the content (working one for first few names):
import requests
from bs4 import BeautifulSoup

url = 'http://hosteldunia.com/controller/search2.php'

payload={
    'address': 'hyderabad',
    'forWhom': 'Men',
    'accomodationType': 'undefined',
    'min': '2000',
    'max': '20000',
    'filter': 'single|doubleShare|tripleShare|fourShare|fiveShare'
}
session = requests.Session()
r = session.post(url,data=payload)
soup = BeautifulSoup(r.text,'lxml')
for item in soup.select("h5.hover-title-top"):
    print(item.text)

How can i get all the names from that link using requests?

A: This proved to be some challenge, I had to look in the javascript code to find this out.
The response contains a single div with class 'more', its id is the next lr. I bet they don't have code reviews :)
import requests
from bs4 import BeautifulSoup

def get_next_batch(lr):
    url = 'http://hosteldunia.com/controller/search2.php'

    payload = {
        'address': 'hyderabad',
        'forWhom': 'Men',
        'accomodationType': 'undefined',
        'min': '2000',
        'max': '20000',
        'filter': 'single|doubleShare|tripleShare|fourShare|fiveShare',
        'lr': lr
    }
    session = requests.Session()
    r = session.post(url, data=payload)
    soup = BeautifulSoup(r.text, 'html.parser')

    for item in soup.select("h5.hover-title-top"):
        print(item.text)

    next_lr = soup.select(".more")[0]['id']
    return next_lr

lr = None
#loads next batches
lr = get_next_batch(lr)
lr = get_next_batch(lr)
lr = get_next_batch(lr)


text:
Q: PHP User Access im trying to create an access role script in which only the manager can edit a select box and assign an employee.
here is my code
useraccess.php
<?php
    session_start();
    $useraccess = $_SESSION['userglobalaccess'] ;
    echo $useraccess ; // it will echo administrator or user just for me to see

    if ($useraccess=='administrator')
        {
           $_SESSION['employeeincharge'] ='';
        }

    else
        {
            $_SESSION['employeeincharge'] ='disable';
        }
 ?>

in my html have select with this property
addrecord.html
<select name="test" id="test1">
    <option  <?php echo $_SESSION['employeeincharge']; ?> value="John">John</option>
    <option  <?php echo $_SESSION['employeeincharge']; ?> value="Jeff">Jeff</option>
    <option  <?php echo $_SESSION['employeeincharge']; ?> value="Nikko">Nikko</option>
</select>

when im looking at page view source it will say it is has disable property. but yet it is not disabled and i can select in option eve if im only have user access.

A: You should change disable into disabled
w3 reference


text:
Q: Image change when i scroll gridview GridView load images from URL. When i scrolls gridview, more image chance, how to do fix it... I have tried imageAdapter.notifyDataSetChanged(), gridView.invalidateViews().. I have not found a solution to this problem.
public class ImageAdapter extends BaseAdapter{

    private Context mContext;
    private LayoutInflater mInflater;
    private ArrayList<NodeFood> listImage = new ArrayList<NodeFood>();

    public ImageAdapter(Context c, ArrayList<NodeFood> listImage){
        this.mContext = c;
        this.listImage = listImage;
    }

    public class ViewHolder{
        ImageView imageView;
        ProgressBar progress;
    }

    public int getCount() {
        return listImage.size();
    }

    public Object getItem(int arg0) {
        return arg0;
    }

    public long getItemId(int arg0) {
        return arg0;
    }

    public View getView(int arg0, View arg1, ViewGroup arg2) {
        final ViewHolder holder;
        if(arg1 == null){
            holder  = new ViewHolder();
            mInflater = LayoutInflater.from(mContext);
            arg1    =   mInflater.inflate(R.layout.layout_item_grid, null);
            holder.imageView = (ImageView)arg1.findViewById(R.id.imageItemGrid);
            holder.progress = (ProgressBar)arg1.findViewById(R.id.progressBar);
            holder.progress.getIndeterminateDrawable().setColorFilter(0xFFFF0000,android.graphics.PorterDuff.Mode.MULTIPLY);
            arg1.setTag(holder);
        }else{
            holder = (ViewHolder)arg1.getTag();
        }
        holder.imageView.setTag(arg0);
        holder.progress.setTag(arg0);
        NodeFood a = this.listImage.get(arg0);
        String URL = a.getSRC();
        task_LoadIMG bb = new task_LoadIMG(URL,holder);
        bb.execute();
        return arg1;
    }

    public class task_LoadIMG extends AsyncTask<Void,Void,Bitmap>{
        private String url;
        private ViewHolder holder;
        public task_LoadIMG(String url, ViewHolder holder){
            this.url = url;
            this.holder = holder;
        }
        @Override
        protected Bitmap doInBackground(Void... arg0) {
            try{
                URL aURL = new URL(this.url);
                URLConnection connect = aURL.openConnection();
                connect.connect();

                InputStream is = connect.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                Bitmap bm = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
                return bm;
            }catch(IOException e){
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            holder.progress.setVisibility(View.GONE);
            holder.imageView.setImageBitmap(result);
            holder.imageView.setScaleType(ScaleType.CENTER_CROP);
        }
    }
}

A: The problem is that your AsyncTask is taking longer to load an image than that image is being displayed for. Once it's finished downloaded, that cell has come and gone and has been recycled for the next image.
To work around this, store the URL of the cell's image in the cell's tag property. Then, check to make sure that the cell URL is the same when the AsyncTask completes. If it's not the same, then the cell has been recycled in the meantime and you should discard the update. Here's some code:
public View getView(int arg0, View arg1, ViewGroup arg2) {
    final ViewHolder holder;
    if(arg1 == null){
        holder  = new ViewHolder();
        mInflater = LayoutInflater.from(mContext);
        arg1    =   mInflater.inflate(R.layout.layout_item_grid, null);
        holder.imageView = (ImageView)arg1.findViewById(R.id.imageItemGrid);
        holder.progress = (ProgressBar)arg1.findViewById(R.id.progressBar);
        holder.progress.getIndeterminateDrawable().setColorFilter(0xFFFF0000,android.graphics.PorterDuff.Mode.MULTIPLY);
        arg1.setTag(holder);
    }else{
        holder = (ViewHolder)arg1.getTag();
    }
    NodeFood a = this.listImage.get(arg0);
    String URL = a.getSRC();
    holder.imageView.setTag(URL);
    task_LoadIMG bb = new task_LoadIMG(URL,holder);
    bb.execute();
    return arg1;
}

public class task_LoadIMG extends AsyncTask<Void,Void,Bitmap>{
    private String url;
    private ViewHolder holder;
    public task_LoadIMG(String url, ViewHolder holder){
        this.url = url;
        this.holder = holder;
    }
    @Override
    protected Bitmap doInBackground(Void... arg0) {
        try{
            URL aURL = new URL(this.url);
            URLConnection connect = aURL.openConnection();
            connect.connect();

            InputStream is = connect.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            Bitmap bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
            return bm;
        }catch(IOException e){
            return null;
        }
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (url.equals(holder.imageView.getTag()) {
            holder.progress.setVisibility(View.GONE);
            holder.imageView.setImageBitmap(result);
            holder.imageView.setScaleType(ScaleType.CENTER_CROP);
        } else {
            // View was updated in the meantime, ignore the image
        }
    }
}

You might also consider canceling the AsyncTask as soon as the cell is recycled to save bandwidth/CPU cycles. That's left as an exercise for the reader.

A: I use volley and you can get rid of all async task, tags ...
relapse your ImageView with com.android.volley.toolbox.NetworkImageView
something like:
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/twitter_avatar"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"/>

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private LruCache<String, Bitmap> mMemoryCache;
then:
final int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = 1024 * 1024 * memClass / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {

        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in bytes rather than number of items.
            return bitmap.getByteCount();
        }

    };

    mRequestQueue = Volley.newRequestQueue(context);
    mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {

        public void putBitmap(String url, Bitmap bitmap) {
            mMemoryCache.put(url, bitmap);
        }

        public Bitmap getBitmap(String url) {
            return mMemoryCache.get(url);
        }
    });

Use Volley:
NetworkImageView image = (NetworkImageView) row.findViewById(R.id.ivGridViewImage);

image.setImageUrl(url, mImageLoader);

A: I was having the same problem with my GridView. Although there are not many item, only 24, and I loaded images from my phone's SD card instead of online, I was still getting images jumping all around when I scrolled, which was really only a line or two that was hidden from view at a time.
What I did was simply add a ViewHolder and it was fixed. Looks like this tutorial implements it similarly as @scompt.com. His point in the tutorial is that with the ViewHolder like this, a call to findViewById() is not repeatedly called when the view gets recycled. This might be why the images don't jump around anymore when scrolling.
Not sure if this would help others in the same predicament. I searched on S.O. for this problem and very few addressed it. Hope it helps someone.
In my adapter class: PhotoGridItem is my model class, that is typed into my ArrayAdapter extension, like this: ArrayAdapter<PhotoGridItem>. Just to explain my code a bit.
@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        final ViewHolder holder;

        if (row == null) {

            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(resourceId, parent, false);

            holder = new ViewHolder();
            holder.imageView = (ImageView) row.findViewById(R.id.photo_grid_view);
            // stores holder with view
            row.setTag(holder);

        } else {

            holder = (ViewHolder)convertView.getTag();
        }

        PhotoGridItem photoGridItem = getItem(position);

        if (photoGridItem != null) {
            bm = photoGridItem.getImage();
            holder.imageView.setImageBitmap(bm);

            // positioning the image in the GridView slot
            holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            holder.imageView.setLayoutParams(new LinearLayout.LayoutParams
                    (270, 270));
        }

        return row;

    }

    public class ViewHolder{
        ImageView imageView;
    }


text:
Q: Block chmod over SFTP Is it possible to block chmod over SFTP without patching the SSH daemon? I read somewhere that you can do this via ACLs although I am not quite sure how that is supposed to work.

A: By default as far as I know this is not possible however it is possible to patch SFTP by yourself.
Go check out the patch here: http://sftpfilecontrol.sourceforge.net/
Hope this helps.

A: Yes, you can do this with a program called authprogs.


text:
Q: Simulate Properties Window of visual studio in winform I want to design a panel like properties window of visual studio in my winform application.
Infact i want to have a grid that can accept a combobox as one of its cells,so user could select one of its items instead of typing.
I know it is possible in wpf but i want to know if there is any way to do this in winform app?
Edit:
I'm looking for a way to show the result of FooForm in this example just in front of FooProperty.
Note: I can not place screen shot of my real application here! but i have something like the following picture in my property grid and i want to show the name of the selected Background Image as value of BackgroudImage property that specified in the red rectangle instead of (none) value.

please tell me if there is a way to do this?

A: You can use System.Windows.Forms.PropertyGrid control. You'll find plenty of examples on the internet.

A: A grid can be provided via PropertyGrid; this uses the System.ComponentModel implementation, which is very flexible but quite complex. However, to provide suggested values - you use the GetStandardValues method of TypeConverter. Full example:
(edit: needs CanConvertFrom / ConvertFrom to work as combo)
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{

    public class MyType
    {
        [TypeConverter(typeof(GiveMeOptionsConverter))]
        public string SomeProperty {get;set;}

        private class GiveMeOptionsConverter : TypeConverter
        {
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
            }
            public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
            {
                if (value is string) return value;
                return base.ConvertFrom(context, culture, value);
            }
            public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
            {
                return true;
            }
            public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
            {
                return false; // true is drop-down; false is combo
            }
            public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
            {
                // this gives you the `MyType` instance if you need it
                var obj = (MyType)context.Instance;

                return new StandardValuesCollection(
                    new[] { "abc", "def", "ghi" });
            }
        }
    }
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            using (var grid = new PropertyGrid {
                Dock = DockStyle.Fill,
                SelectedObject = new MyType()
            })
            using (var form = new Form { Controls = { grid } })
            {
                Application.Run(form);
            }

        }
    }
}

A: You can use a PropertyGrid and a custom type editor for doing that.
Here you have a detailed explanation of what you can do with a property grid, and how do a custom UI type editor.
http://msdn.microsoft.com/en-us/library/aa302326.aspx


text:
Q: register DLL in ASP.NET I'm getting
Error Type:
Server object, ASP 0177 (0x800401F3)
Invalid class string
/ErrorProcess.asp, line 64
error while I try to run my project in ASP.NET. I've registered all the necessary DLLs but it is not working.
Do I have to restart my machine after registration? or is there any other problem?

A: In the asp.net you need not to register dll. You can add reference of dll and use it. Right click on asp.net project and click on "Add Reference" and add the dll reference. Then you can use it.


text:
Q: CORS policy: Request header field tron-pro-api-key is not allowed by Access-Control-Allow-Headers in preflight response I have a problem with trongrid. I dont know what to do. On trongrid i create API and put it in index.js
What config should i have on api settings on trongrid?
Console

Access to XMLHttpRequest at 'https://api.shasta.trongrid.io/wallet/getnodeinfo' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field tron-pro-api-key is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my index.js
const TRONGRID_SHASTA_API = 'https://api.shasta.trongrid.io';

const HttpProvider = TronWeb.providers.HttpProvider;
const fullNode = new HttpProvider(TRONGRID_SHASTA_API);
const solidityNode = new HttpProvider(TRONGRID_SHASTA_API);
const eventServer = new HttpProvider(TRONGRID_SHASTA_API);
const privateKey = "c4f27f7b0523507**********************ecddfb21c891";
const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, privateKey);
tronWeb.setHeader({'Content-Type': 'application/json',
    'Access-Control-Allow-Headers': '*',
    'Access-Control-Allow-Origin': '*',
    'TRON-PRO-API-KEY': '6ad9cb75-****-4f4c-a9cf-2156aa5e8453'});

async function triggercontract(){
    console.log("trx:", tronWeb.trx);
    console.log(tronWeb.transactionBuilder);
    console.log(tronWeb.utils);
    let instance = await tronWeb.contract().at("TNS*******tST9zAqXXssho5hgZ");
    let res = await instance.f().call();
    let res1 = await instance.g().call();
    console.log("res", res);
    console.log("res1", res1);
}

UPD 1:
I understand that: I have simple react-app, when i start it it up on localhost:3000 and it makes requests to api.shasta.trongrid.io/..... making post requests but api.shasta.trongrid.io dont give access to this localhost cause i dont have cors but how to set it cors correctly to work it project?
UPD 2:

Why my browser simply get info from this link, but react-app not? What should i do?


text:
Q: How to pass arguments to Perl one liner? #!/usr/bin/perl
my $a;
$a=qx(date --date "+3 min" '+ %Y/%m/%d-%H:%M:%S');
system( q(perl -pi.back -e 's{/2013/07/31-05:54:14/}{$a}g;' /tmp/ron/replace.txt));

I'm getting the date from server adding 3mins to it and assigining it to $a variable, but i'm not able to print that using the one liner. How to print a variable in perl one liner?

A: If you're doing this in bash, then it's probably simpler to replace your entire operation with the following sed command:
sed 's!/2013/07/31-05:54:14/!'"$(date --date "+3 min" '+ %Y/%m/%d-%H:%M:%S')"'!g'

This will insert the output of the date command into the sed substitution string.
Also, I see that you've got a / character at the start and end of your search string.  Did you mean to include those as part of the search string?
In your original command, you need to interpolate $a into the system command which you could do like this:
#!/usr/bin/perl
my $a;
$a = qx(date --date "+3 min" '+ %Y/%m/%d-%H:%M:%S');
system( q(perl -pi.back -e 's{/2013/07/31-05:54:14/}{) . $a . q(}g;' /tmp/ron/replace.txt));

The $a does not expand inside a q() string (which is equivalent to a string surrounded by ') so I've closed the q() and concatenated $a the reopened q().
Calling perl from within a perl script is a little clunky. Essentially, you're just wanting to use the output of the date command in a one-liner, so something like this might also be simpler:
bash$ perl -pi.back -e 's{/2013/07/31-05:54:14/}{'"$(date --date "+3 min" '+ %Y/%m/%d-%H:%M:%S')"' /tmp/ron/replace.txt

Although this is pretty similar to using sed.


text:
Q: Maximum number of DDS Topics that may be created in a single DDS Domain Is there a limit to the number of Topics that may be created for a particular Domain in DDS? Is this implementation-dependent?
What is the maximum for RTI Connext DDS 5.0.0? I don't see it specified in the documentation.

A: The 'magic' limit of 240 you recalled was most likely either the maximum number of DomainParticipants that can run on a single computer on the same domain ID, which is 120. Or else it is the maximum number of DDS domain IDs, which is 233. See http://community.rti.com/kb/what-maximum-number-participants-domain
As Reinier mentioned there are no intrinsic limits to the number of endpoints.
Gerardo

A: With Connext, the limiting factor is not so much the number of Topics, but more the number of DataReaders and DataWriters created in a particular Domain. Of course, each DataReader and DataWriter is associated with exactly one Topic, so indirectly there is a dependency on the number of Topics.
With regard to the maximum number of DataReader and DataWriters in a Domain (often collectively indicated by Endpoints), the practical limitations depend on the resources in your system. Memory consumption due to administration of the topology of your DDS system will increase with the number of Endpoints. There is no hard or hard-coded limit on the number of Endpoints though.
If you have any particular scale in mind, I could indicate where you are in comparison to other users of the product.
This answer is indeed implementation dependent. My remarks apply to RTI Connext DDS and are not necessarily true for other DDS implementations.


text:
Q: How to use the public key generated by using PHP on the server? On the server, I have an PHP script (Laravel) that can generate RSA key pairs, flash them into the session, and return a base64 encoded public key, which will be used in my windows application to encrypt the password, and the key is created by calling the openssl_pkey_new function:
// get RSA key pairs
public function generateRSAKeyPairTest(Request $request)
{
    $t = $this->microtime_float();

    $res = openssl_pkey_new();
    openssl_pkey_export($res, $privkeyraw);
    $d= openssl_pkey_get_details($res);
    $pubkeyraw = $d['key'];
    $pubkey = base64_encode($pubkeyraw);
    $privkey = base64_encode($privkeyraw);
    $request->session()->flash('privkey', $privkey);
    $request->session()->flash('pubkey', $pubkey);

    $tdiff = $this->microtime_float() - $t;
    $keypair = array('pubkey'  => $pubkey,'diff' => $tdiff);

    return response()->json($keypair);
}

// decode the encryted string
public function decryptRSATest(Request $request)
{
    if ($request->session()->has('privkey'))
    {
        $privkey = $request->session()->get('privkey', 'default value');
        $resPriv = openssl_pkey_get_private(base64_decode($privkey));

        $encrypted_text_base64 = $request->encrypted_text;
        $outval = '-';
        $encrypted_text = base64_decode($encrypted_text_base64);
        openssl_private_decrypt($encrypted_text, $outval, $resPriv);
        return response()->json(
            [
                 'decoded_text_from_clit'=>$outval
            ]
        );
    }
    return response()->json(["error"=>"private key does not exist!"]);
}

then in my windows application (C#), I get the json from server and retrieve the public key
    var data = Convert.FromBase64String(publicKeyStringBase64);
    var publicKeyRaw = Encoding.UTF8.GetString(data);
    var pkStr = publicKeyRaw.Replace("-----END PUBLIC KEY-----", "").Replace("-----BEGIN PUBLIC KEY-----", "");
    var publicKey = Encoding.UTF8.GetBytes(pkStr);

the publicKeyRaw is like following (PKCS#8 format):

-----BEGIN PUBLIC KEY-----
  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArwg6U1EET7OSbLO7UUZh
  7p8ODYY4kXUd5S1Z/qexG5IqpNflrdQbpVh+8KWNi83oidAUjWEb050Rl3AuY/E6
  7hYlEdUvI9pevmBpjjU1GktzQsDsbva3THHSpTZXPlctnFnuz0b5hVu1nUETmbGF
  fSbslZet3pbKcK5KGnJpm6v6OQGpvgQjyNWF16HjUD4/x1rAL2aDNOZZED+FNJcC
  hNmdK1A8nECk1JoTTdiK7r0EXMWxdVjEaSkAsvi7ywKi7ZESWwS1JmRuIJ5ZPiRx
  Fvur1tgaiomEZ+9oDpk1+bwDenrERYgBxw2L6Rw0CwuyinhwYfIbWkNmy4cAiZVx
  KwIDAQAB
  -----END PUBLIC KEY-----

I tried to use RSAParameters, but whether the Modulus is the raw byte array (data) or the array converted from the stripped string (publicKey), the encryptedText encrypted by using RSACryptoServiceProvider's Encrypt method cannot be decrypted by openssl_private_decrypt on the server.
var rsaInfo = new RSAParameters()
{
    Exponent = new byte[] { 1, 0, 1 },
    Modulus = data, // publicKey
};

var csp = new RSACryptoServiceProvider();
csp.ImportParameters(rsaInfo);
var password = "testing-passsword!";
var hash = csp.Encrypt(Encoding.UTF8.GetBytes(password), false);
var encryptedText = Convert.ToBase64String(hash);

I guess that RSACryptoServiceProvider does not encrypt the password correctly, so what is the correct way to use this key string (publicKeyRaw ) with the RSACryptoServiceProvider ?
[Update]
After doing a lot of searching work on google, the prolem becomes clear (just the same as what @James Reinstate Monica Polk mentions):
the key generated by using openssl_pkey_new() is, by default, in PKCS#8 format, while RSACryptoServiceProvider only accepts the key in PKCS#1 v1.5 format. Such incompatibility caused this problem.
so, do you have any solutions for this?

A: I've got a solution from this post: Correctly create RSACryptoServiceProvider from public key
there are many things we need to take care of when using the RSAPrameters class.

*

*it is recommended to encode the public key by using
base64_encode on the server so that it could be passed to the client in a json string. And I use phpseclib instead of the openssl.
to genereate the PKCS#1 format public key

*In C#,decode the base64 encoded string into a readable public key
    string, which has a format as follows:

        -----BEGIN RSA PUBLIC KEY-----
        base64 encoded data
         -----END RSA PUBLIC KEY-----

*In C#, retrieve the public key data and extract the modulus and
public exponent byte arrays. In this step, we should pay a
particular attention to Modulus in the RSAParameters class,
when we fill in the Modulus, we should skip the fist byte, which
is 0x00. I implemented a simple but not complete decoder as follows:

public static RSAParameters GetRSAParametersFromPublicKey(string publicKeyString)
{
            // publicKeyString should have following format:

            // -----BEGIN RSA PUBLIC KEY---- -
            // base64 encoded data
            // -----END RSA PUBLIC KEY---- -

            var pubicKeyContentString = publicKeyString.Replace("-----BEGIN RSA PUBLIC KEY-----", "")
                .Replace("-----END RSA PUBLIC KEY-----", "")
                .Replace("\r", "")
                .Replace("\n", "")
                .Replace(@"\/", "/");
            var publicKeyArray = Convert.FromBase64String(pubicKeyContentString);

            var mask = 0x7F;
            var skipCount = 0;
            var rsaParameters = new RSAParameters();
            for (int i = 0; i < publicKeyArray.Length; i=skipCount)
            {
                var tag = publicKeyArray[i];
                var lengthLength = publicKeyArray[i + 1];
                var length = Convert.ToInt32(lengthLength);
                skipCount += 2;
                if (lengthLength > mask)
                {
                    var lengthBit = lengthLength & mask;
                    var lengthBytes = publicKeyArray.Skip(skipCount).Take(lengthBit).ToArray();
                    skipCount += lengthBit;
                    length = BitConverter.ToInt16(lengthBytes.Reverse().ToArray(),0);
                }
                if (tag == 0x02)
                {
                    // both modulus and public exponent start with 0x02: integer
                    // therefore, 0x02 is the only tag we are interested in
                    var valueBytes = publicKeyArray.Skip(skipCount).Take(length).ToArray();
                    if (valueBytes[0] == 0x00)
                    {
                        // a valid DER has a leading byte 0x00
                        rsaParameters.Modulus = valueBytes.Skip(1).ToArray();
                    }
                    else
                    {
                        rsaParameters.Exponent = valueBytes;
                    }
                    skipCount += length;
                }
            }
            return rsaParameters;
        }

and here is a function that encrypt the input plainText with input base64 encoded public key string
public static string Cryptography(string plainText, string publicKeyStringBase64)
{
    var publicKey = Convert.FromBase64String(publicKeyStringBase64);
    var publicKeyRaw = Encoding.UTF8.GetString(publicKey);
    var rsaInfo = GetRSAParametersFromPublicKey(publicKeyRaw);
    if (rsaInfo.Modulus != null && rsaInfo.Exponent != null)
    {
        var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(rsaInfo);
        var hash = csp.Encrypt(Encoding.Unicode.GetBytes(plainText), false);
        var encryptedText = HttpUtility.UrlEncode(Convert.ToBase64String(hash));

        return encryptedText;
    }
    return "!!error!!";
}

*On the server, I'd like to use phpseclib instead to generate a PKCS#1 key pair and perform the decoding (laravel):

    use phpseclib\Crypt\RSA;

    public function decryptRSATest(Request $request)
    {
        if ($request->session()->has('privkey'))
        {
            $privkeybase64 = $request->session()->get('privkey', 'default value');
            str_replace(['\/', '\n'], ['/', ''], $privkeybase64);
            $privkey = base64_decode($privkeybase64);

            $rsa = new RSA();
            $received = str_replace(['\/', '\n',"\0",'\\'], ['/', '', '',""], $request->encrypted_text);
            $rsa->loadKey($privkey);
            $rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
            $decrypt_text2 = $rsa->decrypt(base64_decode($received));
            $decrypt_text2 = str_replace("\0",'',$decrypt_text2);

            return response()->json(
                [
                     'decoded_text_from_clit' => $decrypt_text2
                ]
            );
        }
        return response()->json(["error"=>"private key does not exist!"]);
    }

Moreover, if we just need the modulus and the exponent instead of a complete public key, we can just pass the modulus and exponent to the client (base64_encoded):
            // PHP - Server end
            $modulus_base64 = base64_encode($rsa->modulus);
            $exponent_base64 = base64_encode($rsa->exponent);

and in the C#, it might be a little bit tough to correctly decode them, here is a code snippet:
        // C# - Client end
        var modulus = Convert.FromBase64String(modulusStringBase64);
        var exponent = Convert.FromBase64String(exponentStringBase64);
        var modulusRaw = Encoding.UTF8.GetString(modulus);
        var exponentRaw = Encoding.UTF8.GetString(exponent);
        var bigIntegerModulus = BigInteger.Parse(modulusRaw);
        var bigIntegerExponent = BigInteger.Parse(exponentRaw);
        var exponentArray = bigIntegerExponent.ToByteArray();
        var modulusArray = bigIntegerModulus.ToByteArray();

and some useful online tools:
base64 decoder
ASN 1 decoder
Json Viewer
Hope this could be helpful for you.


text:
Q: How to have Text next to CLKRelativeDateTextProvider I am building watchOS complications and i want to have a timer that counts down what i have made using the following:
func createUtilitarianLargeTemplate(prayer: Prayer?) -> CLKComplicationTemplate {
    let myComplicationTemplate = CLKComplicationTemplateUtilitarianLargeFlat()
    let dateProvider = CLKRelativeDateTextProvider()

    if let prayer = prayer {
        dateProvider.date = prayer.prayerTime.prayerDate
        dateProvider.calendarUnits = [.hour, .minute]
        dateProvider.relativeDateStyle = .timer
    }

    myComplicationTemplate.textProvider = dateProvider

    return myComplicationTemplate
}

But i want to show some text next to the timer in an UtilitarianLarge complication family. How is that possible as i can't set text in the dateProvider.
What I want to achieve is the following String:
GBT * 15:24:12
So I want to have "GBT * " in front of the timer. How is that possible? Somehow it must be possible as I have seen other complications on the Appstore achieving this

A: It took them until watchOS 6 to add init(format:_:) to CLKTextProvider.
let myComplicationTemplate = CLKComplicationTemplateUtilitarianLargeFlat()
let dateProvider = CLKRelativeDateTextProvider()

dateProvider.date = Date()
dateProvider.calendarUnits = [.hour, .minute]
dateProvider.relativeDateStyle = .naturalAbbreviated

let finalText = CLKTextProvider(format: "GBT * %@", dateProvider)

myComplicationTemplate.textProvider = finalText

For watchOS 5 and prior, this is the only good way to do it...


text:
Q: qtoolbar button mouse clicking not working This is weird.  The toolbar on the left side in only clickable at the very corner.
But if I move the button position to the right of the other buttons it is clickable.  It seems like its only that what ever button is first on the left side.
This image shows that I cant click on the button when I mouse over it.

This image shows that I can click on it on the lower corner of the image only.

Update 1
OK this is weird.  I added a menu on top just to see using the Designer and now my toolbar works.
But I also noticed that my menu item on the left doesnt

But If I click on any menu item to the right that I can click and move to the left, then I can click on the menu item that I wasnt able to originally

Update 2
I was able to resolve it by calling raise() on the toolbar fixed the issue.


text:
Q: ненужные файлы codeblocks в codeblocks при работе создается куча ненужных файлов вроде:
main_build_log.html
main.depend
main.save

И так для каждого файла с которым работаешь, из-за чего сложно ориентироваться по папке. как можно сделать чтобы эти файлы создавались в другую папку проекта.


text:
Q: How to find an explicit formula for a recurrence using substitution I have a recurrence as follows:
\begin{equation}
T(n) = \begin{cases}a, & \text{for $n=1$}\\
T(\dfrac{n}{2})+b,&\text{for $n\geq2$}
\end{cases}
\end{equation}
$a$ and $b$ are some undefined constant.
I'm asked to find an explicit formula using substitution, showing my work for $k$ iterations. I understand, conceptually, how to substitute:
\begin{align*}
    T(n) &= T(n/2)+b\\
    T(n/2) &= T(n/4) + 2b\\
    T(n/4) &= T(n/8) + 3b\\
    T(n/8) &= T(n/16) + 4b
\end{align*}
WolframAlpha tells me that this recurrence resolves to $T(n) = a + \dfrac{b \log(n)}{\log(2)}$, but I have no idea how it arrived there, or if that is even correct.
What is the correct way to perform this substitution to arrive at an explicit formula?

A: First, one can notice that this recurrence is defined only for numbers $n$ which are powers of 2.
To solve the recurrence, you can try to unravel it.
Namely,
$$T(n) = b+T\left(\frac{n}{2}\right) = b+b+T\left(\frac{n}{4}\right)= b+b+b+T\left(\frac{n}{8}\right) = 3b+T\left(\frac{n}{2^3}\right)$$
We can see that the coefficient next to $b$ increases by one in every step and that the argument of $T$ gets divided by two every time. So, we can infer that the general formula would be:
$$T(n) = k\cdot b + T\left(\frac{n}{2^k}\right)$$
for some $k\in\mathbb N$.
But, we are aiming to get $n=2^k$, in order for the chain to terminate. This gives us that $k=\log_2 n$.
Now we have
$$T(n) = b\log_2 n + T(1) = b\log_2 n+a$$
You can use mathematical induction to prove that this is indeed the general formula for $T(n)$.
Also, this formula is equivalent to the formula WolframAlpha gave.

A: It might be useful to rewrite the recursion as follows:

*

*$\boxed{n=2^k} \Rightarrow \boxed{t_k = T(2^k)}$

*$\Rightarrow \boxed{t_{k+1} = t_k + b, t_0 = a}$ for $k \in \mathbb{N}$

*Telescoping gives $\boxed{t_k} = t_0 + \sum_{i=0}^{k-1} (t_{i+1} - t_i) \boxed{= a + kb}$

*Having in mind that $n=2^k \Leftrightarrow k = \log_2 n = \frac{\ln n}{\ln 2}$ you get:
$$\boxed{T(n) = a+ b\cdot \log_2 n} \mbox{ for } n= 2^k, k \in \mathbb{N}$$


text:
Q: Como mudar todos os valores de um array JSON? var cookie = [
{"domain":".nada.com","flag":true,"expiration":"1595998766"},
{"domain":".nada.com","flag":true,"expiration":"1627534734"},
{"domain":".nada.com","flag":true,"expiration":"1595998765"}
]

// Mudar os valores das chaves expiration para 0 todas
// Ex.
[
{"domain":".nada.com","flag":true,"expiration":"0"},
{"domain":".nada.com","flag":true,"expiration":"0"},
{"domain":".nada.com","flag":true,"expiration":"0"}
]

A: Existem algumas maneiras de se fazer isso, mas a que eu recomendo é o uso de Array.prototype.forEach()¹

var cookie = [{
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998766"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1627534734"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998765"
  }
];

cookie.forEach((el) => el.expiration = 0);

console.log(cookie);

Com isso você altera o array inicial, o forEach percorre cada elemento do array com isso você não tem que se preocupar com o index do elemento atual, apesar de ser possível utiliza-lo com a sintaxe .forEach((el, index) => console.log(index)).
Caso você queira percorrer o array e ainda assim manter o valor original do antigo array para algo em especifico, você pode usar o Array.prototype.map()² da seguinte forma:

var cookie = [{
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998766"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1627534734"
  },
  {
    "domain": ".nada.com",
    "flag": true,
    "expiration": "1595998765"
  }
];

var newCookie = cookie.map((el) => {
  return { ...el, expiration: 0 }
});

console.log(cookie);
console.log(newCookie);

A magica está no uso do spread operator (...)³ nessa linha: {...el, expiration: 0}. Desse modo pegamos todo conteúdo original do array e sobrescrevemos o valor de expiration com 0.


text:
Q: Error while installing mysql on ubuntu I am getting error while installing MySQL
Errors were encountered while processing:
   mysql-server-5.7
   mysql-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

I tried various solutions one of them is
sudo apt-get purge mysql*
sudo apt-get autoremove
sudo apt-get autoclean

After completely uninstalling mysql run the following command
sudo apt-get dist-upgrade

Then reinstall mysql
sudo apt-get install mysql-server

But it did not worked.
Please help me

A:
The error message "Sub-process /usr/bin/dpkg returned an error code (1)" indicates a problem with the package installer. This can happen in Ubuntu after a failed software installation, or if the installer becomes corrupted.

Method 1: Reconfigure dpkg Database
sudo dpkg ––configure –a
Method 2: Force-install the Software
If Method 1 did not work, you can attempt to fix the dependencies in the package installer.
sudo apt-get install –f
if non of theme worked try looking here


text:
Q: Trying to find the minimum number in a extraneous file and print it For an assignment Im working on I need to go through a file from OurWorldInData.org which has info on all countries names, codes, years and life expectancy's with spanish flu and I need to pull out the year and country name that had the lowest and highest life expectancy as well as offer a way for the user to enter a year and the program to display the life expectancy from that year. I don't know how much help yall will be able to offer since its kinda hard to emulate if you don't have the csv file of the info but this is my code right now.
filename = 'Life_expectancy.csv'

with open(filename) as le_file:
    next(le_file)
    for line in le_file:

        line = line.strip().split(",")

        name = line[0]
        code = line[1]
        year = int(line[2])
        life_expectancy = float(line[3])

        min(life_expectancy) = min_life_expectancy

print(f'Name: {name}, Code: {code}, Year: {year}, Life Expectancy: {life_expectancy}')

I struggled for a really long time trying to wrap my head around this assignment and decided just to try min(life_expectancy), but got an error that reads "SyntaxError: can't assign to function call" and I don't know what this means. If anybody could help me I would greatly appreciate it.

A: So I created a wee dummy data file called life.csv. Easy enough. It looks like this:
Name1,asd,1990,74,blah,blah,blah
Name2,bec,1923,41,blah,blah,blah
Name3,fre,1983,93,blah,blah,blah
Name4,jve,1066,23,blah,blah,blah
Name5,vne,1930,43,blah,blah,blah

A good bit of advice is to create a dummy for asking questions, but don't worry about that for the moment! :-) Hopefully it looks a little like the top part of yours!
I've revised your code. If you're having trouble diagnosing this type of loop remember that having print() statements in each iteration is your friend when debugging, as you start out! However, I'm hoping I've not been too abstract so you're happy to work through it and understand what's going on:
rows = []
with open(filename) as le_file:
    next(le_file)
    for line in le_file:

        line = line.strip().split(",")
        rows.append(line)

With this you'll end up with a variable called rows containing your split data.
rows
[['Name1', 'asd', '1990', '74', 'blah', 'blah', 'blah'],
 ['Name2', 'bec', '1923', '41', 'blah', 'blah', 'blah'],
 ['Name3', 'fre', '1983', '93', 'blah', 'blah', 'blah'],
 ['Name4', 'jve', '1066', '23', 'blah', 'blah', 'blah'],
 ['Name5', 'vne', '1930', '43', 'blah', 'blah', 'blah']]

Now we can extract the INDEX of the row that has the smallest age like so:
ages = [row[3] for row in rows]
min_age_idx = ages.index(min(ages))

This returns the first index in the CSV of the minimum age, which you can now use to get the details of the entry in question:
details = rows[min_age_idx]
print('Name: {}, Code: {}, Year: {}, Life Expectancy: {}'.format(details[0], details[1], details[2], details[3]))

Now, I appreciate this isn't the most concise solution but very illustrative of what you're trying to achieve. The problem you were having is that you were still reading through the file assigning entries to variables, BEFORE you had any idea which line has the minimum age. Therefore each age AFTER the line with the minimum would reassign the variables you eventually use in your print statement. There are many ways to solve the problem or simplify the print statement, including using help libraries like pandas to read the CSV but I think it important to know what's going on with your problem!
The reason for "can't assign to function call" is because min() is a function call and it's on the left hand side of your statement. If you wanted to assign a variable with the result of a min() function call, it would look like:
my_min_value = min(values)

The left hand side of the = is what you're assigning to, the right hand side is the operation whose result you want to assign to it.
I really hope this helps clear things up for you! :-)


text:
Q: How to tackle a software architect that feels he's above a standard programmer? This post felt like it belonged somewhere in between SE Workplace and SE Programmers. However, since it's specifically targeting a programming issue, I decided to put it here.
What are the responsibilities of an architect? I'm asking because at every company that I've worked for, the architect's duties were along the lines of :

*

*Specifying the interface of functional modules.

*Participating in code reviews.

*Preparing specification documents which describe the functionality that is to be implemented, including but not limited to sequence diagrams and the like.

I recently started a new job. Here, the architect's duties are :

*

*Describing one problem and proposed implementation to every team member separately, instead of documenting it once and then letting us familiarize ourselves with it.

*Engaging in two-week almost 24-hour coding streaks where he puts out a lot of code that is not documented at all, even though the code does what it's supposed to do.

*Not caring about code review at all, be it his own or others'.

*Bypassing any coding standards that we have strived to put in place as programmers : be it unit tests, documentation, or formatting.

*Being completely ignorant to the rules governing the language that we write our application in (C++), including but not limited to object life cycle management, or passing large structs via copy.

When confronted about this stuff, he responds that "We couldn't have written the stuff that he writes in a way that it's supposed to be written". When I spoke to some of the more senior staff in here, they simply said that "It's how it's always been", and that he simply has more leeway with management because he individually maintains a system for managing testing of our application that is of course vital to the company.
I feel like such behaviour should not be tolerable, since it reduces the number of people being able to maintain the code to practically zero, as he usually writes the most basic code for the application that we need to use later on. I do understand that he may be used to working alone because of his previous experiences, but by repeating his practices, he pretty much creates a system that nobody else can maintain later on.
Is there anything that can be done in my situation, short of handing in my resignation and looking for another opportunity? I'm really frustrated with the situation, as I see this simply as an abuse of power.

A:
What are the responsibilities of an architect?

It will vary from company to company. Some do the high level design for the system. Some serve as translators from business to dev and vice versa. Some mentor programmers in how to be better programmers. Some write all of that gnarly code that nobody else can. Some sit in their offices browsing the web, collecting paychecks.

Is there anything that can be done in my situation, short of handing in my resignation and looking for another opportunity?

Absolutely.
Let's start with the first option - giving the architect the benefit of the doubt. It is entirely possible that by making working code they're providing far more value to the company than they would via documentation. Yes, it might be slower or more error-prone for you to maintain this, but you might've been even slower or more error prone in implementing the stuff they implemented.
I've worked at places where one top tier programmer made the company. Without their ability to do stuff that competitors could not, the company would fold. If they don't do that, it doesn't matter how maintainable the code is - you're all out of jobs.
Now, that's the decidedly optimistic case. A perhaps more likely scenario is one where a good programmer hasn't kept up with the times. They haven't heard about unit tests. They don't buy into the cost argument for maintainability. Maybe they're busy. Maybe they're stubborn. Maybe they weren't really that good to begin with. Doesn't matter.
What you'll need to do is show the value in those things. If the architect asserts that you couldn't have done it right - challenge that by asking to do one of the upcoming modules. If the architect says that large struct copies are necessary, show that they aren't by refactoring the code and shelving it. If the architect says that the code is plenty maintainable, get some metrics on mean time to resolution and show that they aren't. If the architect doesn't think unit tests are useful, show how you can get code done faster and with less defects by using them.
And remember that you're all there to solve problems. If the architect doesn't want to solve problems your way, then ask what alternative they have.


text:
Q: Typescript: getTime is not function I am using Typescript for my function. I have two sets of data in the database, one is date and one is time. Both are expecting strings.
I made one POST request when the user chooses the date, and that time will be selected for the user. I made a helper function for that, when the delivery time will start, it means user selecting time is expired, in which case I show them an alert on the front-end that shows.

"Your selected time expired!" .

I am trying to pass default date parameter like this now = new Date() in my function instead of use directly new Date(). When I console log typeof now it shows the parameter is function.
PS: I am still new in Typescript. It will be great learning for me if someone give me detail about my mistake.
This is my function throws the error
const isStartimeExpired = (
    date: string,
    time: string,
    now = new Date(),
) => {
    const [startTime] = time.split(' - ');
    const newDate = new Date(`${date}T${startTime}`);

    if (newDate.getTime() < now.getTime()) { // this throws an error that getTime() is not function
        return true;
    } else if (isEmptyString(date) || isEmptyString(time)) {
        return false;
    }

    return false;
};

This one works
const isStartimeExpired = (
    date: string,
    time: string,
) => {
    const [startTime] = time.split(' - ');
    const newDate = new Date(`${date}T${startTime}`);

    if (newDate.getTime() < new Date().getTime()) { // this one does not throw any error
        return true;
    } else if (isEmptyString(date) || isEmptyString(time)) {
        return false;
    }

    return false;
};

A: You have to type the parameter now into a date, else the type of the parameter is any.
const isStartimeExpired = (
    date: string,
    time: string,
    now: Date = new Date(),
) => {
    const [startTime] = time.split(' - ');
    const newDate = new Date(`${date}T${startTime}`);

    if (newDate.getTime() < now.getTime()) {
        return true;
    } else if (isEmptyString(date) || isEmptyString(time)) {
        return false;
    }

    return false;
};


text:
Q: Spring Jdbc template setAutocommit(false) I want insert multiple rows in db table.
I am using SpringJdbc.
How can i manage transaction in SpringJdbc connection.
My code is:
@Override
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public int addUserRelationshipMapping(final ArrayList<UserDO> userDOs, final long userId) throws UserDataException {
    final JdbcTemplate jd = this.getJdbctemplate();
    try {
        jd.getDataSource().getConnection().setAutoCommit(false);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    int totalAdded = 0;
    try {
        int[] isAdded = jd.batchUpdate(ADD_USER_RELATION_MAPPING, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                final long userRelationId = jd.queryForObject(USER_RELATION_KEY, Long.class);
                UserDO userDO = userDOs.get(i);
                    ps.setLong(1, userRelationId);
                    ps.setLong(2, userId);
                    ps.setLong(3, userDO.getprimaryUserId());
                    ps.setInt(4, 1);
                    ps.setInt(5, 0);
                    jd.getDataSource().getConnection().commit();
            }

            @Override
            public int getBatchSize() {
                return userDOs.size();
            }
        });
        totalAdded = isAdded.length;
    } catch (DuplicateKeyException dExp) {
        log.info("error for duplicate key exception ",dExp);
        log.error(dExp);

    } catch (DataAccessException dExp) {
        throw new UserDataException("error while adding user relation for userId is" + userId, dExp);
    }
    return totalAdded;
}

In this code userRelationId return always old values not updated table values.
So will use database connection commit.
SOF question:Java MYSQL/JDBC query is returning stale data from cached Connection
I got error message:
Caused by: java.sql.SQLException: Can't call commit when autocommit=true
So i need help for this.
Advance thanks.

A: See the example of how to set auto commit false
<bean id="database" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
    <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        ...
        <property name="defaultAutoCommit" value="false" />
        ...
    </bean>
</property>

ref:
spring 3.1: jdbcTemplate auto commit to false.
You can also try the annotation based connection transaction management ?
How can I config to turn off autocommit in Spring + JDBC?


text:
Q: Trick to get appropriate auto complete method in xcode I have a query what is the best trick to easily get correct method using autocomplete in Xcode for swift.
Like for objective C the trick is use - sign for instance method and + for class methods.
Then next just add return type Xcode will show you appropriate methods.
For example if I want to get the the method cellForRowAtIndexPath of tableview datasource.
I have attached two images how result changes when we provide return type.

*

*Without adding return type

*With return type.

Now since in swift syntax of a function or method return type is at the end of the function, what else we can do to easily get required results.

A: You just start typing cellForRowAtIndexPath you will get that particular method. No need to type from tableView...blah blah... Just type the methods main phrase, then you will get correct method in suggestion.

Thanks:)


text:
Q: Trouble Executing GIT commands from outside bash shell (windows) I'm using finalbuilder to execute GIT commands without success.  FinalBuilder docs suggest setting the env variable HOME to %USERPROFILE% which I have done.  I can execute git clone commands successfully from the git bash shell but not from inside finalbuilder with their git action.
Leaving finalbuilder out of the picture, in windows, how can I execute a git command from outside of bash?
Now, my error is simply a timeout. no error, just timeout.
Thanks

A: Assuming you mean Git for Windows and not the cygwin git - then provided the Program Files\Git\cmd folder is added to your PATH environment variable then you will be able to run git commands from the cmd prompt or any other shell. The bash prompt has its own PATH set up using the /etc/profile file which handles this separately. So git version should return the version you are running. If this is not enough to solve your issue you might consider providing that information along with the actual commands you run and which Windows version and platform you are on and so on.


text:
Q: Debug fork() in eclipse cdt I'm trying to debug some fork() mechanism with eclipse cdt (Juno).
I wrote the program in C.
  if( -1 == (pid = fork()) ) /* error */
    goto cleanup;
  else if ( 0 == pid ) /* child */
  {
    execlp("gcc", "gcc", cFilePath, "-o" , GCC_OUTPUT_FILE_NAME, NULL);
    goto cleanup; /* Arrives here only on error! */
  }
  else if (pid > 0) /* parent - checks: correct pid returns, returns normally, with exit status = 0*/
  {
      returnedpid = wait(exitStatus);
      if( pid != returnedpid || exitStatus == NULL || !WIFEXITED(*exitStatus) || !WEXITSTATUS(*exitStatus) )
          goto cleanup;
  }

I tried to add "set follow-fork-mode child" as said here: http://unix.derkeiler.com/Newsgroups/comp.unix.programmer/2006-02/msg00435.html
1. How can I debug the code section where (0==pid)?
2. When I get to the wait statement, the debugger just return immediately, isn't wait() suppose to suspend till the child returns? Why is it return immediately?

A: Your problems are probably due to "detach-on-fork" being set to off. DSF sets this by default (it's also gdb's default).
1) Put a breakpoint onto lines with "execlp..." and "returnedpid =...".
2) In debug configuration enable "non-stop mode" and "automatically debug forked process".
3) Start debug session. You will hit a breakpoint either in child or parent. Now see debug view.

You will notice your binary shows two threads.
4) Click on one or the other (lines with main() in above image) to switch debug context.

A: It might be because the init process reaps the child before you go to wait. Try blocking sigchld as you go into fork and then unblock the signals after your forks/execs. Maybe that should give you some idea as to what is exactly happening.
Using sigprocmask should help you.

A: *

*In debug configuration window -> Debugger -> Check "Automatically debug forked processes"

*Open breakpoint window -> View menu -> Add Event Breakpoint C/C++ -> "fork
called"

*Now once the event breakpoint occurred, press F6 -> you'll see new process in debug window

*Choose new process and press F6 -
You are in the child

*Enjoy


text:
Q: Match Variable Count of Repeating Words (I am stepping through this laboriously to get my thoughts in order. Skip to the end for the question!)
My input (file names) is like this
word1.word2.word3.e01S01.word4.word5.ext
word1.word2.E03s04.word3.ext
word1.e24s02.ext

(Any number of words can be before or after ExxSxx; xx is 00-99, E and S are constants but may be uppercase or lowercase; there's always ext but it's variable alpha.)
My desired output for these examples:
Word1 Word2 Word3 E01S01.ext
Word1 Word2 E03S04.ext
Word1 E24S02.ext

(All words before and including ExxSxx are kept; . is replaced with space; words are in title case; E and S are capitalised; words between ExxSxx and .ext are discarded; ext is appended unchanged.)
I can match a known number of repeats (here 2) between . with this regex (match 1 or more instances of not . up to a dot):
[^\.]+\.

and I can group like this to be able to refer to what I want to extract:
^([^\.]+)\.                so \u$1 gives Word1

I can repeat 2 times:
^([^\.]+)\.([^\.]+)\.      so \u$1 \u$2 gives Word1 Word2

I can continue:
^([^\.]+)\.([^\.]+)\.([eE][0-9]{2}[sS][0-9]{2})
                          so \u$1 \u$2 \U$3 gives Word1 Word2 ExxSxx

Then I skip over the remainder and grab .ext:
^([^\.]+)\.([^\.]+)\.([eE][0-9]{2}[sS][0-9]{2}).*(\.[a-z]{3}$)
                          so \u$1 \u$2 \U$3\L$4 gives Word1 Word2 ExxSxx.ext

Here, finally, is my question:
Without explicitly repeating the pattern for the first x words can I get what I want with any number of .-separated words?  Would it be better to grab everything up to and including the known ExxSxx together with .ext and deal with capitalisation afterwards?

A: Oh man, that was a hard one. You cannot do it with one piece of regex capturing a whole line at a time as far a I'm aware (unfortunately), but you can handle it piece by piece if you do something like this:
(?:([eE]\d\d[sS]\d\d).*(\.ext)|\b(\w)([^.]*)\.)

Explanation:
(?:                                              // -Case 1- (non-capturing group)
   ([eE]\d\d[sS]\d\d)                            // Capture the e01S01 bit as \1
                     .*                          // Anything at all up until...
                       (\.ext)                   // ... The extension! (Capture as \2)
                              |                  // -Case 2-
                               \b(\w)            // Word boundary, then a word character (Capture as \3)
                                     ([^.]*)     // The rest of the word (Capture as \4)
                                            \.)  // The dot

And replace with this:
\U\3\L\4\U\1\L\2 \E

Explanation:
\U\3                  // (Case 2) Uppercase the first letter of the first word
    \L\4              // Lowercase the rest of the word
        \U\1          // (Case 1) Uppercase the E01S01 bit.
            \L\2 \E   // Lowercase the extension, add a space, and end the enforced case (for good measure)

Example: https://regex101.com/r/oHpXXS/3
Basically it'll go through and resolve each part, piece by piece, until it's done with the whole thing. Only 2 of the 4 capturing groups will ever be used - \3 and \4 in case 1, or \1 and \2 in case 2. The other capturing groups will be blank, and therefore resolve to nothing.
Problems:
This has a trailing space at the end of every single entry. No ideas for how to make it go away.


text:
Q: How do I selectively stack columns with twitter bootstrap I have a template based on fluid example here:
http://twitter.github.io/bootstrap/examples/fluid.html
I have the latest files from here, the only customizations being colors:
http://twitter.github.io/bootstrap/customize.html
The basic markup is

    Column 1

    Column 2

Column 2 falls under column 1 on mobile devices, which is what I want sometimes.  But in some cases (specific pages) I want the 2 columns to remain side by side.  My question is how do I achieve this with the same js/css files?

A: Here's one possibility: http://jsfiddle.net/panchroma/RMPMA/
You will see that the columns don't drop on the row with class = double-col
CSS
@media (max-width: 767px){
.double-col.row-fluid [class*="span"] {
float: left;
width: 50%;

}
}

Since this resets the width of each col to 50% on viewpoints 767px and below, this will work with rows having two columns. For other combinations, simply play with the width setting. You might also want refine the padding and other styling, but easy enough now.
Hope this helps!


text:
Q: How to recode multiple choice answers in R using dplyr? I have a dataset with answers to a large number of multiple choice questions. I now want to recode these answers in either true (1) or false (0). I
`#ID  q1 q2 q3 cq1 cq2 cq3
 #1   1  2  1  NA  NA  NA
 #2   1  2  2  NA  NA  NA
 #3   2  2  2  NA  NA  NA
 #4   1  2  1  NA  NA  NA`

what I want is this:
`#ID  q1 q2 q3 cq1 cq2 cq3
 #1   1  2  1  0  0  0
 #2   1  2  2  0  0  1
 #3   2  2  2  1  0  1
 #4   1  2  1  0  0  0`

I know that I could write out all answers like this:
`data_re <- data %>%
  mutate(cq1 = if_else(q1==2, 1, 0),
         cq2 = if_else(q2==1, 1, 0),
         cq3 = if_else(q3==2, 1, 0))`

But is there any way how to automatically do this (similar to this approach: How to mutate_at multiple columns on a condition on each value?
However, I would have to generate the variablename of the conditional variable automatically. I tried this:
`names_answer_two_correct <- c("q1", "q3")
 cnames_answer_two_correct <- paste0("c", names_answer_two_correct)

 for (i in 1:length(names_answer_two_correct)) {
   data_re <- data %>%
   mutate(names_answer_two_correct[i] = if_else(cnames_answer_two_correct[i]== 2, 1, 0))
}`

But I get "Error: unexpected '=' in:"
Does anyone know a solution?

A: You can use across to apply the function to multiple columns.
library(dplyr)
names_answer_two_correct <- c("q1", "q3")

data %>%
  mutate(across(all_of(names_answer_two_correct),
                ~as.integer(.==2), .names = 'c{col}'),
         cq2 = as.integer(q2==1)) -> data_re

data_re

#  ID q1 q2 q3 cq1 cq2 cq3
#1  1  1  2  1   0   0   0
#2  2  1  2  2   0   0   1
#3  3  2  2  2   1   0   1
#4  4  1  2  1   0   0   0


text:
Q: Appbar fitsSystemWindows - Inside a ViewPager I have an Activity that contains a ViewPager:

activity.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"/>

</FrameLayout>

The fragments this pager contains – which are all generated from the same layout – have a CoordinatorLayout and CollapsingToolbarLayout to provide a collapsing image-back titlebar:

fragment.xml:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <!-- Content here -->

    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:elevation="8dp"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:expandedTitleMarginStart="72dp"
            android:fitsSystemWindows="true">

            <ImageView
                android:id="@+id/photo"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                android:background="@color/photo_placeholder"
                android:fitsSystemWindows="true"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                app:layout_collapseMode="pin"
                android:layout_gravity="bottom">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

Without the fitsSystemWindows flags in the activity layout, the image in the fragment properly displays behind the system status bar, while the text sometimes collapses behind the status bar when scrolled up. If I add the flags in – as shown above – the text issue is resolved, but the image now cuts off at the status bar. Keeping the collapsing toolbar code in the fragment, is there a way to fit the fragment's content to the system window?
Without fitsSystemWindows in the activity (preferred behaviour):

With fitsSystemWindows in the activity:

A: You haven't declared, that you want NestedScrollView also to fitSystemWindows. So, literally, you are prohibiting WindowInsets to be passed to children off NestedScrollView, thus ViewPager is not even aware about WindowInsets.
Apply android:fitSystemWindows="true" to NestedScrollView also.