text:
Q: Route for a controller without model in rails 3 I have a controller named BaseController that inherits from ApplicationController whitout a model associated but it has ping method that just respond with a message to inform that everything is OK.
I'm trying to call the action ping through the BaseController setting this in my routes.rb file:
namespace :api, defaults: { format: 'json' } do
  match '/ping' => 'base#ping'
end

But it always give me an NameError uninitialized constant Base. I suppose it's trying to find a model called Base which doesn't exist so, I don't know how to set to the correct route to my controller.
The content of my BaseController is the following:
class Api::BaseController < ApplicationController
   load_and_authorize_resource
   respond_to :json

   def ping
      respond_with({ :status => 'OK' })
   end
end

As extra information: BaseController is just a parent controller for other controllers to inherit. The others are resourceful controllers and have models associated
Thanks.

A: When you put a namespace around a route, it will look for the controller within that namespace.
So in you case, it will be looking for a controller called Api::BaseController, which normally would be stored in app/controllers/api/base_controller.rb. Is this how your controller is set up?
See here for more details: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
EDIT:
I don't think its not finding the controller that's the problem. The error is being caused because you are calling load_and_authorize_resource in the controller.  CanCan uses the controller name to attempt to load the resource.
If there is no model for the controller, make the call authorize_resource :class => false.
See the bottom of this page for more details.

A: Please try this:
Add this in your routes.rb
resources :base

A: Try this in your routes.rb
map.resources :base, :collection=> {:ping=>:get}


text:
Q: Enqueueing into NSInputStream? I would like to add three "parts" to an NSInputStream: an NSString, an output from another stream and then another NSString. The idea is the following:
The first and last NSStrings represent the beginning and end of a SOAP request while the output from the stream is a result of loading a very large file and encoding it as Base64 string. So, in the end I would have the final NSInputStream hold the whole SOAP request like this:
< soap beginning > < Base64 encoded data > < soap ending >
The reason I want the whole request to be held in NSInputStream is two-fold:

*

*I don't what to load the very large data file into memory

*I think that this is the only way to enforce sending the final request in HTTP 1.1 chunks (which I need because otherwise, if the request becomes too big, the server won't accept it). So, I know that doing this:
NSInputStream *dataStream = ....;
[request setHTTPBodyStream:dataStream];

ensures that the request will be sent as HTTP 1.1 chunks and not as one huge raw SOAP request.
So, I wonder how this can be achieved - namely, how do I "enqueue" things into an NSInputStream? Can it be even done? Is there an alternative way?
Just for reference, in Java this can be done as follows
 Vector<InputStream> streamVec = new Vector<InputStream>();
 BufferedInputStream fStream = new BufferedInputStream(fileData.getInputStream());
 Base64InputStream b64stream = new Base64InputStream(fStream, true);
 String[] SOAPBody = GenerateSOAPBody(fileInfo).split("CUT_HERE");
 streamVec.add(new ByteArrayInputStream(SOAPBody[0].getBytes()));
 streamVec.add(b64stream);
 streamVec.add(new ByteArrayInputStream(SOAPBody[1].getBytes()));
 SequenceInputStream seqStream = new SequenceInputStream(streamVec.elements());

because Java has these objects available, but NSStreams in objective-c look like very low level objects and are very hard to work with.
Note: I completely re-wrote the original question as I asked it 2 days ago, since I think the new edit explains more clearly what the problem is. I hope it would help it be easier comprehended and maybe answered
UPDATE 2
Here is what I've been able to achieve so far: Instead of trying to enqueue into a stream, I am using a temp file to first write the < soap beginning >, then I set up an input stream to read from the file in chunks, encode each chunk as a Base64 string and write this to the same temp file, finally, when my stream closes, I write the < soap ending > to the temp file. Then I set up another input stream with the contents of this file which I pass to the NSMutableURLRequest:
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
        ...
        NSInputStream *dataStream = [NSInputStream inputStreamWithFileAtPath:_tempFilePath];
        [request setHTTPBodyStream:dataStream];

This ensures HTTP 1.1 chunked transfer of the contents of the file. After the connection finishes, delete the temp file.
This seems to work fine but of course this is an annoying work-about. I don't want to be writing to a temp file when it all could have been handled by streams (ideally.)  If anybody still has better suggestions, let me know :)
UPDATE 3
OK, another update is in order. While my writing to file seems to work, I am now hitting an unexpected issue with some of my requests failing to upload to the server. Specifically, everything is going according to the plan, I am reading the contents of the temp file into a stream and set HTTP body of my request to be this stream and it starts transmitting the HTTP 1.1 chunks as I want it to - but for some reason some packets get dropped and the final request - this is my guess - gets malformed and thus fails. I think the issue of dropped packets is random, because I observe it on larger requests - that is, the issue just has more chance to show up - while my smaller requests usually go thru just fine. This is of course a separate issue from the original in this question. If anybody has a good idea what might be causing this, I asked about the problem here: Packets dropped during chunked HTTP 1.1 request sent by NSURLConnection

A: Your solution is an ok option, but you can do it with a stream. It means subclassing NSInputStream, and that isn't trivial because there are a bunch of methods you need to implement.
Basically your subclass would initially return the header bytes, then it would return bytes from the 'internal' stream to the file content, then when that's used up it returns the footer bytes. It means maintaining a record of how big the header and footer are and how much has been processed so far, but that isn't a big issue.
There's an example of creating a subclass here which shows the tricky hidden methods you need to implement to get the stream subclass to work properly without throwing exceptions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing package and module usage/importing in Python - hierarchy and best practices. (new to external files) I am NOT new to general programming, but I am new to larger programs requiring creating/importing my own modules. I've done it in c language before, but it was years ago.. and this is Python.
I'm looking for guidance on organizing. I finally figured out HOW to import a .PY file into my project (and what it should maybe look like) as well as adding paths to windows variables, but now I am curious about if I'm doing things 'correct' or what is the best practice. Below, I included a list of links I've already read that didn't answer my questions, but figured I would try to make this thread a one-stop-shop as I've seen this is a little bit of a hot topic over the years.
I'm trying to make a kindof all-in-one module full of functions for scraping so I can do like I did in the test file and just simply write ONE line to do what I need. I.e. pass in a URL and get back a sorted list of all HTML tags and their frequency in the page. (This is just something to experiment while trying to learn organization and external files) It's a pain, because if something goes wrong, I have to change all kinds of files.
I'm getting errors like: "request = scraper_tools.get_request(url, data=None, headers=scraper.reg_header)NameError: name 'scraper' is not defined"
Am I doing it wrong, and is there a better way? (I assume there is) :)
My code goes like this:
scraper_tools.py
#!my_modules/python
# Filename: scraper_tools.py

import requests import bs4 as bs

phone_header = {'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like mac OS X)'} reg_header = {'user-agent': 'Mozilla/5.0 (Windows NT
6.1; rv:52.0) Gecko/20100101 Firefox/52.0'}

def make_soup(request, parser):
    # Make soup
    return bs.BeautifulSoup(request.text, parser)

def get_request (url, data, headers, **kwargs):
    if kwargs and not headers:
        try:
            return requests.get(url, data=data)
        except Exception as e:
            print(e)
    elif headers and kwargs:
        return requests.get(url, headers=headers, data=data)

def get_all_items(soup, tag):
    return soup.find_all(tag)

def open_file_write(path, filename):
    save_path = path
    return open(os.path.join(save_path, filename), 'w')

def get_all_links(self, soup):
    href_tags = soup.find_all(href=True)
    link_list = []

    for tag in href_tags:
        if 'http' in tag['href'][0:4]:
            link_list.append(tag['href'])

    return link_list

get_all_tags.py
from stevens_tools import scraper_tools
import operator
import requests

'''
Author: Steven Smith
Email: StevenSmithCIS@gmail.com
Date: 9/1/2017
Description: This file uses an online resource website to dynamically get all
common HTML tags in a list to be used to count list elements inside a specific
web page (and therefore know something about the quantity of each particular tag).
'''

html_tag_website_url = 'https://www.quackit.com/html/tags'
soup = None
tag_qnty_dict = None
request_object = None

def get_html_tags():
    #Get all the HTML tags currently from the website
    all_tags = []
    ul_lists = soup.find_all('ul', {'class': 'col-3 taglist'})
    for li in ul_lists:
        for item in li.find_all('a'):
            all_tags.append(item.text)
    return all_tags

def get_all_tags_from(url):
    #Returns a dictionary of all tags from HTML tag website in passsed in URL
    #with tag and quanity listed
    request = scraper_tools.get_request(url, data=None, headers=scraper_tools.reg_header)
    soup = scraper_tools.make_soup(request, 'lxml')
    tag_qnty_dict = {}
    tags = get_html_tags_from_file()
    if tags:
        for tag in tags:
            # If there is more than 0 items, add to list
            item_qnty = len(scraper_tools.get_all_items(soup, tag))
            if item_qnty > 0:
                tag_qnty_dict.update({tag: item_qnty})
    return tag_qnty_dict

def sort_items(reverse):
    #Sorts items in tag dictionary by quantity. In reverse (largest first)
    # if reverse is True
    return sorted(tag_qnty_dict.items(), key=operator.itemgetter(1), reverse=reverse)

def print_all():
    for item in sort_items(True):
        print('Tag = ' + item[0] + " Quantity: = " + str(item[1]))

test_tag_counter.py
from stevens_tools import get_all_tags

get_all_tags.print_all(get_all_tags.get_all_tags_from('https://www.goodreads.com/list/tag/best'))

^^^^^^^^^^^^^^^^^^ Not too crazy about those names, but.. they're descriptive! lol
**Other topics I've visited

Python Packages and Modules
  (..new to importing modules/packages in Python)
  http://mikegrouchy.com/blog/2012/05/be-pythonic-init__py.html (using
  __init.py for module/package identifier) create Python package and import modules
  (import each file vs one time)
  Why installing package and module not same in Python?
  (import version problem -Python 3.4 vs 2x)
  What's the difference between a Python module and a Python package?
  (<-- see name lol)
  What's the difference between "package" and "module"
  (<-- see name)
  Remove package and module name from sphinx function
  (removing module name)
  importing package and modules from another directory in python(<-- using sys)
  Best practices when importing in IPython
http://docs.python-guide.org/en/latest/writing/structure/#modules


text:
Q: Что нужно для создания соц сети на Android Есть проект, пока на стадии идеи, это что-то типо университетской социальной сети, подскажите пожалуйста что нужно для создания такого рода приложения, с какими трудностями можно столкнуться.

A: Я сам новичок. Но попробуйте с чего-то простого. Начните с приложения для общения с другом, потом развивайте. Самое плохое для программиста - реализовать сразу какую-то идею, сколь большой она не была. Задачу всегда стоит разбивать на подзадачи. Если не согласны, то готовьтесь учить саму Java, Android SDK, HTTP и шифрование.


text:
Q: How do I tell D3 to make the dendrogram vertical (top down) instead of left to right? I'm looking at this example that uses cluster layout to assign the X and Y coordinates to nodes on a dendrogram. How can I tell cluster to layout vertically, top down, instead of the default left to right?

A: For the example you link, just flip the use of the X and Y coordinates. This can be done by changing
var diagonal = d3.svg.diagonal()
  .projection(function(d) { return [d.y, d.x]; });

and
var node = vis.selectAll("g.node")
  .data(nodes)
 .enter().append("g")
   .attr("class", "node")
   .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

to
var diagonal = d3.svg.diagonal()
  // Flip the values here.
  .projection(function(d) { return [d.x, d.y]; });

and
var node = vis.selectAll("g.node")
   .data(nodes)
 .enter().append("g")
  .attr("class", "node")
  // Flip the values here.
  .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })

Here is a JSFiddle showing the above changes in action.


text:
Q: Define $A_{m,n} = \{ x \in Z : n^2x^3+2020x^2+mx=0 \}$ Then the number of pairs (m,n) for which $A_{m,n}$ has exactly two points Let m and n be non zero integers. Define $A_{m,n} = \{ x \in R : n^2x^3+2020x^2+mx=0 \}$ Then the number of pairs (m,n) for which $A_{m,n}$ has exactly two points is
(A) 0
(B) 10
(C) 16
(D) $\infty$
My approach is one of the root is x=0 and the quadratic eqn $n^2x^2+2020x+m=0$ must have equal roots.
Condition we get is $n^2m=(101)^2(2)^2(5)^2$. We can choose n^2 4+3C2+1 ways So total no of (m,n) should be 16. Please verify if the solution is correct


text:
Q: ¿Cómo puedo recorrer este array (php)? array(3) { [0]=> array(6) { ["denominacion"]=> string(4) "Test"
["descripcion"]=> string(4) "Test" ["precio"]=> string(1) "1" ["cantidad"]=>
string(1) "2" ["id_registro"]=> string(4) "7578" ["id_producto"]=> int(1) }
[1]=> array(6) { ["denominacion"]=> string(4) "Test" ["descripcion"]=>
string(4) "Test" ["precio"]=> string(1) "1" ["cantidad"]=> string(1) "1"
["id_registro"]=> string(4) "7578" ["id_producto"]=> int(2) } [2]=> array(6)
{ ["denominacion"]=> string(4) "Test" ["descripcion"]=> string(4) "Test"
["precio"]=> string(1) "1" ["cantidad"]=> string(1) "1" ["id_registro"]=>
string(4) "7578" ["id_producto"]=> int(3) } }

Arreglo
$producto = array(
    "denominacion" => $denominacion,
    "descripcion" => $descripcion,
    "precio" => $precio,
    "cantidad" => $cantidad,
    "id_registro" => $id_registro,
    "id_producto" => $id_producto
);

Ya probe así y no me muestra ningún resultado
 foreach($productos as $producto){
    echo $producto['id_producto'];
 }

A: Usando la  función foreach de php. Veo q tenes varios arrays dentro de otro array. Yo haria algo asi:
foreach ($array1 as $array) {
    foreach ($array as $prod) {
      echo $prod["id_producto"];
    }
}

A: A. Si quieres leer los nombres de claves y sus valores
Dado que estás creando un array de arrays, podrás leerlos de forma automática de este modo, usando dos bucles:
<?php

$productos=array();
$producto = array( "denominacion" => "d1", "descripcion" => "desc1", "precio" => 1, "cantidad" => 1, "id_registro" => 1, "id_producto" => 1 );
$productos[]=$producto;
$producto = array( "denominacion" => "d2", "descripcion" => "desc2", "precio" => 2, "cantidad" => 2, "id_registro" => 2, "id_producto" => 2 );
$productos[]=$producto;

foreach ($productos as $k=>$v){

    foreach ($v as $kk=>$vv){
        echo "Llave: ".$kk. "-> Valor: ".$vv."
";
    }
    echo "
";
}
?>

Resultado:

Llave: denominacion-> Valor: d1
Llave: descripcion-> Valor: desc1
Llave: precio-> Valor: 1
Llave: cantidad-> Valor: 1
Llave: id_registro-> Valor: 1
Llave: id_producto-> Valor: 1

Llave: denominacion-> Valor: d2
Llave: descripcion-> Valor: desc2
Llave: precio-> Valor: 2
Llave: cantidad-> Valor: 2
Llave: id_registro-> Valor: 2
Llave: id_producto-> Valor: 2

B. Si quieres acceder por nombres de llaves del array.
Puedes abrir un sólo bucle, que te diferencie con as las llaves y los valores. En este caso, $v será un array en el cual podrás buscar el valor por el nombre de una llave específica. Por ejemplo, para el caso de la llave id_producto :
foreach ($productos as $k=>$v){
        echo $v["id_producto"]."
";
}

Resultado:

    1
2


text:
Q: accessibility service is not started I want to log all toasts events in android ics (4.0.3), but I was unable to log any system event. Service is just not started!
According to this question:
onAccessibilityEvent(AccessibilityEvent event) not intercepting notification
MyAccessibilityService.java
package com.test.toasts2;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Notification;
import android.os.Parcelable;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toast;

public class MyAccessibilityService extends AccessibilityService {

    public static final String TAG = "volumeMaster";

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event)
    {
        Log.v(TAG, "***** onAccessibilityEvent");
        Toast.makeText(getApplicationContext(), "Got event from: " + event.getPackageName(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onInterrupt()
    {
        Log.v(TAG, "***** onInterrupt");
    }

    @Override
    public void onServiceConnected()
    {
        Log.v(TAG, "***** onServiceConnected");

        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
        info.notificationTimeout = 100;
        info.feedbackType = AccessibilityEvent.TYPES_ALL_MASK;
        setServiceInfo(info);

    }
}

Toast2Activity.java
package com.test.toasts2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class Toast2Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i = new Intent(this, MyAccessibilityService.class);
        startService(i);
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.toasts2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
<service android:name=".MyAccessibilityService" android:label="@string/app_name" android:enabled="true" android:exported="false">
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>

</service>

        <activity
            android:name=".Toast2Activity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I included activity tag in manifest (to start service on app start), and also tried to remove. Nothing changed. Service is just not started. I don't get notification in log cat (Log.v in onServiceConected).
I am compiling this as normal app (not system app), android 4.0.3. Am I doing something wrong?
Attached project (may be mistake is somewhere else, or maybe I am compiling it wrong):
https://dl.dropbox.com/u/1928109/toast2.zip

A: You need to enable the accessibility service from the system settings menu:

*

*Install your app on the testing device.

*With the app installed on the device, change the following setting on the device:

Home Screen > System Settings > Accessibility > Accessibility Services > Toast2 > Change from Off to On,

where Toast2 is your app name.

*Then run your app.
AFAIK there is no method to set accessibility programmatically to On mode from within your app. As a workaround you can prompt the user to change the setting and if they agree by clicking a button, launch the accessibility system settings like so:
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivityForResult(intent, 0);

A: As a complementary answer to the comments, one more thing worth noting is that you have to declare permission - android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" in your service, or else there will be no switch in setting->accessibility.


text:
Q: consuming webservices but not able to show data fetched from webservices in listview
*

*created xml for listview order.xml

*consuming web services in Webservices.java class

private static String NAMESPACE = "http://ws.admin.gaurav.in/";
//Webservice URL - WSDL File location
private static String URL = "http://adm.gaurav.in/UserWS?wsdl";
private static String SOAP_ACTION = "/";
private static final String METHOD1 = "ordersList";

public static String invokeListViewWS(String userName,String webMethName) {

  SoapObject request = new SoapObject(NAMESPACE, METHOD1);
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
  envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

  try {
    // Invoke web service
    androidHttpTransport.call(SOAP_ACTION+METHOD1, envelope);
    // Get the response
    SoapObject response = (SoapObject) envelope.getResponse();
    String[] list = new String[response.getPropertyCount()];
    for(int i= 0; i< response.getPropertyCount(); i++){
      list[i] = response.getProperty(i).toString();
    }

  } catch (Exception e) {
    //Assign Error Status true in static variable 'errored'
    HomeActivity.errored = true;
    e.printStackTrace();
  }
  return "abhi";
}

I am trying to fetch method ordersList which is type  and returning a list
I am unable to get that can any one help me with how to get list from webservice, how to store that and populate that in list view. I am new in android development so if anyone have  any link or resources which can help please help me. Thanks in advance


text:
Q: MySQL query GROUPing from one table, excluding results found in another sub query Let's say I have two tables - ADDONS and DOWNLOADS.
ADDONS dictates which apps come with which addons for FREE.
DOWNLOADS logs addon downloads from all apps, those that include for free and not.
ADDONS
appname  | varchar
appaddon | varchar

DOWNLOADS
id       | int
appaddon | varchar
appname  | varchar
source   | varchar
date     | datetime

I am trying to write a query that shows the count of each appaddon in DOWNLOADS where it was NOT included for free in ADDONS.
I got as far as:  "SELECT appaddon, count(id) FROM downloads GROUP BY appaddon ORDER BY count(id) DESC" - but that is inclusive of apps that included it for free and those that do not.
Can anyone point me in the right direction on this?

Update:
Example:  Imagine I have two holiday themed apps - one for Christmas, one for Halloween, and each app allows you to download costumes that are included with the app (for example Halloween lets you download a witch, skeleton or jack o lantern, and Christmas lets you download a Santa or elf).  BUT if someone upgrades from within the app, they can download ANY of the available costumes (so Christmas upgraded could download a skeleton, or Halloween upgraded could download an Elf).
I am trying to get a count of the downloads that are NOT included without upgrading.  So I want to exclude the witches downloaded by Halloween, and the Santas downloaded by Christmas, but get a count of the witches, skeletons, elves, etc downloaded by the OTHER apps.
Here is some example data:
ADDONS
appname     | appaddon
========================
halloween   | jackolantern
halloween   | skeleton
halloween   | witch
christmas   | santa
christmas   | elf
christmas   | reindeer
easter      | bunny
allholidays | bunny

DOWNLOADS
id | appaddon  | appname   | date
=======================================
1  | skeleton  | halloween | 2012-10-15
2  | skeleton  | halloween | 2012-10-15
3  | witch     | halloween | 2012-10-16
4  | santa     | christmas | 2012-10-16
5  | elf       | christmas | 2012-10-16
6  | witch     | christmas | 2012-10-16
7  | bunny     | christmas | 2012-10-16
8  | bunny     | halloween | 2012-10-17
9  | bunny     | easter    | 2012-10-18

Based on above, I would expect the results:
appaddon  | count
=================
bunny     | 2
witch     | 1

A:  SELECT appaddon, count(id) FROM downloads
    left join addons on addons.appname=downloads.appname
    where addons.appname is null
    GROUP BY downloads.appaddon ORDER BY count(id) DESC

A: This might work for you:
SELECT DOWNLOADS.appaddon, COUNT(*) FROM DOWNLOADS
    INNER JOIN ADDONS ON (DOWNLOADS.appaddon = ADDONS.appaddon)
    WHERE DOWNLOADS.appname != ADDONS.appname
    GROUP BY DOWNLOADS.appaddon;

Here is the SQL Fiddle for it: link

A: I think I figured it out!  Required me to use WHERE NOT EXISTS.
SELECT appaddon, count(id) FROM DOWNLOADS
WHERE NOT EXISTS (
  SELECT appaddon FROM ADDONS
  WHERE DOWNLOADS.appname = ADDONS.appname
  AND DOWNLOADS.appaddon = ADDONS.appaddon)
GROUP BY appaddon

Fiddler for it here


text:
Q: How to extract javascript variable value using imacros browser? I have looked but I simply cannot find an answer to what I expect should be a very simple task.
I have navigated to a page that contains a known javascript variable.
eg: var foo='my variable text';
How can I extract that value ('my variable text') using iMacros browser? Is that even possible to do directly?
Or, would I have to execute javascript to place that variable's value into an input or tag, that iMacros can then extract from?
Many thanks in advance.

A: You can use the URL GOTO method to call a javascript function, which will load the value inside the input element. Please checkout the below example where I have replicated the same.
HTML:
<script>
var a  = "naren";
</script>
<input type="text" id="naren"/>

IMacros:
VERSION BUILD=9030808 RECORDER=FX
TAB T=1
URL GOTO=javascript:{(function<SP>(){console.log(document.getElementById(a).value='works!')})()}

So I have made a mockup page with the html as above, then ran the below imacros.
Some  points you need to know about calling the imacros script are:
I have wrapped the anonymous function as an iife, long story short, the function will get executed immediately.
If you visit the IMACROS URL wiki page There is a line which tells us.

The URL GOTO command by default outputs the result of the evaluated
  Javascript expression on a new page in the current tab. If you want to
  manipulate an element on the page and don't want the result to be
  processed by the URL GOTO command, you need to wrap it in some other
  call or expression that does not evaluate to any value.
For example, to change the value of the Name field on the demo Fill
  Form page, you can wrap the call in console.log() as follows:
URL GOTO=http://demo.imacros.net/Automate/TestForm1 URL
  GOTO=javascript:console.log(document.getElementById("name").value='Test');

So I have implement the above statement by wrapping the assignment done to the input element inside a console.log.
Please let me know if you have issues implementing this solution!


text:
Q: How to create a txt file composed by output from different SQL queries? I need to create a txt file from a SQL SERVER DataBase composed as follows:
Products
OutputQuery1

Racks
OutputQuery2

Products per Rack
OutputQuery3

...

OutputQuery1 is only a value returned from Query1
OutputQuery2 is only a value returned from Query2
OutputQuery3:
each row is composed by the following columns: Id_Prod, Id_Rack, NumProd
in the txt file I have to show only the number of product.
This is an example:
Products
3
Racks
2

Products per Rack
5 5 5
4 4 4

Have you some suggestion??
Thnaks!

A: You can do this multiple ways:
If you need to export a query to txt.
You can go to the ribbon on the top of SQL server and select Results to text
another way
Right click the top-right corner of the result set while it's in grid view. If formatting is not an issue, you can just directly copy and paste entire contents from here.
Right-Click top-right corner
SELECT ALL
Copy with Headers/Without
Paste to blank txt document.
You could also write an SSIS package.


text:
Q: Exporting Data Using Attribute Table Widget In ArcGIS Web AppBuilder? I'm using web app builder for ArcGis and in the configuration of Attribute table widget I did enable exporting data as CSV file but when I try to export it I get something like this in new page in the browser:

What I want is to download the file when the user hit export as CSV.
Is there any better way to export data from Attribute table ?


text:
Q: How to bind text to the label which is in JsonObj using jquery I am getting data in an array which I need to bind to the label below is my code. When the array is empty I need to bind no records found which are working but I need to bind the data in the array to the label. Suppose if I have 2 items in the array I need to bind two items i.e slider 1 should have one item and again after sliding to the right I need to bind the second item.
If more than 1 item is there then the right slider should be enabled and if it has only 1 item right slider should be disabled if there are no items both the sliders should be disabled

success: function (response) {
    var json = response.d;
    if (json.length == 0) {
        $('.swiper-wrapper').append('
No rocords found
');
    } else {
        $.each(json, function (index, item) {
            $('.swiper-wrapper').append('
Name : ' + item.Name + '
Number: ' + item.Number + '
');
        });
    }

A: You could throw a bunch of if else statements
if(length > 1) {
// there is more than one item
} else if(length < 1) {
// there is less than one item
else {
//there is exactly one item
}


text:
Q: JSON parser with child I have this Json file:
{
   "id":0,
   "leagueCaption":"League Two",
   "rankings":[
      {
         "id":0,
         "position":1,
         "teamName":"Portsmouth",
         "wins":26,
         "draws":9,
         "losses":11,
         "points":87
      },
      {
         "id":0,
         "position":2,
         "teamName":"Plymouth Argyle",
         "wins":26,
         "draws":9,
         "losses":11,
         "points":87
      },
      {
         "id":0,
         "position":3,
         "teamName":"Doncaster Rovers FC",
         "wins":25,
         "draws":10,
         "losses":11,
         "points":85
      }
   ]
}

I'm trying to render a list using map, however I can not render it by having the child rankings,
I need to render the leaguecaption as a Title, and the rankings on the grid,
I did this, but it still is not working, it returns me an error saying that it is not possible to render,
My request:
getItems(event) {
        event.preventDefault();
        this.setState({ 'isLoading': true });
        API.getRanking(this.state.code)
            .then(items => this.setState({ items, 'isLoading': false }))
            .catch(error => this.setState({ error, isLoading: false }));

}

My component:
render() {
        return (

                            Position
                            Points
                            Name
                            Wins
                            Draws
                            Defeats

                        {
                            this.props.items.map(function (team) {
                                return (

                                        {team.position}
                                        {team.points}
                                        {team.teamName}
                                        {team.wins}
                                        {team.draws}
                                        {team.losses}

                                );
                            })
                        }

        )
    }

My screen render:
return (

Championship of Football

                <ChampionshipForm
                    onSubmit={this.getItems}
                    controlId='form'
                    id="code"
                    name="code"
                    value={this.state.code}
                    onChange={this.setCode.bind(this)}
                />

                <RankingTable items={this.state.items}/>

        );

Error message:

A: Your question is not very clear. But i am suspecting you are accessing items before its available. Try add a simple checking like below in your component
{
   this.props.items && this.props.items.map(function (team) {
        return (

                {team.position}
                {team.points}
                {team.teamName}
                {team.wins}
                {team.draws}
                {team.losses}

        );
    })
}

Another possible schenarion is that, items is not an array hence the reason why items.map is not a function. Can you console this.props.items in your component and it type like below
console.log(this.props.items);
console.log(typeof this.props.items)

the second console from above should print array. If not then you are passing the wrong items type.
One more thing i noticed. Your array is rankings and items is a object from your json above. Consider changing
 <RankingTable items={this.state.items}/>

to
 <RankingTable items={this.state.items.rankings}/>


text:
Q: Assumptions in mathematica when Symplify on Log[Exp[a/b]] In mathematica 9.0:
This:
Assuming[b > 0 || b < 0, Simplify[Log[Exp[a/b]]]]

yields:
a/b

However, this:
Assuming[FullSimplify[b > 0 || b < 0], Simplify[Log[Exp[a/b]]]]
enter code here

or this:
Assuming[b !=0 , Simplify[Log[Exp[a/b]]]]

Yield:
Log[Exp[a/b]]

Shouldn't be both equivalent? Why isn't the expression simplified in the second case?. Also tried to add ass an assumption a and b to be real, just in case, but doesn't work either.  Could someone shed any light on this?

A: I suspect that this has to do with the assumption b > 0 implicitly stating that b is a real, where that is not the case with b != 0.  This is, of course, because there is no natural ordering of complex numbers, but they do have a 0-element to compare against.  As evidence for this answer, note that
Assuming[Element[b, Reals] && b != 0, Simplify[Log[Exp[a/b]]]]

Gives the expected result of a/b where it didn't above.


text:
Q: How do I add a dropdown button on each row of a jquery datatable I am using datatables plugin to display data as a table in my application.
I want to add the Bootstrap Dropdown Buttons or Javascript Dropdowns on each row of my table. But the dropdown part goes hidden under the table rows, and I am not able to fix it.
The html for the table would be:

       ID
      Modifier
       Created Time
       Modified Time
       Edit
       Actions

      100
      Admin
      10/06/2014
      11/02/2015

        <button type="button" class="btn btn-primary btn-sm">
          Edit
        </button>

          <button id="dLabel" type="button" data-toggle="dropdown"
                  aria-haspopup="true" aria-expanded="false">
            Dropdown trigger

          </button>

Action

Another action

I initialize the datatable as follows:
$('#swcmtable').DataTable({
  "iDisplayLength" : 50,
  "aaSorting": []
});

Is there any way to fix this?

A: From the details you provided, it is clear that you are using a custom style to hide text overflow in your data-table. Also since you have specified that this style is important, you can try to hide text overflow only for the column where you need to truncate the extra text and do not apply this style for entire table.
Use something like:
table.dataTable td:nth-child(2)
{
    max-width:120px;
    word-wrap: break-word;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

This code will hide text overflow only for the second column of the table and the remaining columns will not b affected.
I believe this should work in your case


text:
Q: Is there a way to list all the commands a user can execute (KSH)? I am currently writing a ksh script where I check for sticky bits to see if a unprivileged user can execute certain commands. I was wondering if there is a more efficient way to check it. Any help is appreciated.

A: find(1) is your friend (if it isn't, install GNU find):
find / -type f -executable


text:
Q: Negative weights using Dijkstra's Algorithm I am trying to understand why Dijkstra's algorithm will not work with negative weights. Reading an example on Shortest Paths, I am trying to figure out the following scenario:
    2
A-------B
 \     /
3 \   / -2
   \ /
    C

From the website:

Assuming the edges are all directed from left to right, If we start
  with A, Dijkstra's algorithm will choose the edge (A,x) minimizing
  d(A,A)+length(edge), namely (A,B). It then sets d(A,B)=2 and chooses
  another edge (y,C) minimizing d(A,y)+d(y,C); the only choice is (A,C)
  and it sets d(A,C)=3. But it never finds the shortest path from A to
  B, via C, with total length 1.

I can not understand why using the following implementation of Dijkstra, d[B] will not be updated to 1 (When the algorithm reaches vertex C, it will run a relax on B, see that the d[B] equals to 2, and therefore update its value to 1).
Dijkstra(G, w, s)  {
   Initialize-Single-Source(G, s)
   S ← Ø
   Q ← V[G]//priority queue by d[v]
   while Q ≠ Ø do
      u ← Extract-Min(Q)
      S ← S U {u}
      for each vertex v in Adj[u] do
         Relax(u, v)
}

Initialize-Single-Source(G, s) {
   for each vertex v  V(G)
      d[v] ← ∞
      π[v] ← NIL
   d[s] ← 0
}

Relax(u, v) {
   //update only if we found a strictly shortest path
   if d[v] > d[u] + w(u,v)
      d[v] ← d[u] + w(u,v)
      π[v] ← u
      Update(Q, v)
}

Thanks,
Meir

A: Since Dijkstra is a Greedy approach, once a vertice is marked as visited for this loop, it would never be reevaluated again even if there's another path with less cost to reach it later on. And such issue could only happen when negative edges exist in the graph.

A greedy algorithm, as the name suggests, always makes the choice that seems to be the best at that moment. Assume that you have an objective function that needs to be optimized (either maximized or minimized) at a given point. A Greedy algorithm makes greedy choices at each step to ensure that the objective function is optimized. The Greedy algorithm has only one shot to compute the optimal solution so that it never goes back and reverses the decision.

A: Note, that Dijkstra works even for negative weights, if the Graph has no negative cycles, i.e. cycles whose summed up weight is less than zero.
Of course one might ask, why in the example made by templatetypedef Dijkstra fails even though there are no negative cycles, infact not even cycles. That is because he is using another stop criterion, that holds the algorithm as soon as the target node is reached (or all nodes have been settled once, he did not specify that exactly). In a graph without negative weights this works fine.
If one is using the alternative stop criterion, which stops the algorithm when the priority-queue (heap) runs empty (this stop criterion was also used in the question), then dijkstra will find the correct distance even for graphs with negative weights but without negative cycles.
However, in this case, the asymptotic time bound of dijkstra for graphs without negative cycles is lost. This is because a previously settled node can be reinserted into the heap when a better distance is found due to negative weights. This property is called label correcting.

A: The algorithm you have suggested will indeed find the shortest path in this graph, but not all graphs in general. For example, consider this graph:

Let's trace through the execution of your algorithm.

*

*First, you set d(A) to 0 and the other distances to ∞.

*You then expand out node A, setting d(B) to 1, d(C) to 0, and d(D) to 99.

*Next, you expand out C, with no net changes.

*You then expand out B, which has no effect.

*Finally, you expand D, which changes d(B) to -201.

Notice that at the end of this, though, that d(C) is still 0, even though the shortest path to C has length -200. This means that your algorithm doesn't compute the correct distances to all the nodes. Moreover, even if you were to store back pointers saying how to get from each node to the start node A, you'd end taking the wrong path back from C to A.
The reason for this is that Dijkstra's algorithm (and your algorithm) are greedy algorithms that assume that once they've computed the distance to some node, the distance found must be the optimal distance. In other words, the algorithm doesn't allow itself to take the distance of a node it has expanded and change what that distance is. In the case of negative edges, your algorithm, and Dijkstra's algorithm, can be "surprised" by seeing a negative-cost edge that would indeed decrease the cost of the best path from the starting node to some other node.

A: TL;DR: The answer depends on your implementation. For the pseudo code you posted, it works with negative weights.

Variants of Dijkstra's Algorithm
The key is there are 3 kinds of implementation of Dijkstra's algorithm, but all the answers under this question ignore the differences among these variants.

*

*Using a nested for-loop to relax vertices. This is the easiest way to implement Dijkstra's algorithm. The time complexity is O(V^2).

*Priority-queue/heap based implementation + NO re-entrance allowed, where re-entrance means a relaxed vertex can be pushed into the priority-queue again to be relaxed again later.

*Priority-queue/heap based implementation + re-entrance allowed.

Version 1 & 2 will fail on graphs with negative weights (if you get the correct answer in such cases, it is just a coincidence), but version 3 still works.
The pseudo code posted under the original problem is the version 3 above, so it works with negative weights.
Here is a good reference from Algorithm (4th edition), which says (and contains the java implementation of version 2 & 3 I mentioned above):

Q. Does Dijkstra's algorithm work with negative weights?
A. Yes and no. There are two shortest paths algorithms known as Dijkstra's algorithm, depending on whether a vertex can be enqueued on the priority queue more than once. When the weights are nonnegative, the two versions coincide (as no vertex will be enqueued more than once). The version implemented in DijkstraSP.java (which allows a vertex to be enqueued more than once) is correct in the presence of negative edge weights (but no negative cycles) but its running time is exponential in the worst case. (We note that DijkstraSP.java throws an exception if the edge-weighted digraph has an edge with a negative weight, so that a programmer is not surprised by this exponential behavior.) If we modify DijkstraSP.java so that a vertex cannot be enqueued more than once (e.g., using a marked[] array to mark those vertices that have been relaxed), then the algorithm is guaranteed to run in E log V time but it may yield incorrect results when there are edges with negative weights.

For more implementation details and the connection of version 3 with Bellman-Ford algorithm, please see this answer from zhihu. It is also my answer (but in Chinese). Currently I don't have time to translate it into English. I really appreciate it if someone could do this and edit this answer on stackoverflow.

A: you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.
this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]
in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.

A: Consider what happens if you go back and forth between B and C...voila
(relevant only if the graph is not directed)
Edited:
I believe the problem has to do with the fact that the path with AC* can only be better than AB with the existence of negative weight edges, so it doesn't matter where you go after AC, with the assumption of non-negative weight edges it is impossible to find a path better than AB once you chose to reach B after going AC.

A: "2) Can we use Dijksra's algorithm for shortest paths for graphs with negative weights – one idea can be, calculate the minimum weight value, add a positive value (equal to absolute value of minimum weight value) to all weights and run the Dijksra's algorithm for the modified graph. Will this algorithm work?"
This absolutely doesn't work unless all shortest paths have same length. For example given a shortest path of length two edges, and after adding absolute value to each edge, then the total path cost is increased by 2 * |max negative weight|. On the other hand another path of length three edges, so the path cost is increased by 3 * |max negative weight|. Hence, all distinct paths are increased by different amounts.

A: You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.
In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

A: I will be just combining all of the comments to give a better understanding of this problem.
There can be two ways of using Dijkstra's algorithms :

*

*Marking the nodes that have already found the minimum distance from the source (faster algorithm since we won't be revisiting nodes whose shortest path have been found already)

*Not marking the nodes that have already found the minimum distance from the source (a bit slower than the above)
Now the question arises, what if we don't mark the nodes so that we can find shortest path including those containing negative weights ?
The answer is simple. Consider a case when you only have negative weights in the graph:
)
Now, if you start from the node 0 (Source), you will have steps as (here I'm not marking the nodes):

*

*0->0 as 0, 0->1 as inf , 0->2 as inf in the beginning

*0->1 as -1

*0->2 as -5

*0->0 as -8 (since we are not relaxing nodes)

*0->1 as -9 .. and so on
This loop will go on forever, therefore Dijkstra's algorithm fails to find the minimum distance in case of negative weights (considering all the cases).
That's why Bellman Ford Algo is used to find the shortest path in case of negative weights, as it will stop the loop in case of negative cycle.


text:
Q: cross browser extension to take data from a usb and display I am starting to work on a browser extension that can take data from a usb and then display the data to the user. I am in early stages and researching about web to usb comms.
I am struggling to find out if I will be able to use webUSB API (as I want it to be used on most browsers) or if there are any alternatives. Any help or direction would be appreciated.
I have just been researching and unable to find any concrete answers


text:
Q: Conditionally making WooCommerce product non purchasable I've been struggling with a snippet for WooCommerce that I'd like to add to my child's theme functions but I am reaching the limits of my PHP knowledge.
I have set a custom attribute called pdt_volume, that I will fill everytime I add a product. I would like to remove the Add_to_cart button when the sum of this attribute for all the items already in the cart have reach a max_volume limit.
For example, the Max_volume is 100, I have 4 products of pdt_volume = 20, therefore, the add_to_cart button for a product with a pdt_volume of 25 should be removed so that I cannot add it to the cart.
So I have come up with this snippet, with bits of code found here and there.
But the functions.php won't save it, and others variations of this code has succeeded to register in the functions.php but the website would then give a 500 error...
Please, does someone has any idea how to achieve this?
What am I doing wrong?
Thanks.

EDIT 1 : Alright, so I got this code to actually be registered in the functions.php by the editor without breaking, but on the site, I still get the internal server error. Like something is not computing or something.

EDIT 2 (29/01/2017)
I used the ACF plugin I had purchased a long time ago but didn't find any suitable purpose... so far.
Here is the working code I was able to come up with. This is not a code masterpiece and I won't get any award for this, but it seems to be working so far. At least, it allows me to get a TRUE/FALSE statement that I can use in a if condition to change the add_to_cart button to a Your_box_is_full button.
Indeed, I didn't need any global $woocommerce or $product !
function get_cart_volume() {
  $cart_volume = 0;
  foreach( WC()->cart->get_cart() as $cart_item ) {
     $item_id = $cart_item['product_id'];
     $item_volume = get_field('product_volume', $item_id);
     $item_qty = $cart_item['quantity'];
     $vol_by_qty = $item_volume * $item_qty;
     $cart_volume += $vol_by_qty;
   }
  return $cart_volume;
}

function check_if_full($candidate) {
  $max_volume = 100;
  $candidate = $product->id;
  $a_volume = get_field('product_volume', $candidate);
  $b_volume = get_cart_volume();
  $check_volume = $a_volume + $b_volume;
    if ($check_volume > $max_volume)
      return true;
   else
      return false;
}

//Just a function to see if it's working on the cart page fur debugging purpose
add_action( 'woocommerce_check_cart_items', 'current_volume');
function current_volume() {
  if (is_cart() || is_checkout()) {
    global $woocommerce;
    $current_volume = get_cart_volume();
    wc_add_notice( sprintf( 'Volume is %s.',    $current_volume ),
    'error' );
   }
}

A: As Helgatheviking says, you get already, with woocommerce_is_purchasable hook in your hooked function, the $product object as 2nd argument. So you don't need and you have to remove global $woocommerce, $product; to make it work without throwing an error.
Your code is going to be:
add_filter('woocommerce_is_purchasable', 'if_room_is_purchasable', 10, 2);
function if_room_is_purchasable ($is_purchasable, $product){

    $cart_volume = 0;
    $max_volume = 100;

    foreach( WC()->cart->get_cart() as $cart_item ){
        $item_id = $cart_item['product_id'];
        $terms = get_the_terms( $item_id, 'pa_pdt_volume');
        foreach($terms as $key => $term){
            $cart_volume += $term->name; // May be better with $term->slug;
        }
    }

    $candidate_volume = $cart_volume + $product->get_attribute( 'pa_pdt_volume' );

    if ( $candidate_volume > $max_volume )
        return false;
    else
        return true;
  }

This should work now without error.


text:
Q: What are the dimension of View Controller in xcode? As you can see the frame with X=0,Y=209 Width = 600 units and Height = 391 units.
I want to know what is ACTUALLY type of unit they are. i.e. are they points or pixels or what exactly? This question arises from the situation that if I want to move/slide down/set a sub-View in View Controller using storyboard P pixels down from top ? than what should I set the value of y-coordinate in that picture below which have currently 209 units in that settings?

A: This is in points and not pixels. And doesn't take into consideration if the device is retina supported or not.


text:
Q: Word application reference from VSTO to net core class library I developed a VSTO Word add-in and a class library (net 4.7.2) in C#. This add-in sets a variable in the class library with the current word application object and calls methodes of the class library to manipulate word documents.
All works well.
This week, I converted the class library to net core (referencing the interop.microsoft.office.interop.word) and it compiled successfully. :)
But the VSTO add-in can not set the application.word reference variable in the class library anymore. It's not compatible and throws an error.
I tried to get an object of the running Word application from within the class library but Marshal.GetActiveObject is not in net core available.
Is there a way to overcome this problem?


text:
Q: java hibernate @ManyToMany with composite key and common field org.hibernate.MappingException: Repeated column in mapping for collection I have this tables :

*

*tbShop with fields

*

*idShop

*idAppli

*Name

*tbCategorie with fields

*

*idCategorie

*idAppli

*categName

*tbCategorieShop using for relation manytomany between tbShop and tbCategorie with fields

*

*idShop

*idAppli

*idCategorie

Entity Shop :
@Entity
@Table(name = "tbShop")
public class Shop implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected ShopPK shopPK;
    @Column(name = "commNom")
    private String name;

    @ManyToMany( fetch=FetchType.EAGER)
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.ALL})
    @JoinTable(name = "tbCategorieShop",
            joinColumns = {
                @JoinColumn(name = "idAppli", referencedColumnName = "idAppli")
                , @JoinColumn(name = "idShop", referencedColumnName = "idShop")}
            , inverseJoinColumns = {
                @JoinColumn(name = "idCategorie", referencedColumnName = "idCategorie")
                , @JoinColumn(name = "idAppli", referencedColumnName = "idAppli")}

    )
    private List<Categorie> tbCategorie ;

Entity Categorie:
@Entity
@Table(name = "tbCategorie")
public class Categorie implements Serializable {

    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected CategoriePK categoriePK;

    @Column(name = "categName")
    private String categName;

    @JoinTable(name = "tbCategorieShop", joinColumns = {
        @JoinColumn(name = "idCategorie", referencedColumnName = "idCategorie")
        , @JoinColumn(name = "idAppli", referencedColumnName = "idAppli")}
           , inverseJoinColumns = {
        @JoinColumn(name = "idAppli", referencedColumnName = "idAppli")
        , @JoinColumn(name = "idShop", referencedColumnName = "idShop")}
    )
    @ManyToMany
    private Collection<Shop> shopCollection;
    ...

Primary Key ShopPk
@Embeddable
public class ShopPK implements Serializable {

    @Basic(optional = false)
    @Column(name = "idAppli")
    private int idAppli;
    @Basic(optional = false)
    @Column(name = "idShop")
    private String idShop;
... }

Primary Key CategoriePk
@Embeddable
public class CategoriePK implements Serializable {
    @Basic(optional = false)
    @Column(name = "idCategorie")
    private int idCategorie;
    @Basic(optional = false)
    @Column(name = "idAppli")
    private int idAppli;

and I have error
Caused by: org.hibernate.MappingException: Repeated column in mapping for collection: hello.Categorie.shopCollection column: id_appli

Is it possible to have common field in this entites for ManyToMany relation ?

A: The issue you are facing is because the field "idAppli" is getting repeated in Shop and Categorie entities.
You can mark this field as insertable=false and updatable=false at one of the locations at should fix the issue


text:
Q: How to fix bugs in my i2c bit bang python library? I have a problem with my i2c library on raspberry pi zero.
I have written my code in python using many tutorials but none of them was fully sufficient. In this code time.sleep() is missing, but even when included, problem still exists. It can communicate with device but inproperly. It was tested on device BME280.
import RPi.GPIO as GPIO
import time

class SMBus(object):

    pin_SCL = 0
    pin_SDA = 0
    signal = []

    def __init__(self, bus=-1):
        GPIO.setmode(GPIO.BOARD)
        self.set_pin(13, 11)
        self.start()

    def set_pin(self, SCL, SDA):
        self.pin_SCL = SCL
        self.pin_SDA = SDA
        GPIO.setup(self.pin_SCL, GPIO.OUT)

    def start(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)

        GPIO.output(self.pin_SCL, GPIO.HIGH)
        GPIO.output(self.pin_SDA, GPIO.HIGH)

        GPIO.output(self.pin_SDA, GPIO.LOW)
        GPIO.output(self.pin_SCL, GPIO.LOW)

    def stop(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)

        GPIO.output(self.pin_SDA, GPIO.LOW)

        GPIO.output(self.pin_SDA, GPIO.HIGH)
        GPIO.output(self.pin_SCL, GPIO.HIGH)

    def send_byte(self, byte):
        GPIO.setup(self.pin_SDA, GPIO.OUT)

        for i in range(8):
            GPIO.output(self.pin_SDA, byte & 0b10000000)
            GPIO.output(self.pin_SCL, GPIO.HIGH)
            GPIO.output(self.pin_SCL, GPIO.LOW)
            byte = byte << 1

    def acknowledge_from_slave(self):
        GPIO.setup(self.pin_SDA, GPIO.IN)

        GPIO.output(self.pin_SCL, GPIO.HIGH)
        status = GPIO.input(self.pin_SDA)
        GPIO.output(self.pin_SCL, GPIO.LOW)

        if (status == GPIO.HIGH):
            print("BYTE NOT RECEIVED")

    def acknowledge_from_master(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)

        GPIO.output(self.pin_SCL, GPIO.HIGH)
        GPIO.output(self.pin_SDA, GPIO.LOW)
        GPIO.output(self.pin_SCL, GPIO.LOW)

    def receive_byte(self):
        byte = ''

        GPIO.setup(self.pin_SDA, GPIO.IN)

        for i in range(8):
            GPIO.output(self.pin_SCL, GPIO.HIGH)
            byte = byte + str(GPIO.input(self.pin_SDA))
            GPIO.output(self.pin_SCL, GPIO.LOW)

        byte = int(byte, 2)
        return byte

    def write_byte_data(self, DEVICE, address, byte):
        self.start()
        self.send_byte(DEVICE*2+0)
        self.acknowledge_from_slave()
        self.send_byte(address)
        self.acknowledge_from_slave()
        self.send_byte(byte)
        self.acknowledge_from_slave()

    def read_byte_data(self, DEVICE, address):
        self.start()
        self.send_byte(DEVICE*2+1)
        self.acknowledge_from_slave()
        self.send_byte(address)
        self.acknowledge_from_master()
        return self.receive_byte()

I expect to get proper temperature from my device (BME280).

A: You were very close. Here is working solution:
import RPi.GPIO as GPIO
import time

class SMBus(object):

    pin_SCL = 0
    pin_SDA = 0
    delay = 0.001

    def __init__(self, bus=-1):
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BOARD)
        self.set_pin(11, 13)
        self.start()

    def set_pin(self, SDA, SCL):
        self.pin_SCL = SCL
        self.pin_SDA = SDA
        GPIO.setup(self.pin_SCL, GPIO.OUT)
        time.sleep(self.delay)

    def start(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)
        GPIO.output(self.pin_SDA, GPIO.HIGH)
        GPIO.output(self.pin_SCL, GPIO.HIGH)
        time.sleep(self.delay)
        GPIO.output(self.pin_SDA, GPIO.LOW)
        time.sleep(self.delay)

    def repeated_start(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)
        GPIO.output(self.pin_SCL, GPIO.LOW)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SDA, GPIO.HIGH)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SCL, GPIO.HIGH)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SDA, GPIO.LOW)
        time.sleep(self.delay)

    def stop(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)
        GPIO.output(self.pin_SCL, GPIO.LOW)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SDA, GPIO.LOW)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SCL, GPIO.HIGH)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SDA, GPIO.HIGH)
        time.sleep(self.delay)

    def send_ack(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)
        GPIO.output(self.pin_SCL, GPIO.LOW)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SDA, GPIO.LOW)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SCL, GPIO.HIGH)
        time.sleep(self.delay)

    def send_nack(self):
        GPIO.setup(self.pin_SDA, GPIO.OUT)
        GPIO.output(self.pin_SCL, GPIO.LOW)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SDA, GPIO.HIGH)
        time.sleep(self.delay/2)
        GPIO.output(self.pin_SCL, GPIO.HIGH)
        time.sleep(self.delay)

    def send_byte(self, byte):
        GPIO.setup(self.pin_SDA, GPIO.OUT)

        for i in range(8):
            GPIO.output(self.pin_SCL, GPIO.LOW)
            time.sleep(self.delay)
            GPIO.output(self.pin_SDA, byte & 0b10000000)
            time.sleep(self.delay/2)
            GPIO.output(self.pin_SCL, GPIO.HIGH)
            time.sleep(self.delay)
            byte = byte << 1

        self.send_ack()

    def receive_byte(self):
        byte = ''

        for i in range(8):
            GPIO.setup(self.pin_SDA, GPIO.OUT)
            GPIO.output(self.pin_SCL, GPIO.LOW)
            GPIO.output(self.pin_SDA, GPIO.HIGH)
            time.sleep(self.delay)
            GPIO.output(self.pin_SCL, GPIO.HIGH)
            time.sleep(self.delay/2)
            GPIO.setup(self.pin_SDA, GPIO.IN)
            byte = byte + str(GPIO.input(self.pin_SDA))
            time.sleep(self.delay)

        byte = int(byte, 2)
        return byte

    def write_byte_data(self, DEVICE, address, byte):
        self.start()
        self.send_byte(DEVICE*2+0)
        self.send_byte(address)
        self.send_byte(byte)
        self.stop()

    def read_byte_data(self, DEVICE, address):
        self.start()
        self.send_byte(DEVICE*2+0)
        self.send_byte(address)

        self.repeated_start()

        self.send_byte(DEVICE*2+1)
        byte = self.receive_byte()
        self.send_nack()
        self.stop()

        return byte


text:
Q: Shell Script For Loop Exits After Finishing First Loop Code works fine until the last for loop.
It tries to login database. Either, it establish a successful connection with database or not, script gives output OK/NOT OK depending to the connection and then exit the shell script. What should I do to solve this?
#!/bin/bash

read -p 'Username: ' var_username
read -sp 'Password: ' var_password

filename="$1"

while read -r line; do
name=$(sed 's/#.*$//g; s/(.*$//g; s/=.*$//g; s/).*$//g')
done < "$filename"

#retval=$? | tail -n1|grep OK

for tns in $name
do
tnsping $tns
if [ $? -eq 1 ]; then
echo $tns 'tnsping i calismiyor' >>tnslatest.log
else
echo $tns 'tnsping i calisiyor' >>tnslatest.log
working_tns+=($tns)
fi
done

#The following lines do not work properly.#
for working in $working_tns
do
echo "exit" | sqlplus -L $var_username/$var_password@$working | grep
Connected > /dev/null
if [ $? -eq 0 ]
then
    echo "OK"
 else
    echo "NOT OK"
 fi
done

For example; my tnsnames.ora file contains 4 tns.
So, I want to have for output like OK or NOT OK in total.
Thanks in advance.


text:
Q: JRuby and Swing DefaultTableModel ("no constructor with arguments matching[...]") I use Swing from JRuby and I am trying to set up a JTable with a TableModel as input.
table_headers looks something like this: ["bla", "narf", "poit"]
table_data looks something like this: [["one", "two"], ["test, test"], ["hello", "world"]]
my_model = javax.swing.table.DefaultTableModel.new(table_data,table_headers)
results in

C:/jruby/lib/ruby/site_ruby/shared/builtin/javasupport/java.rb:51:in
  `new': no constructor with arguments
  matching [class org.jruby.RubyArray,
  class org.jruby.RubyArray] on object
  (NameError)

my_model = javax.swing.table.DefaultTableModel.new(table_data.to_java,table_headers.to_java)
results in

C:/jruby/lib/ruby/site_ruby/shared/builtin/javasupport/java.rb:51:no constructor with arguments matching
  [class
  org.jruby.java.proxies.ArrayJavaProxy,
  class
  org.jruby.java.proxies.ArrayJavaProxy]
  on object  (NameError)

Any idea how to solve this?
Also: Isn't there an "easy" way to simple create a table and set the fields?
(e.g. something along the lines of:
bla = SomeTable.new(5,5)
bla[2][1] = "edited"
)
p.s. as you might see from the errormessage, I have to use windows

A: I've seen this kind of thing before with classes that have multiple constructors with similar number of args (but differing type).  JRuby sometimes has trouble picking which constructor you mean to hit (the same goes for overloaded methods).  It's easy to see why in this case: some constructors take Object[].
Luckily you can add your columns and data after instantiation:
m = javax.swing.table.DefaultTableModel.new
m.add_column("id")
m.add_column("name")
m.add_row(["1", "jimmy"].to_java)
m.add_row(["2", "robert"].to_java)

...etc

Also: Isn't there an "easy" way to simple create a table and set the fields?

You could create your own wrapper, or take a look at MonkeyBars or profligacy


text:
Q: Asynchronously receiving a file uploaded via ajax I'm using a jquery file uploader, which is damn simple to use.
Basically, what it does is, it creates an <iframe> and adds a <form method="POST"  enctype="multipart/form-data" action="settings.action">
And then, it creates a <input type="file"> inside that form and submits the form to the given action setting.
$('#sampleFile').ajaxfileupload({
  action:'AsyncFileUploadHandler.ashx' // submits the file to this url
});

And this is my handler:
<%@ WebHandler Language="C#" Class="AsyncFileUploadHandler" %>
using System;
using System.Web;
public class AsyncFileUploadHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
        // I don't know how to grap the uploaded file here.
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

I've seen MVC examples but not Web Forms. Googling really gave me nothing. And it seems that there is no duplicate of this question on SO.
So, what should I do in my handler to get the file contents?

A: I added name attribute to the file control and just context.Request.Files[0] and it worked correctly.


text:
Q: how to pass variable from one function to another function in codeigniter I have two functions in my controller like this.
function search_keyword()
{
    $keyword    =   $this->input->post('keyword');
    $this->data['result']    =   $this->mymodel->search($keyword);
    //print_r($this->data);
    //$pro_id = [];
    foreach($this->data['result'] as $key => $val){
       $pro_id[] = $val->product_id;
    }
    print_r($pro_id);
    $this->download_function();
    $this->twig->display('home.html', $this->data);
}
function download_function()
{
    //print_r($keyword);
    $this->data['re']    =   $this->csv->ExportCSV($keyword);
    $this->twig->display('home.html', $this->data);
}

I want to pass pro_id variable to download_function from search_keyword funtion.please help me to do this.
this is my model
function ExportCSV($pro_id)
{

    //print_r($keyword);
    $this->load->dbutil();
    $this->load->helper('file');
    $this->load->helper('download');
    $delimiter = ",";
    $newline = "\r\n";
    $filename = "filename_you_wish.csv";
    $query = "SELECT * FROM products WHERE product_id LIKE '%$pro_id%'";
    $result = $this->db->query($query);
    $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
    force_download($filename, $data);
}

A: function search_keyword()
{
    $keyword    =   $this->input->post('keyword');
    $this->data['result']    =   $this->mymodel->search($keyword);
    //print_r($this->data);
    //$pro_id = [];
    foreach($this->data['result'] as $key => $val){
       $pro_id[] = $val->product_id;
    }
    print_r($pro_id);
    $this->download_function($pro_id);
    $this->twig->display('home.html', $this->data);
}
function download_function($pro_id)
{
    //print_r($keyword);
    $this->data['re']    =   $this->csv->ExportCSV($keyword);
    $this->twig->display('home.html', $this->data);
}

You can pass it through parameter.

A: Its quite simple, do exactly what you would do to pass a paramter to any function.
public function search_keyword() {
    $keyword    =   $this->input->post('keyword');
    $this->data['result']    =   $this->mymodel->search($keyword);
    //print_r($this->data);
    $pro_id = [];
    foreach($this->data['result'] as $key => $val){
       $pro_id[] = $val->product_id;
    }
    print_r($pro_id);
    $this->download_function($pro_id);
    $this->twig->display('home.html', $this->data);
}

public function download_function($pro_ids) {
    //print_r($keyword);
    $this->data['re']      =   $this->csv->ExportCSV($keyword);
    $this->data['pro_ids'] =   $pro_ids;
    $this->twig->display('home.html', $this->data);
}

After some time in a chat room the solution we came up with was to chnage the code to this:
function search_keyword()
{
    $pro_id = $this->input->post('keyword');
    $this->download_function($pro_id);
    $this->twig->display('home.html', $this->data);
}

function download_function($pro_id)
{
    $this->data['re'] = $this->csv->ExportCSV($pro_id);
    $this->twig->display('home.html', $this->data);
}


text:
Q: Why I couldn't get gravity value in Cocos2d-x 3.2 I'm new with cocos2d-x. I was trying to use cocos2d-x 3.2 to build a simple physics game, but I got a problem.
At the beginning, I followed the tutorial and added these in HelloWorld.h:
private:
    PhysicsWorld* m_world;
public:
    void setPhyWorld(PhysicsWorld* world){ m_world = world; }

Then, I added these in HelloWorld.cpp:
Scene* HelloWorld::createScene()
{
    auto scene = Scene::createWithPhysics();
    auto layer = HelloWorld::create();
    layer->setPhyWorld(scene->getPhysicsWorld());
    scene->addChild(layer);
    return scene;
}

Then, I tried to get the gravity value in function init() like this:
bool HelloWorld::init()
{
    Vect g=m_world->getGravity();
    if ( !Layer::init() )
    {
        return false;
    }
    Size visibleSize = Director::getInstance()->getVisibleSize();
    return true;
}

Then, I ran it, but the program stopped at "Vect g=m_world->getGravity();"
It said that "0x00C53B44 had an Unhandled Exceptions", and I had to interrupt it.
Did anybody have the same problem before? I really appreciate if anyone can help me.

A: Please observe your code
auto layer = HelloWorld::create(); //Calling init Method of Hello World Layer

layer->setPhyWorld(scene->getPhysicsWorld()); // Setting PhysicsWorld instance to the layer

the init() method is called first and then you are setting setPhyWorld(scene->getPhysicsWorld()) so m_world = null.
If you really want physicsWorld instance in the init() method, you should customize the create & init method of HelloWorld layer and send physicsWorld instance with create() method.
//This code above header class of HelloWorld
#define CUSTOM_CREATE_FUNC(__TYPE__) \
static __TYPE__* create(PhysicsWorld* world) \
{ \
    __TYPE__ *pRet = new __TYPE__(); \
    if (pRet && pRet->init(world)) \
    { \
       pRet->autorelease(); \
       return pRet; \
     } \
     else \
     { \
        delete pRet; \
        pRet = NULL; \
        return NULL; \
      } \
}

and then
CUSTOM_CREATE_FUNC(HelloWorld); // in the header class, instead of CREATE_FUNC(HelloWorld)
virtual bool init(PhysicsWorld* world);

and
auto layer = HelloWorld::create(scene->getPhysicsWorld()); // in the createScene() Method

and finally
bool HelloWorld::init(PhysicsWorld* world)
{
   m_world = world;
   Vect g=m_world->getGravity();
   if ( !Layer::init() )
   {
      return false;
   }
   Size visibleSize = Director::getInstance()->getVisibleSize();
   return true;
}


text:
Q: How to detect the location of taps in ios 7 I have a view controller with half table view (bottom, 320x289)and half map view (top, 320,289). How can I detect location of tap?
Currently my code for the tap looks like this - when tapping, it hides the navigation bar so that the map gets some extra real estate. However, because it's not detecting location of the tap, when I tap on the tableview, I'm not able to segue into my table view controller.
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideShowNavigation)];
tap.numberOfTapsRequired = 1;
[self.view addGestureRecognizer:tap];

Ideally I would like to detect location of taps. If tapped at the top (if height <=289px), it hides navigation bar (or maybe even segue into a separate view controller where map is full screen). If tapped at the bottom (if height > 289px), then it pushes the segue into table view controller.
- (void) hideShowNavigation:(id)sender
{
    [self.navigationController setNavigationBarHidden:!self.navigationController.navigationBarHidden];

    [self hidesBottomBarWhenPushed];
}

Here's the whole code:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.navigationController.navigationBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = YES;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideShowNavigation:)];
        tap.numberOfTapsRequired = 1;
        [self.view addGestureRecognizer:tap];
}

- (void) hideShowNavigation:(id)sender
{
    CGPoint = [sender locationInView:self.view];
    CGFloat y = location.y;

    if(y<=289){
        [self.navigationController setNavigationBarHidden:!self.navigationController.navigationBarHidden];

        [self hidesBottomBarWhenPushed];
    }
}

A: In your selector:
CGPoint location = [sender locationInView:self.view];
CGFloat x = location.x;
CGFloat y = location.y;


text:
Q: next js empty render when i import data my problem is when i want to fetch data from data.json nothing display it give me many empty array when i try to console.log
screenshot:
screenshot and path of files
i tried hard to change the import path to back with ../ but nothing display to me im so wonder about this error and this is my first time i work with next js
import Image from 'next/image'

const  EventPerCityPage = ({data}) => {
  console.log("helloa"+data)
    return (

 event in london

        {data.map((ev)=>{
          <a key={ev.id} href={`/events/${ev.city}/${ev.id}`}>
             <Image width={300} height={300} alt={ev.title} src={ev.image} />

{ev.title}

{ev.description}

        })}

hello

    )
  }
  export default EventPerCityPage;

  export async function getStaticPaths (){
    const {events_categories} = await import ('/data/data.json')
    console.log(events_categories+"this code")
    const allPaths = events_categories.map(ev=>{
      return{

          params: {
            cat: ev.id.toString()
          }

      }
    })
    console.log(allPaths)
    return{
      paths: allPaths,
      fallback:false
    }
  }
  export async function getStaticProps(context){

    const id = context?.params.cat
    console.log("all path aaaaaaaa" +id)
    const {allEvents} = await import('/data/data.json')
    console.log(allEvents+"rrrrrrtttttttt")//
    const data = allEvents.filter((ev) => ev.city===id)
    console.log(data+"eeeeeeeeeezzzzzzz")
    return{
      props: {data}
    }

  }


text:
Q: Swagger CodeGen, make Proxies remove certain elements and be Simplified Is there a way to Auto Generate proxies with Swagger Io Codegen Editor, while removing certain elements? We are converting C# Apis to Angular Typescript Proxies.

*

*I have 4 methods below,

*Do not require Authentication if the statement

*Nor do I need HeadersAccept
https://editor.swagger.io/
Original Proxy:
    public getUserDepartment(departmentId: number, observe?: 'body', reportProgress?: boolean): Observable<GetUserResponse>;
    public getUserDepartment(departmentId: number, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<GetUserResponse>>;
    public getUserDepartment(departmentId: number, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<GetUserResponse>>;
    public getUserDepartment(departmentId: number, observe: any = 'body', reportProgress: boolean = false ): Observable<any> {

        if (departmentId === null || departmentId === undefined) {
            throw new Error('Required parameter departmentId was null or undefined when calling getUserDepartment.');
        }

        let headers = this.defaultHeaders;

        // authentication (Token) required
        if (this.configuration.apiKeys && this.configuration.apiKeys["Authorization"]) {
            headers = headers.set('Authorization', this.configuration.apiKeys["Authorization"]);
        }

        // to determine the Accept header
        let httpHeaderAccepts: string[] = [
            'application/json;odata.metadata=minimal;odata.streaming=true',
            'application/json;odata.metadata=minimal;odata.streaming=false',
            'application/json;odata.metadata=minimal',
            'application/json;odata.metadata=full;odata.streaming=true',
            'application/json;odata.metadata=full;odata.streaming=false',
            'application/json;odata.metadata=full',
            'application/json;odata.metadata=none;odata.streaming=true',
            'application/json;odata.metadata=none;odata.streaming=false',
            'application/json;odata.metadata=none',
            'application/json;odata.streaming=true',
            'application/json;odata.streaming=false',
            'application/json',
            'application/xml',
            'application/prs.odatatestxx-odata',
            'text/plain',
            'text/json'
        ];
        const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts);
        if (httpHeaderAcceptSelected != undefined) {
            headers = headers.set('Accept', httpHeaderAcceptSelected);
        }

        // to determine the Content-Type header
        const consumes: string[] = [
        ];

        return this.httpClient.request<GetUserResponse>('get',`${this.basePath}/api/Users/department/${encodeURIComponent(String(departmentId))}`,
            {
                withCredentials: this.configuration.withCredentials,
                headers: headers,
                observe: observe,
                reportProgress: reportProgress
            }
        );
    }

Final Intended Result:
    public getUserDepartment(departmentId: number) {

        if (departmentId === null || departmentId === undefined) {
            throw new Error('Required parameter departmentId was null or undefined when calling getUserDepartment.');
        }

        return this.httpClient.request<GetUserResponse>('get',`${this.basePath}/api/Users/department/${encodeURIComponent(String(departmentId))}`,
            {}
        );
    }

The team has over 1000+ Api methods to convert , looking for simplified code


text:
Q: ASP.NET prevent the same user being logged in multiple times I have a requirement for an ASP.NET web application whereby the same user is not allowed to be logged in multiple times. I think this is to prevent people from sharing usernames and passwords.
The problem I am having is that unless a user explicitly logs out of the system it is hard to tell if he is still logged in and using the system or not.
Hence the only reliable way I can think of to implement this is to log to database the user id, IP address and timestamp every time a user makes an interaction with the system and lock anyone else out who is not from that IP address if they try and log in within ten minutes of the last date logged in this table.
Can anyone think of a better way to manage this?

A: If you use ASP.NET MembershipProvider you can do something like this:
    protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
    {
        if (Membership.ValidateUser(Login1.UserName, Login1.Password))
        {
            int time = Membership.UserIsOnlineTimeWindow;

            MembershipUser user = Membership.GetUser(Login1.UserName, true);
            if (user != null)
            {
                if (user.IsOnline)
                {
                    lblMessaggeIsOnLine.Visible = true;
                    e.Cancel = true;
                }
                else
                    lblMessaggeIsOnLine.Visible = false;
            }
        }
    }

A: you can use SessionEnd event in global.asax if your session state mode is not SqlServer.
for example:
your config:
<sessionState timeout="15"></sessionState>

after 15min your sessionend event triggered and you can sign out user

A: You are right. You need to manage the user log-ins and act accordingly. Let me knonw whether you are using your own provider or using ASP.NET provider. The default provider has some options within it.


text:
Q: Question related to number of distinct forcing extensions of a countable model A bit of context: the below question is motivated by roughly the following scenario: we have some countable model $\mathcal{M}$, and want to "count" the number of functions/sets $f$ such that $\mathcal{M}[f]$ (in the sense of a forcing extension) is a "mostly-elementary" extension; I'm curious if the number of such extensions can ever be less then the continuum, under the negation of the continuum hypothesis. However the context i'm working in is weak arithmetic so the definition of "forcing extension" and "model" are a bit different then in the standard set-theoretic forcing where this question is (presumably?) already well-understood.
Formal question: Say we have a countable system of "constraints":
$$\mathcal{C} = \{C_i \subseteq \mathbb{N}^{\mathbb{N}}\}_{i \in \mathbb{N}}$$
where each constraint is "finitely meetable" in the following sense: we say a constraint $C$ is finitely meetable if for any finite partial function $r: [n] \to \mathbb{N}$, there is some finite extension $\hat{r}: [m] \to \mathbb{N}, m \geq n$ of $r$ such that whenever $f: \mathbb{N} \to \mathbb{N}$ agrees with $\hat{r}$ we have that $f \in C$ (I imagine there is a standard name for this, as this type of contraint arises naturally in Cohen forcing, which is where the motivation comes from).
We will say that $f: \mathbb{N}\to \mathbb{N}$ "satisfies the constraint $C_i$" if $f \in C_i$, and that it satisfies $\mathcal{C}$ if it satisfies every $C_i \in \mathcal{C}$. My question is now, what can we say in general about the number of functions which satisfy $\mathcal{C}$? Under the continuum hypothesis the answer is always the continuum $\mathfrak{c}$, since:
(1) There are at most $\mathfrak{c}$-many functions $f: \mathbb{N}\to\mathbb{N}$
(2) There are at least uncountably many by a basic diagonalization argument: say we had some countable family $\mathcal{F} = \{f_i\}_{i \in \mathbb{N}}$ of functions satisfying $\mathcal{C}$. Then we can build a new satisfying function outside of $\mathcal{F}$ by extending some finite partial function piece by piece, on even steps extending enough to satisfy some constraint $C_i$, and on odd steps extending enough to differ from some $f_i$.
However, it is not clear to me how to strengthen this second argument to show unconditionally that there are at least $\mathfrak{c}$-many satisfying functions, and I'm curious if there could be a possible countable system of constraints $\mathcal{C}$ which admits say, only $\aleph_1$ many satisfying assignments, and thus less then $\mathfrak{c}$ assuming the negation of CH?


text:
Q: Java app can't be closed even "CLOSE ON EXIT", TCP Server I just wanna make a Server application which gets Strings and put these into a JTextArea. There are two errors I get, even no errors are showed.

*

*the window can't be closed although I used this statement:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

*If the client connects to the Server, the whole window turns black. What could be the error? Here the code:

Client:
public Main() {
    super("Main");
    setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/images/ic.png")));

    panelFields = new JPanel();
    panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));
    panelFields2 = new JPanel();
    panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));

    scrollPane = new JScrollPane();
    panelFields.add(scrollPane);

    getContentPane().add(panelFields);
    getContentPane().add(panelFields2);
    getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
    setSize(326, 264);
    setVisible(true);

    messagesArea = new JTextArea();
    scrollPane.setViewportView(messagesArea);
    messagesArea.setColumns(30);
    messagesArea.setRows(10);
    messagesArea.setEditable(false);

    startServer = new JButton("Start");
    startServer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            socketConnection();
            startServer.setEnabled(false);
        }
    });

    panelFields.add(startServer);
}

And the Server connection:
private void socketConnection() {
    try {
        serverSocket = new ServerSocket(9090);
        System.out.println("Listening: " + serverSocket.getLocalPort());
    } catch (IOException e) {
        e.printStackTrace();
    }

    while (true) {
        try {
            socket = serverSocket.accept();
            dataInputStream = new DataInputStream(socket.getInputStream());
            System.out.println("ip: " + socket.getInetAddress());
            System.out.println("message: " + dataInputStream.readUTF());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Maybe you could tell me, how I can fix those problems and also, how I can make, that the server doesn't close the socket although the client disconnects. I wanna reconnect maybe later...

A: You need to start your socket listener in its own thread, and you need to add a window close listener that shuts down that thread.
For example:
private ServerSocket serverSocket = null;
private boolean done = false;

private void startServer() {
    Thread t = new Thread(new Runnable() {
        public void Run() {
            socketConnection();
        });
    }
    t.start();
}

private void socketConnection() {
    try {
        serverSocket = new ServerSocket(9090);
        System.out.println("Listening: " + serverSocket.getLocalPort());

        while (!done) {
            try {
                final Socket socket = serverSocket.accept();
                Thread t = new Thread(new Runnable() {
                    public void Run() {
                        handle(socket);
                    }
                });
                t.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void handle(Socket socket) {
    if (socket == null) return;
    try {
        dataInputStream = new DataInputStream(socket.getInputStream());
        System.out.println("ip: " + socket.getInetAddress());
        System.out.println("message: " + dataInputStream.readUTF());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dataInputStream != null) {
            try {
                dataInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public void windowClosing(WindowEvent e) {
    done = true;
    socketServer.close();
}

Your button click listener should call startServer(), then your window close function would set done = true and call socketServer.close().
Now you have one thread for the UI, one thread for the socket server, and one thread for each connection to the server.


text:
Q: close multiple window in titanium I am opening a new Window when a button is pressed in the current displayed window. When the user clicks back or the back button in android I close my current window and it works fine. But when the user presses the home button of the application to go to the first window, all the other added window will keep there in background, and in android if the user presses the back button of the phone the app goes to the last opened window and not where it should go.
this is how I open a new window:
view.addEventListener('click', function(e) {
    var win = Ti.UI.createWindow({
        url : 'List.js'
    });
    win.open();
});

To close the window I use:
Ti.UI.currentWindow.close();

For example I have opened window A,B,C,D and in the D window I press the home button of the app where I must go to the B window. So I need to close the C and D window but I don't now how to close the C window that is in background.
I'm not using Alloy

A: I believe a way to achieve this is to keep track of the opened windows.
For example, in alloy.js you can have:
Alloy.Globals.openWindows = []

(If your not using Alloy, just use some other global variable)
Now your event handler will look like this:
view.addEventListener('click', function(e) {
    var win = Ti.UI.createWindow({
        url : 'List.js'
    });
    Alloy.Globals.openWindows.append(win);
    win.open();
});

Now if you need close the window and parent windows you can just do this:
Alloy.Globals.openWindows.pop().close()

You can repeat the above line as many times as needed to close the required number of windows. For example if you needed to close 3 parent windows you can just do the following:
for (var i = 0: i < 3; i++) {
    Alloy.Globals.openWindows.pop().close()
}

If you need to close ALL windows, except the first you can do this (assuming the first window was not added to openWindows):
while(Alloy.Globals.openWindows.length > 0) {
    Alloy.Globals.openWindows.pop().close()
}


text:
Q: Writing a connection string when password contains special characters I'm using SQLalchemy for a Python project, and I want to have a tidy connection string to access my database. So for example:
engine = create_engine('postgresql://user:pass@host/database')

The problem is my password contains a sequence of special characters that get interpreted as delimiters when I try to connect.
I realize that I could just use engine.URL.create() and then pass my credentials like this:
import sqlalchemy as sa

connection_url = sa.engine.URL.create(
    drivername="postgresql",
    username="user",
    password="p@ss",
    host="host",
    database="database",
)
print(connection_url)
# postgresql://user:p%40ss@host/database

But I'd much rather use a connection string if this is possible.
So to be clear, is it possible to encode my connection string, or the password part of the connection string - so that it can be properly parsed?

A: In Python 3.x, you need to import urllib.parse.quote:

The urllib module has been split into parts and renamed in Python 3 to
urllib.request, urllib.parse, and urllib.error.

When you are trying to connect database MySQL with password which contains sequence of special characters and your python version is Python3
user_name is your userid for database
database is your database name
your_password password with special characters
 from urllib.parse import quote
 from sqlalchemy.engine import create_engine
 engine = create_engine('mysql+mysqlconnector://user_name:%s@localhost:3306/database' % quote('your_password'))

A: You need to URL-encode the password portion of the connect string:
from urllib.parse import quote_plus
from sqlalchemy.engine import create_engine
engine = create_engine("postgres://user:%s@host/database" % quote_plus("p@ss"))

If you look at the implementation of the class used in SQLAlchemy to represent database connection URLs (in sqlalchemy/engine/url.py), you can see that they use the same method to escape passwords when converting the URL instances into strings.

A: METHOD 1:
The password contains "@", you can escape the "@" character using "%40" instead.
BEFORE:
# mssql+pymssql://username:password@databaseserver/database

mssql+pymssql://admin:admin123@10.10.10.110/dbtest

AFTER:
mssql+pymssql://admin:admin%40123@10.10.10.110/dbtest

METHOD 2:
Encode the password using urllib.parse.quote_plus.
DATABASE_PASSWORD = "admin@123"

# to elimate the error, if the password contains special characters like '@'
DATABASE_PASSWORD_UPDATED = urllib.parse.quote_plus(DATABASE_PASSWORD)

Here is the complete code snippet :
import os, sys, click, urllib
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

# Make sure to replace below data with your DB values
DATABASE_HOST = "10.10.10.110"
DATABASE_NAME = "dbtest"
DATABASE_USERNAME = "admin"
DATABASE_PASSWORD = "admin@123"

app = Flask(__name__)

# to elimate the error, if the password contains special characters like '@'
# replace the DATABASE_PASSWORD with DATABASE_PASSWORD_UPDATED.

DATABASE_PASSWORD_UPDATED = urllib.parse.quote_plus(DATABASE_PASSWORD)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pymssql://'+DATABASE_USERNAME+':'+DATABASE_PASSWORD_UPDATED+'@'+DATABASE_HOST+'/'+DATABASE_NAME
app.config['SQLALCHEMY_ECHO'] = True

db = SQLAlchemy(app)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)


text:
Q: When to use /proc and when /dev I need to write a kernel module that is not a device driver. That module will be communicating with some user space processes. As I dont want to use ioctl(), I am left with either creating a file in /proc directory or creating a device file in /dev directory.
Question: How do i decide between /proc and /dev. Is this just a judgement call or are there any unwritten agreements on using these two.

A: You will have a great deal of difficulty getting a new interface added into /proc/. The kernel developers are unhappy that it has become a dumping ground for miscellaneous interfaces, and unless you are actually modifying something about processes via /proc/pid/, I think you'll have trouble convincing the kernel community to accept it.
A device file in /dev/ may be acceptable, even for modules that aren't really device drivers. (e.g., /dev/kvm, /dev/pts, /dev/ecryptfs, /dev/fuse, /dev/kmsg, /dev/ptmx, etc.) However, device files are too-often easier to manipulate with ioctl(), and I think you're right to avoid it if you can.
The current trend in kernel circles is sysfs or custom filesystems. The sysfs approach is based upon single-value-per-file semantics, intended to be manipulated with echo and cat. It's wonderful for users if it works for you. Custom filesystems lets you write very specific binary-capable interfaces, and fs/libfs.c should help you write your own filesystem to your own needs. (I don't know anyone who has used configfs, but I've always thought it looked neat. Maybe it would suit your module?)


text:
Q: Spinnaker Installation via helm in terraform I am trying to install spinnaker on Kubernetes with Terraform using the following resource:
resource "helm_release" "spinnaker" {
  chart      = "stable/spinnaker"
  name       = "spinnaker"
  repository = "https://helmcharts.opsmx.com/"
  version    = "2.2.3"

I keep on receiving the following error message:
Error: chart "stable/spinnaker" version "2.2.3" not found in https://helmcharts.opsmx.com/ repository
  on spinnaker-helm/helm.tf line 1, in resource "helm_release" "spinnaker":
   1: resource "helm_release" "spinnaker" {

Here is the artifact hub chart we try to refer to:
https://artifacthub.io/packages/helm/spinnaker/spinnaker
I am using terraform 0.14 and helm provider 1.2.3
Thank you for your help.
Charles

A: The chart is "spinnaker/spinnaker" and not "stable/spinnaker".
In general stable repo was deprecated and wiped on Nov 2020.
Those are the available charts in the repot you are adding:
 ebiriukov@Evgenis-MacBook-Pro ➜  ~ helm search repo spinnaker                                                                                <aws:iris-dev>
WARNING: Kubernetes configuration file is group-readable. This is insecure. Location: /Users/ebiriukov/.kube/config
WARNING: Kubernetes configuration file is world-readable. This is insecure. Location: /Users/ebiriukov/.kube/config
NAME                        CHART VERSION   APP VERSION DESCRIPTION
spinnaker/spinnaker         2.2.3           1.22.2      Open source, multi-cloud continuous delivery pl...
spinnaker/oes               3.4.0           3.4.0       OES is a non-forked version of OSS spinnaker
spinnaker/opsmx-autopilot   2.0.0           2.9.10      Autopilot is a release verification platform