text:
Q: What Headers to use when using HttpResponseCache.get I'm trying to use httpResponseCache to cache some of my requests. Problem is, I'd like to know if the request is cached before making the request.
I saw in the source for HttpResponseCache that there is a get method that takes in (URI, requestMethod, Map< String, List< String > >) and returns a cachedResponse. I've tried a couple different sets of (URI, "GET", Headers), but I can't seem to figure out what the headers would be, and every time I request a cachedResponse using get, I get back null, even though there is a response cached.
Has anyone been successful in using the get method to determine if a request is cached before making the request / alternatively is there a different way to check if something is cached before making the request? I understand I can use hitCount to figure out if the response was taken from cache, and I can use the "Cache-Control","only-if-cached" to force a cached response. I would just like to be able to check if it is cached.
Here's some code I've used to try to accomplish this. In the onCreate of the Activity, I do initialize the cache this way:
try {
               File httpCacheDir = new File(this.getCacheDir(), "http");
               long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
               Class.forName("android.net.http.HttpResponseCache")
                       .getMethod("install", File.class, long.class)
                       .invoke(null, httpCacheDir, httpCacheSize);
        }
            catch (Exception httpResponseCacheNotAvailable) {
                Log.d(TAG,"HttpResponseCache not available.");
           }

And then try to use it this way:
   HttpResponseCache cache = HttpResponseCache.getInstalled();
            try {
                HashMap map = new HashMap<String, List<String>>();
                CacheResponse response = cache.get(URI.create(base_url), "GET", map);
                //response is always null
                Log.d(TAG," Response is!:"+response);
            } catch (IOException e) {
                e.printStackTrace();
            }

Sorry/thanks/ Any help is super appreciated!

A: HttpURLConnection connection = (HttpURLConnection)url.openConnection();
HttpResponseCache cache = HttpResponseCache.getInstalled();
cache.get(new URI(url.toString()), "GET", connection.getHeaderFields());

That is how it should be done, but I haven't tried it yet.


text:
Q: Ajax post back causing all other web requests to hang until the method request finishes Edit
Ok thats typical, I figure out a possible solution to the problem just after I ask for help!
My code is now using Threading to spawn a new thread to perform the indexing independently from the current request. It seems to be working.
The code that I came up with:
private static WebDocument Document;
private static readonly object Locker = new object();

[WebMethod(true)]
public static string Index(string uri)
{
  WebDocument document = WebDocument.Get(uri);

  if (document == null)
    document = WebDocument.Create(uri);

  Document = document;
  Thread thread = new Thread(IndexThisPage);
  thread.Start();

  //document.Index();

  return "OK";
}

public static void IndexThisPage()
{
  lock (Locker)
  {
    Document.Index();
  }
}

Orginal Question
On all of my pages I have an ajax post that performs an index on the current page as well as all documents on the page. The indexer I'm using is Keyoti.
What seems to happen is when one page is being indexed any request to any other page seems to not respond (i.e. its stuck on "Waiting for server") until the indexing is finished. Note: I'm loading the different pages from the same machine, because the code is local.
Here's the ajax I'm using:
<script type="text/javascript" src="/Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
  $(window).load(function () {
    $.ajax({
      type: "POST",
      url: "/DoIndex.aspx/Index",
      data: "{ uri: '" + self.location + "' }",
      contentType: "application/json; charset=utf-8",
      dataType: "json"
    });
  });
</script>

And the method it calls:
[WebMethod(true)]
public static string Index(string uri)
{
  WebDocument document = WebDocument.Get(uri);

  if (document == null)
    document = WebDocument.Create(uri);

  document.Index();

  return "OK";
}

Anyone have any thoughts?

A: your answer is completely right.
If you using .Net 4, I'd like to let you know you could use task instead of thread.
I guess it's easer to read and also it'll let the OS to decide how manage threads.
this is the good explanation as well.
private static WebDocument Document;
private static readonly object Locker = new object();

[WebMethod(true)]
public static string Index(string uri)
{
  WebDocument document = WebDocument.Get(uri);

  if (document == null)
    document = WebDocument.Create(uri);

  Document = document;

  // start a new background thread
  var System.Threading.Tasks.task = Task.Factory.StartNew(() => IndexThisPage);

  //document.Index();

  return "OK";
}

public static void IndexThisPage()
{
  lock (Locker)
  {
    Document.Index();
  }
}

Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which method is called earlier SignalR Configuration or ASP.NET Application_Start? I've SignalR 2.x and ASP.NET with ServiceStack framework. It makes to entry points, one per each pipeline:

*

*Startup.Configuration(IAppBuilder app) -- for SignalR startup configuration
and

*Global.Application_Start() in Global.asax.cs -- for initializing the standard ASP.NET pipeline.

I'd like to pass some object that has been created in Application_Start() into Configuration() (e.g. IOC instance). For this I'd like to be sure that Configuration() will be called after Application_Start().
I found this stackoverflow question. What bothering me is the slightly later definition. Does it mean the execution is overlapped? Is it promised that the code in Configuration() will be called after Application_Start() for sure?
Does anybody know how it is exactly working and what is this delay? Has anyone had an experience with coding these methods?
Thank you

A: Iv decided to confirm my previous (and incorrect) statement by experiment and indeed Application_Start() method is called before any Owin startup class which means before SignalR Configuration (assuming recommended SignalR configuration using Owin startup of course).
It is true that Owin (Microsoft.Owin.Host.SystemWeb to be precise - which is Owin host adapter for IIS) uses System.Web.PreApplicationStartMethodAttribute to hook into ASP.NET pipeline but only to register its own OwinHttpModule (and yes this registration happens before Application_Start()). But Owin startup classes are discovered and run during OwinHttpModule.Init() which happens after Application_Start(). Slightly later means exactly that - both methods are called during execution of HttpApplication.RegisterEventSubscriptionsWithIIS private method. No overlaping for sure...
Sidenote: Imho there is no reason to have startup\configuration in two different places in application and because OWIN is the next big thing in ASP.NET world (see vNext or SignalR) and offers more benefits than Application_Start() (such as switching startup configuration in web.config), I'm definitely planning to migrate all Application_Start() code to OWIN startup.
-> No reason to worry about what's happening 1st ;)
And this is also my suggestion to you!


text:
Q: k8s fails scheduling of local ssd volume on GCP I'm trying to specify Local SSD in a Google Cloud as a PersistedVolume. I followed the docs to set up the automated SSD provisioning, and running kubectl get pv returns a valid volume:
NAME                CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM     STORAGECLASS   REASON    AGE
local-pv-9721c951   368Gi      RWO            Delete           Available             local-scsi               1h

The problem is that I cannot get my pod to bind to it. The kubectl get pvc keeps showing this:
NAME      STATUS    VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   AGE
mapdata   Pending                                       local-scsi     7m

and kubectl get events gives me these:
LAST SEEN   FIRST SEEN   COUNT     NAME                                                KIND                    SUBOBJECT   TYPE      REASON                 SOURCE                        MESSAGE
7m          7m           1         v3tiles.1551c0bbcb23d983                            Service                             Normal    EnsuredLoadBalancer    service-controller            Ensured load balancer
2m          8m           24        maptilesbackend-8645566545-x44nl.1551c0ae27d06fca   Pod                                 Warning   FailedScheduling       default-scheduler             0/1 nodes are available: 1 node(s) didn't find available persistent volumes to bind.
2m          8m           26        mapdata.1551c0adf908e362                            PersistentVolumeClaim               Normal    WaitForFirstConsumer   persistentvolume-controller   waiting for first consumer to be created before binding

What would i need to do to bind that SSD to my pod?  Here's the code I have been experimenting with:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: maptilesbackend
  namespace: default
spec:
  selector:
    matchLabels:
      app: maptilesbackend
  strategy:
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: maptilesbackend
    spec:
      containers:
      - image: klokantech/openmaptiles-server
        imagePullPolicy: Always
        name: maptilesbackend
        volumeMounts:
          - mountPath: /data
            name: mapdata
            readOnly: true
      volumes:
        - name: mapdata
          persistentVolumeClaim:
            claimName: mapdata
            readOnly: true
---
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: "local-scsi"
provisioner: "kubernetes.io/no-provisioner"
volumeBindingMode: "WaitForFirstConsumer"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mapdata
spec:
  storageClassName: local-scsi
  accessModes:
    - ReadOnlyMany
  resources:
    requests:
      storage: 300Gi

A: ReadOnlyMany doesn't make sense for local SSDs
As per the docs:

ReadOnlyMany – the volume can be mounted read-only by many nodes

You can't mount a local SSD on many nodes because it's local to one node only.

A: It turns out that accessMode: ReadOnlyMany does not work in this case. Not sure how to make it work... will post if I find more information.


text:
Q: How to attach `\x` at the beginning of some value and make string out of it? I have written below code in sass / scss. Here i am facing an issue i.e. when i'm trying to loop and concatenate value with \ . I'm getting space when my value contains alpha numeric. Kindly suggest how to overcome form this
SCSS =>>
Input :
$data: (
a:2766,
b:27B3,
d:1F48C
);

@each $value1, $value2 in $data {
 .#{$value1}{
   content: str-slice("\x",1,1)+($value2);
 }
}

Output :
.a {
  content: "\2766";
}

.b {
  content: "\27B 3";
}

.d {
  content: "\1F 48C";
}

A: It looks like this is a bug in Sass itself. Update your Sass and your problem should be fixed.
You can see this is the case on sass playground. Copy and paste your sass code there and then select Sass v3.3.14 and Sass v3.4.21 (or any later/newer) and you'll see the difference. :)
Edit:
In order to add \x at the beginning, you can do it this way:
SCSS (Sass v3.4.21):
$data: (
  a: 2766,
  b: 27B3,
  d: 1F48C
);

@each $value1, $value2 in $data {
 .#{$value1}{
   content: str-insert(#{$value2}, "\\x", 1);
 }
}

CSS output:
.a {
  content: \x2766;
}

.b {
  content: \x27B3;
}

.d {
  content: \x1F48C;
}

str-insert puts a string inside other string.  \\ in \\x escapes to single \x. Oh, and as the reference states, first character in sass is 1, not 0.


text:
Q: Http get request in Android 2.3.3 I need help with sending HTTP GET request. My code is as follows:
    URL connectURL = new URL("url");
    HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("GET");

    conn.connect();
    conn.getOutputStream().flush();
    String response = getResponse(conn);

But it fails at getResponse(conn); Why?

A: GET request could be used like this:
try {
    HttpClient client = new DefaultHttpClient();
    String getURL = "http://www.google.com";
    HttpGet get = new HttpGet(getURL);
    HttpResponse responseGet = client.execute(get);
    HttpEntity resEntityGet = responseGet.getEntity();
    if (resEntityGet != null) {
        // do something with the response
        String response = EntityUtils.toString(resEntityGet);
        Log.i("GET RESPONSE", response);
    }
} catch (Exception e) {
    e.printStackTrace();
}

A: I believe setDoOutput(true) implies POST automatically.

A: I am using this piece of code for GET response which is working fine on my end:
HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(requestUrl);

    HttpResponse response=null;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        Log.d(TAG,"1. "+e.toString());

    } catch (IOException e) {
        Log.d(TAG,"2. "+e.toString());

    }
    int status_code=response.getStatusLine().getStatusCode();
    Log.d(TAG,"Response Code returned ="+status_code);

    BufferedReader in=null;
    try {
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IllegalStateException e) {
        Log.d(TAG,"3. "+e.toString());
    } catch (IOException e) {
        Log.d(TAG,"4. "+e.toString());
    }

    StringBuffer sb = new StringBuffer("");
    String line = "";
    String newline = System.getProperty("line.separator");
    try {
        while ((line = in.readLine()) !=null){
            sb.append(line + newline);
        }
        String data = sb.toString();
        Log.d(TAG,data);
    } catch (IOException e) {
        Log.d(TAG,"5. "+e.toString());
    }
    try {
        in.close();
    } catch (IOException e) {
        Log.d(TAG,"6. "+e.toString());
    }
    String data = sb.toString();

    try {
        if(status_code==200 || status_code==401){
            JSONObject responseJSONObject = new JSONObject(data);
            responseJSONObject.put("tpg_status_code", status_code);
        }
    } catch (JSONException e) {
        Log.d(TAG,"6. "+e.toString());
    }

A: i use this code and it works perfectly:
public class HttpGetAndroidExample extends Activity {

            TextView content;
            EditText fname,email,login,pass;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

                  super.onCreate(savedInstanceState);
                 setContentView(R.layout.activity_http_get_android_example);

                 content   =  (TextView)findViewById(R.id.content);
                 fname     =  (EditText)findViewById(R.id.name);
                 email      =  (EditText)findViewById(R.id.email);
                 login       =  (EditText)findViewById(R.id.loginname);
                 pass       =  (EditText)findViewById(R.id.password);

               Button saveme=(Button)findViewById(R.id.save);

        saveme.setOnClickListener(new Button.OnClickListener(){
          public void onClick(View v)
           {
                      //ALERT MESSAGE
                     Toast.makeText(getBaseContext(),"Please wait, connecting to server.",Toast.LENGTH_LONG).show();

            try{

                 // URLEncode user defined data

                   String loginValue    = URLEncoder.encode(login.getText().toString(), "UTF-8");
                   String fnameValue  = URLEncoder.encode(fname.getText().toString(), "UTF-8");
                   String emailValue   = URLEncoder.encode(email.getText().toString(), "UTF-8");
                   String passValue    = URLEncoder.encode(pass.getText().toString(), "UTF-8");

                // Create http cliient object to send request to server

                   HttpClient Client = new DefaultHttpClient();

                // Create URL string

                 String URL = "http://androidexample.com/media/webservice/httpget.php?user="+loginValue+"&name="+fnameValue+"&email="+emailValue+"&pass="+passValue;

                //Log.i("httpget", URL);

               try
                {
                              String SetServerString = "";

                            // Create Request to server and get response

                              HttpGet httpget = new HttpGet(URL);
                             ResponseHandler<String> responseHandler = new BasicResponseHandler();
                             SetServerString = Client.execute(httpget, responseHandler);

                              // Show response on activity

                             content.setText(SetServerString);
                 }
               catch(Exception ex)
                  {
                         content.setText("Fail!");
                   }
            }
          catch(UnsupportedEncodingException ex)
           {
                   content.setText("Fail");
            }
        }
    });

}
}


text:
Q: do..while loop not stopping I am trying to create interval semi diving method (numerical method) and in the program there is a do/while loop, which does not work correctly:
double Funkcija(double x){
    double result = -1/(1+abs(x));
    return result;
}

...
double x[20] = {};
x[0] = 1; //initial point
int k = 1;  // index (from 1 because 0 is giving (x0)
do
{
    cout << "x[" << k << "]= ";
    x[k] = x[k - 1] - pow(2, k - 1)*abs(d);
    cout << x[k] << "\t";
    cout << "f(x[" << k << "])= " << Funkcija(x[k]) << endl;
    k++;
} while (Funkcija(x[k]) < Funkcija(x[k-1]));

what I get is:

I need that loop stop before x[4] , because f(x[3]) > f(x[2]), maybe someone see my error?

A: It's an "off by one" error. You have incremented k before the loop test, so you are testing the wrong indices - compare the elements at k - 1 and k - 2 and everything should be fine.
Note that if you had single-stepped through the code in your debugger, inspecting variables as you go, then the mistake would have quickly become apparent. This is an important skill to work on when you are learning to program.


text:
Q: Will an Angular module that exports all my pipes support tree shaking? I have a module that is dedicated to holding all the pipes for my Angular application.
An example of a module that exports just pipes.
@NgModule({
    imports: [
        CommonModule
    ],
    declarations: [
        FromNowPipe,
        ToNowPipe,
        ShortAgoPipe,
        SuffixPeriodPipe
    ],
    providers: [
        FromNowPipe,
        ToNowPipe,
        ShortAgoPipe,
        SuffixPeriodPipe
    ],
    exports: [
        FromNowPipe,
        ToNowPipe,
        ShortAgoPipe,
        SuffixPeriodPipe
    ]
})
export class PipesModule {
}

I've been wondering if a single module that holds all my pipes will break tree shaking. Where pipes that are never used are still being added to the final bundles.
The reason I asks is that pipes are not components. So the AOT compiler might not track their usage the same way it does for components and directives.
Should I be breaking up my pipes into smaller modules and then only import modules when I know that they are needed?

A: The same tree-shaking mechanism happens with Pipes as any other Angular Component/Directive.
This sounds like it is more important for lazy-loading performance.
Looking at how the Ng Material manages components, is that there is one module per component.
In summary, I would suggest that you break up Pipes either into separate modules or small groups.


text:
Q: enviar variable de PHP a JS intento pasar una variable de PHP a JS, he probado de todas las formas y no consigo resultados..que hago mal???
Segun la consola de firefox 'Uncaught SyntaxError: "" string literal contains an unescaped line break'.
 <?
    $firma=substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
    ?>

<script type="text/javascript">

function enviarDatos(){

var firma =  "<?php echo $firma; ?>";
alert(firma);

 var operario=document.getElementById("Combobox1").value;
 var fechaI=document.getElementById("Editbox1").value;
 var fechaF=document.getElementById("Editbox2").value;
 var cadena= operario+Math.floor(Math.random() * (20- 19)) + 20;

}

</script>

en el código fuente de la página, veo el error:

onclick="enviarDatos(' Notice:  Undefined variable: firma
in C:\xampp\htdocs\vacacionesTablet\firmaVacaciones.php on line
77 ')"

y esta es la linea 77
<input type="button" id="Button6" onclick="enviarDatos('<?php echo $firma; ?>')" name="generar" value="Firmar" style="position: absolute;top: 465px;left: 500px;width:96px;height:25px;z-index:11;">

y esta es la variable en PHP:
<?php
   $firma=substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
........
........
........
?>

Gracias anythingg Solucionado....

A: Asumo que tienes algo parecido a esto
<input type="button" id="Button6" onclick="enviarDatos('<?php echo $firma; ?>')" name="generar" value="Firmar" style="position: absolute;top: 465px;left: 500px;width:96px;height:25px;z-index:11;">
<?php $firma=substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10); ?>

Estás tratando de acceder a la variable antes que se defina, por ende, te arroja dicho error:
Ahora, te pongo en un contexto totalmente diferente para que me entiendas mejor:

Imagínate que quieres una moneda, pero esta está a 1km de ti y no puedes moverte

Por ende, no puedes acceder a ella ni a sus datos, esto es lo que está pasando
Además estás abriendo PHP con <? y no con <?php, esto da una diferencia ya que así la variable no se definirá
Solución
Cambia las líneas
<?php $firma=substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10); ?>
<input type="button" id="Button6" onclick="enviarDatos('<?php echo $firma; ?>')" name="generar" value="Firmar" style="position: absolute;top: 465px;left: 500px;width:96px;height:25px;z-index:11;">

Tengo lo siguiente:
<!DOCTYPE html>
<html>
<body>

<?php
$firma=substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);
?>

<input type="button" id="Button6" onclick="enviarDatos('<?php echo $firma; ?>')" name="generar" value="Firmar" style="position: absolute;top: 465px;left: 500px;width:96px;height:25px;z-index:11;">

<script type="text/javascript">

function enviarDatos(){

var firma =  "<?php echo $firma; ?>";
alert(firma);

 var operario=document.getElementById("Combobox1").value;
 var fechaI=document.getElementById("Editbox1").value;
 var fechaF=document.getElementById("Editbox2").value;
 var cadena= operario+Math.floor(Math.random() * (20- 19)) + 20;

}
</script>

</body>
</html>

Puedes probarlo y verás que funciona perfectamente, si el orden de las líneas está correcto, el error es que estás abriendo PHP con <? y no con <?php
De manera que la solución sería:
<?php $firma=substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10); ?>
<input type="button" id="Button6" onclick="enviarDatos('<?php echo $firma; ?>')" name="generar" value="Firmar" style="position: absolute;top: 465px;left: 500px;width:96px;height:25px;z-index:11;">


text:
Q: Select parent value if all child values are in a query I have three tables similar to the example below
T1                                   T3
------------------------             --------------------------
T1ID       X         ...             T3ID          Z        ...
------------------------             --------------------------
   1       aaa                          1          abc
   2       bbb                          2          def
   3       ccc                          3          ghi
   4       ddd                          4          jkl
                                        5          mno

T2
----------------------------------------
T2ID      T1ID      T3ID      Y     ...
----------------------------------------
   1         1         1      eee
   2         2         1      fff
   3         3         1      ggg
   4         2         2      hhh
   5         2         3      iii
   6         3         3      jjj
   7         1         4      kkk
   8         2         4      lll
   9         3         5      mmm
  10         4         5      nnn

What I want is an inner-join of all 3 tables but I only want the values in T3 selected if all of the values in T2 referencing the selected values in T1 are part of a previously established query. So for example if the previously established query (Q1) has T1ID's 1 and 2 selected then I want this query to select T3ID's 1 and 4. A typical join would select T3ID's 1, 2, 3, and 4 but I do not want T3ID's 2 and 3 selected because the values for T3ID 2 and 3 do not include T1ID 1 in T2. It is okay that T3ID 1 also contains other T1ID's in T2 for it to be selected. (I have no ability to change the database design so please no comments on changing it. Currently this database is in MS Access)

A: Assuming the values for your initial query result are 1 and 2, you have two values returned back, which you can now plug into a HAVING clause.
You would use this to search for the number of times T3ID appears where it has two matches.
This code is written in T-SQL, but I'm sure you can convert it quite easily to Access, as it's for demonstration purposes anyway.
-- This returns the T3IDs that match the conditions
SELECT T3ID
FROM T2
WHERE T3ID IN (1, 2)
GROUP BY T3ID
HAVING COUNT(T3ID) = 2 -- to match on the number of values

This returns two values: 1 and 4. Now you can plug that result into your existing INNER JOIN query, which returns everything, just adding on a WHERE clause.
For example:
SELECT * FROM T2
WHERE T3ID IN (
    SELECT T3ID
    FROM T2
    WHERE T3ID IN (1, 2)
    GROUP BY T3ID
    HAVING COUNT(T3ID) = 2
)

A: you need to re-explain with clear output expected in tabular format.
Sample data,
declare @T1  table(T1ID int,X varchar(20))
 insert into @T1 VALUES
(1,'aaa') ,(2,'bbb')
,(3,'ccc') ,(4,'ddd')

 declare @T3 table(T3ID int,Z varchar(20))
  insert into @T3 VALUES
 (1,'abc'),(2,'def')
  ,(3,'ghi'),(4,'jkl'),(5,'mno')

declare @T2 table(T2ID int,T1ID int,T3ID int,Y varchar(10))
insert into @T2 VALUES
( 1,1,1,'eee')
,( 2,2,1,'fff')
,( 3,3,1,'ggg')
,( 4,2,2,'hhh')
,( 5,2,3,'iii')
,( 6,3,3,'jjj')
,( 7,1,4,'kkk')
,( 8,2,4,'lll')
,( 9,3,5,'mmm')
,(10,4,5,'nnn')

Sql server version

;With CTE as
(
select * from @T1
where T1ID in(1,2)
)
,CTE1 AS(
select t2.T3ID from @T2 t2
inner join cte c
on t2.T1ID=c.t1id
group by t2.T3ID
having count(*)=(select count(*) from cte)
)
select t3.*
from @T3 t3
inner join cte1 c1 on t3.T3ID=c1.t3id

I have use CTE becasue I don't know what is your previously established query. If i am aware then query may be re-written accordingly

MS Access version I have create and run this query in MS Access with same sample data.

select t3.* from T3 t3

inner join
(
select t2.t3id from T2 t2
inner join
(
select * from T1
where T1ID in(1,2)
)t4
on t2.T1ID=t4.t1id
group by t2.T3ID
having count(*)=(select count(*) from T1
where T1ID in(1,2))
)t5
on t3.t3id=t5.t3id

where previously establish query is
select * from T1
    where T1ID in(1,2)

you have to worry about this query.


text:
Q: {detail: Unsupported media type "text/plain; charset=utf-8" in request.} I am using Flutter and Django and have this error when try to call the backend
Back end error :
{detail: Unsupported media type "text/plain; charset=utf-8" in request.}
Flutter code :
Future<void> addAlbum(Album album) async {
print('5');
final url = Uri.parse('http://127.0.0.1:8000/list-create/');

try {
   print('6');
  final response = await http.post(url,
      headers: {
        'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f',
      },
      body: json.encode({
        'title': album.title,
        'cover': album.cover, // => this is an int
        'photos_number': album.photos_number, // => this is an int

      }));
      print('6 ed');
  final responseData = json.decode(response.body);
  print(responseData.toString());

  final newAlbum = Album(
    title: album.title,
    cover: album.cover,
    photos_number: album.photos_number,
  );
  print('6 edddgg');

  _items.add(newAlbum);

  print('6 f');
  notifyListeners();
} catch (error) {
   print('7');
  print(error);
  throw error;
}

}
}

A: Add json content type header.
headers: {
  'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f',
  'Content-Type': 'application/json; charset=UTF-8',
},


text:
Q: Is "the" essential in "The Book of Five Rings"? Is the word "the" in the title necessary? Would it make a difference if the title was "Book of Five Rings"? I've seen many "Book of ..." titles, both with and without "the", and I can't understand its purpose.

A: The is there because the author chose that it should be there. Book titles are not subject to any rules of grammar at all. You may title a book whatever you want and you cannot be wrong.


text:
Q: C file Fwrite and fread struct pointers The program only works for the first time. What was supposed to happen the second time was to add the same data to the binary file but that doesn't happen.
First run: It runs normal and it shows that it writed to the file.
Secound run: It writes to the file but doesnt read.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *name, *role, *course;
    int year, id;
} StudentFile;

void saveBin(StudentFile *studentsFile, int lines){
    FILE *file = fopen("studentsx.bin","ab");
    if (!file) {
        printf("\n\n\tImposible to open file. \n\n");
        exit(1);
    }

    for (int i = 0; i < lines; i++){
        fwrite(&studentsFile[i], sizeof(StudentFile), 1, file);
    }
    fclose(file);
}

void readBin(){
    StudentFile *studentsFile = malloc(sizeof(StudentFile)*5000);
    FILE *file = fopen("studentsx.bin","rb");
    if (!file) {
        printf("\n\n\tImposible to open file. \n\n");
        exit(1);
    }

    int j = 0;

    while (fread(&studentsFile[j], sizeof(StudentFile), 1, file)){
        printf("\nLine read %d: %s\t%s\t%d\t%d\t%s", j+1, studentsFile[j].name, studentsFile[j].role, studentsFile[j].year, studentsFile[j].id, studentsFile[j].course);
        j++;
    }

    fclose(file);
}

void main(){
    StudentFile *studentsFile = malloc(sizeof(StudentFile)*2);
    int lines = 0;

    studentsFile[0].name = "John";
    studentsFile[0].role = "Gamer";
    studentsFile[0].year = 1999;
    studentsFile[0].id = 1;
    studentsFile[0].course = "IOT";
    studentsFile[1].name = "Piter";
    studentsFile[1].role = "GamerXL";
    studentsFile[1].year = 1991;
    studentsFile[1].id = 2;
    studentsFile[1].course = "IOTXL";
    lines = 2;

    saveBin(studentsFile, lines);
    readBin();
}

A: You are writing pointers, not strings. fwrite writes single contiguous array of memory. In your case the StudentFiles and actual strings are scattered all over the static memory and heap memory.
Consider your struct:
typedef struct {
  char *name, *role, *course;
  int year, id;
} StudentFile;

it looks something like this in memory:
[<pointer to name><pointer to role><pointer to course><year><id>]

somewhere else in a different block  of memory:
[John\0Gamer\0\OIT\o.......]

You wrote the first block above and left out the second one.
There are multiple approaches to this problem and we usually name them "serialization" - take your complex data structure and serialize it into a linear file.
One of the approaches is to allocate fixed size block within your structure StudentFile:
#define MAX_NAME 100
#define MAX_ROLE 100
#define MAX_COURSE 100
typedef struct {
  char name[MAX_NAME];
  char role[MAX_ROLE];
  char course[MAX_COURSE];
  int year, id;
} StudentFile;

then strings name, role and course will be inside of StudentFile:
[<100 bytes for name><100 bytes for role><100 bytes for course><year><id>]

this is contiguous block of memory and if can be written using single call to fwrite like you did.
But you won't be able to assign strings like you did with
studentsFile[i].name = "John";

C has strncpy for that:
strcpy(studentsFile[0].name, "John", MAX_NAME);

Another approach is to have several calls to fwrite. For every string, you write length first, then the string itself. For primitive types like int you just write that int.
First you gather strings from different locations pointed by the pointers:
size_t nameLen = strlen(studentsFile[i].name) + 1;/* +1 for the final zero*/
fwrite(&nameLen, sizeof(size_t), 1, file);
fwrite(studentsFile[i].name, nameLen, 1, file);
size_t roleLen = strlen(studentsFile[i].role) + 1;
fwrite(&roleLen, sizeof(size_t), 1, file);
fwrite(studentsFile[i].role, roleLen, 1, file);
size_t courseLen = strlen(studentsFile[i].course) + 1;
fwrite(&courseLen, sizeof(size_t), 1, file);
fwrite(studentsFile[i].course, courseLen, 1, file);

Then you write primitive types:
fwrite(&studentsFile[i].year, sizeof(int), 1, file);
fwrite(&studentsFile[i].id, sizeof(int), 1, file);

Next time when you read the file, you rely on the order of writes and read the fields back in the same order:
size_t nameLen;
fread(&nameLen, sizeof(size_t), 1, file);
char *name = malloc(nameLen);
fread(name, nameLen, 1, file);
size_t roleLen;
fread(&roleLen, sizeof(size_t), 1, file);
char *role = malloc(roleLen);
fread(role, roleLen, 1, file);
size_t courseLen;
fread(&courseLen, sizeof(size_t), 1, file);
char *course = malloc(courseLen);
fread(course, courseLen, 1, file);
int year;
fread(&year, sizeof(int), 1, file);
int id;
fread(&id, sizeof(int), 1, file);

printf("\nLine read %d: %s\t%s\t%d\t%d\t%s", j+1, name, role, year, id, course);

A: The problem lies somewhere else: Think carefully, what is your code doing with fwrite() here?
typedef struct {
    char *name, *role, *course;
    int year, id;
} StudentFile;

fwrite(&studentsFile[i], sizeof(StudentFile), 1, file);

What does the file content look like after writing a single element from studentFile?

*

*Three strings and two integers (in their binary form)

*Three pointers to somewhere and two integers (all in their binary forms)


text:
Q: Serializable schedules So there was this question in my DBMS exam:
Define serializable schedule.
My answer: If a schedule can be converted to some serial schedule by a series of non-conflicting swaps of actions, then it is a serializable schedule.
They've marked it wrong. I have been arguing with the professors for quite some time but they want the definition from the book.
Can someone please point out where am I wrong?Are there any such schedules that cannot be converted to a serial schedule but are nevertheless, serial?
Thanks in advance.

A: your answer is wrong because it defines "conflict serializability" not "serial schedule"
A schedule is called serializable whenever executing the transactions sequentially, in some order, could have left the database in the same state as the actual schedule. Serializability is the commonly accepted criterion for correctness.


text:
Q: how to connect multiple proximity sensors to a PIC to work together on a single port Here is the proyect, making a failsafe autonome Baby Cart
believe me my life is at risk here, im in high school studyng mechatronics so im still learning how to make some stuff but i know the basics the thing is an aunt wants me to make a baby cart for my newly born cousin that can be radiocontrolled or moved by the baby and stops automatically if there is a fall when the baby is in free roam mode.
Using a PIC for the proyect, the circuit uses 2 voltage lines, a main 5V supply is for powering the PIC controller, sensors, output relays, the logic circuit and the RC control (borrowed from a RC car), the secondary 12v power supply is used for the motors for the wheels and the motors on the deployable legs (for stopping the cart if the baby wants to go off a cliff and the sensors stop dettecting ground).
i want to connect 8 sensors but the pic only has 6 input ports and 2 are used for the RC control is it plausible to connect 2 sensors to each port while passing by the same "not" gate?
if the baby falls im going to be dead

A: My answer is no you can't but there is some way to reduce the number of ports used to 4 ports, assuming one of port can be used as ADC port and the other 3 ports can be used as logic output (so it depends the PIC you use, look at the datasheet.)
Use alanog proximity sensors like this and DG528 analog multiplexer. Assuming you have heard about multiplexer, DG528 is the analog-version-multiplexer that have 8 analog input channels and 1 analog output channel. Look at the page 7 of the datasheet of DG528. Depending on the input value of address input, pin A2, A1 and A0, the output channel(pin D) is connected to one of input channel(pin S1 to S8). So you should connect the output channel to a ADC port of PIC to read, and connect A2-A0 ports to the other three digital output ports of the PIC. In this way you can read sensors with reduced number of ports of the PIC.

A: Firstly, I agree with the others (comments). There are many things that could go wrong here and I know I wouldn't want to be responsible for a baby's safety.
With that said, the simple answer here is to get a PIC with enough I/O to support everything instead of trying to make it work with what you got.
If you absolutely must use the PIC you have then you can use a multiplexer (mux)  on the front-end.


text:
Q: How to group json array and sum its total per week? I have an array
    [
        {
            "week_year": "49-2021",
            "total": 6.5
        },
        {
            "week_year": "45-2021",
            "total": 28.5
        },
        {
            "week_year": "45-2021",
            "total": 6.5
        },
        {
            "week_year": "44-2021",
            "total": 6.5
        },
        {
            "week_year": "46-2021",
            "total": 14.5
        }
    ]

I want to group it by the same week_year and sum its total per week. Any other way to do that?

A: If the output needed is like { week_year => total } then you can use a combination of group_by, transform_values and sum:
arr
  .group_by { |hash| hash[:week_year] }
  .transform_values { |arr| arr.sum { |hash| hash[:total] } }
# {"49-2021"=>6.5, "45-2021"=>35.0, "44-2021"=>6.5, "46-2021"=>14.5}

A: If arr is the array given in the question one could write
arr.each_with_object(Hash.new(0)) { |g,h| h[g[:week_year]] += g[:total] }
  #=> {"49-2021"=>6.5, "45-2021"=>35.0, "44-2021"=>6.5, "46-2021"=>14.5}

This makes a single pass through the array and requires less memory than does the use of Enumerable#group_by. Arguably, it also reads better. Whether it's faster is an open question.
This employs the form of Hash::new that takes an argument--called the default value--and no block. If a hash h is so-defined, then, possibly after keys have been added, if h does not have a key k, h[k] returns the default value. The default value is commonly chosen to be zero, as it is here.
The expression
h[g[:week_year]] += g[:total]

expands to
h[g[:week_year]] = h[g[:week_year]] + g[:total]

so if h does not have a key g[:week_year] this becomes
h[g[:week_year]] = 0 + g[:total]

A: You can use group_by in combination with transform_values:
array.group_by { |a| a[:week_year] }
     .transform_values { |values| values.sum { |value| value[:total] } }

Which will return:
{
 "49-2021" => 6.5,
 "45-2021" => 35.0,
 "44-2021" => 6.5,
 "46-2021" => 14.5
}


text:
Q: SelectNodes with XPath ignoring cases I have a problem finding elements in XPath that's contains a certain string ignoring character casing.
I want to find in a HTML page all the nodes with id contains the text "footer" ignoring it's write in uppercase or lowercase.
In my example I have a different html text like this:

some text

some text

some text

some text

I need to select all nodes (or any combination in any case with the word "footer" in the id) with a XPath.
Currently I'm using this xpath but doesn't work for the UpperCase id's
"//*[contains(./@id, 'footer')]/@id"

I've done several tests with translate() but doesn't work as I expected.
Any idea?
EDIT: I'm using HtmlAgilityPack with works with the XPath 1.0 version.

A: Not sure if you've tried this yet, but this is what I do for case sensitive contains searches:
//*[contains(translate(./@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), 'footer')]/@id

I saw you have found your solution, so I'm posting this answer in case others have the same issue.


text:
Q: Finding column index of a PyTorch tensor that has most 1's I have a PyTorch tensor a shaped like below:
import torch
a = torch.tensor([[[1., 0., 0., 0.]],
        [[0., 1., 0., 0.]],
        [[1., 0., 0., 0.]],
        [[0., 0., 0., 1.]],
        [[1., 0., 0., 0.]],
        [[0., 0., 0., 1.]],
        [[1., 0., 0., 0.]]])

Each row of the tensor a has 4 elements, 1's and 0's. Say I index the row and the column of this tensor accordingly. So for instance, the entry in the row 0 (uppermost row) is [[1., 0., 0., 0.]], whereas the entry in the column 3 (rightmost column) is [[0., 0., 0., 1., 0., 1., 0.]].
From a given tensor, I want to identify the index of the column where 1. appear most frequently. For example, for the tensor a, the index of such a column would be 0. If there are ties in the number of 1.'s, I still would like to get all of those tied column indices.
How can I do this task easily on Python?
Thank you,

A: If your matrix only contains 0 and 1, you can sum the elements of each column and then search for the sum that is the largest:
import numpy as np

% sum over columns
sumsi = torch.sum(a, dim=1)

% find where maximum
col_idx = np.where(sumsi==np.max(sumsi))


text:
Q: Write a single congruence?
Write a single congruence that is equivalent to the pair of congruences:
$x\equiv 1(\mod4)$ and $x\equiv 2 (\mod 3)$.

I am new to Number Theory/ Modular Arithmetic. Just started reading the theory from a book yesterday. Earlier I had read about it a little on the internet. I know the basic definitions and some properties. I do not understand the question properly. What does writing a single congruence mean? Does it mean I have to find $x$? How do I solve this question. Do I need to use any theorem like the Chinese Remainder Theorem or something else? I am stuck. Please help.

A: Hint:
Start from a Bézout's relation between the moduli, say $\; 4-3=1$, and consider the analog of the linear interpolation polynomial: for any $a, b \in\mathbf Z$,
$$a\cdot 4-b\cdot3\equiv \begin{cases}a \mod 3, \\[1ex]  b\mkern 1.5mu \mod 4. \end{cases}$$

A: you can literally turn this into $3z+2=4y+1;3z+1=4y$; take this mod 3 and get 1=y; so plug $y=3a+1$ and get back $3z+1=12a+4$ and then add 1 to both sides restoring the original getting $3z+2=12a+5$  so you get $x\equiv 5 \bmod 12$.  This is basically CRT done via linear polynomials.


text:
Q: Operations with Delta Functions I was asked to "justify" the following formula with delta functions:
$\delta_{0}((x-a)(x-b))=\displaystyle\frac{(\delta_{0}(x-a)+\delta_{0}(x-b))}{|a-b|}$
Where we say $\delta_{0}(x-a)$ is the Dirac delta with concentration at $a$. However, I'm not sure on how to go about the proof for this statement. Without loss, one can assume that $b > a$, however I find that the result will be $\delta_{0}(x-a)+\delta_{0}(x-b)$, without the term $\frac{1}{|a-b|}$. Would in this case $\delta_{0}((x-a)(x-b))$ be the Dirac delta with concentration at $a,b$? How would one be able to justify the above formula (preferably using distributions and actions on test functions)?
Any help would be appreciated.

A: Where $f(x)$ is an arbitrary function, consider
\begin{align}
\int_{-\infty}^\infty \delta[g(x)]f(x)dx
\end{align}
Assume that $g(x)$ has only one zero at $x=x_{0i}$ in the interval $(x_i,x_{i+1})$. Let's also assume $g'(x)>0$ on the interval (the case if g'(x)<0 should be handled separately). Then, the above integral is equivalent to
\begin{align}
\int_{x_i}^{x_{i+1}} \delta[g(x)]f(x)dx
\end{align}
Now let $u=g(x)$ such that $du = g'(x) dx$. Noting that $g(x_i) <g(x_{i0})=0 < g(x_{i+1})$, we find that
\begin{align}
\int_{g(x_i)}^{g(x_{i+1})} \delta(u)\frac{f(g^{-1}(u))}{g'(g^{-1}(u))}du
= \frac{f(g^{-1}(0))}{g'(g^{-1}(0))} = \frac{f(x_{0i})}{g'(x_{0i})}
\end{align}
Strictly, I should be equating the delta function with a distribution in the above argument, arguing that I can extend the integration limits to infinity, and limiting the distribution until it achieves the form of a delta function.
If we also considered the case where $g'(x)<0$ instead, we would find that in general,
\begin{align}
\int_{x_i}^{x_{i+1}} \delta[g(x)]f(x)dx = \frac{f(x_{0i})}{|g'(x_{0i})|}
\end{align}
But what if $g(x)$ has multiple zeros, as in your case? Split up the integration limits into $N$ intervals labelled by $(x_i,x_{i+1})$ in a way that $g'(x)\ne0$ within each interval but may be zero on the boundaries. Since $g'(x)$ is either positive or negative in each interval, $g(x)$ has at most one zero within each interval. By the above argument, we can show
\begin{align}
\sum_{i=1}^N \int_{x_i}^{x_{i+1}} \delta[g(x)]f(x)dx
& =\sum_{i=1}^N \frac{f(x_{0i})}{|g'(x_{0i})|}
\end{align}
One could say then, for a $g(x)$ with $N$ zeros, we can identify
$$\delta[g(x)] = \sum_{i=1}^N \frac{\delta(x-x_{0i})}{|g'(x_{0i})|}$$
This matches what you're seeking. I hope this outline helps.


text:
Q: Get Java object using C++ to call the Java method I am developing in native and Java code for Android.
I plan to invoke a Java listener based on a C/C++ code. The idea is the C/C++ code call a method that actually invoke the Java Listener.
The C/C++ code is as follow. I can call the Java method using code below: the first code block is initiating the methodid and class inside JNI_OnLoad
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }

    jclass dataClass = env->FindClass("com/example/crowdlogic/NativeManager");
    dataClassHandle = (jclass)env->NewGlobalRef(dataClass);
    if (dataClassHandle == NULL) LOGI("dataClassHandle null");
    LOGI("init dataUpdateHandle");
    dataUpdateHandle = env->GetMethodID(dataClassHandle, "dataUpdate", "(I)V");
    if (dataUpdateHandle == NULL) LOGI("dataUpdateHandle null");

    return JNI_VERSION_1_6;
}

Next codeblock is actually calling it:
void sendCount(int totalCount) {
    jint jtotalCount = totalCount;
    jobject dataObjectHandle = env->NewObject(dataClassHandle, dataUpdateHandle);
    if (dataObjectHandle == NULL) LOGI("dataObjectHandle null");
    env->CallVoidMethod(dataObjectHandle, dataUpdateHandle, jtotalCount);
}

In the Java part, the dataUpdate method is actually called, but never invoke the listener. The listener is null. This is the Java listener class
public class NativeManager {

    private static final String TAG = "crowdlogic:native_manager";

    // all the listener stuff below
    public interface Listener {
        public void onDataUpdated(int totalCount);
    }

    private Listener mListener = null;

    public void registerListener (Listener listener) {
        mListener = listener;
    }

    public void dataUpdate(int totalCount) { // call this from JNI in C++ class
        // now notify if someone is interested.
        Log.i(TAG, "Data update in Java called");
        if (mListener != null) {
        Log.i(TAG, "mListener not null");
        mListener.onDataUpdated(totalCount);
    }
    else
        Log.i(TAG, "mListener null"); // always come to this; the listener is null
    }
}

In my main activity, I have instantiated the listener (inside onCreate):
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    // start listener for data update
    mNativeMgr = new NativeManager();
    mNativeMgr.registerListener(this);
    mNativeMgr.dataUpdate(0);
    ...
}

I think this is because in the native part, instead of calling the instantiated Java listener object, I actually create a new one using the
jobject dataObjectHandle = env->NewObject(dataClassHandle, dataUpdateHandle);

inside void sendCount(int totalCount).
My question is, how can I get the instantiated Java object rather than create a new one, in the C/C++ code? Thanks guys, spent last 2 days on this already...

A: I found the solution. Instead of calling dynamic method, I make the Java method as static method and call it from C++ using CallStaticVoidMethod. Code example:
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return -1;
    }

    jclass dataClass = env->FindClass("com/example/crowdlogic/NativeManager");
    dataClassHandle = (jclass)env->NewGlobalRef(dataClass);
    dataUpdateHandle = env->GetStaticMethodID(dataClassHandle, "dataUpdate", "(I)V");
    return JNI_VERSION_1_6;
}

The native function that calls the Java method:
void sendCount(int totalCount) {

jint jtotalCount = totalCount;
jobject dataObjectHandle = env->NewObject(dataClassHandle, dataUpdateHandle);
if (dataObjectHandle == NULL) LOGI("dataObjectHandle null");
LOGI("init CallVoidMethod");
env->CallStaticVoidMethod(dataClassHandle, dataUpdateHandle, jtotalCount);
}

In Java, I declare the method as static method


text:
Q: Why can I use the constructor without an object declaration? Why can I use the constructor without a previous object declaration? And, if the previous works, why do I get an error when using k()?
Here is my code:
#include <iostream>
using namespace std;

class Test
{
int i, x;
public:
Test(int ii = 0)
{
    cout<<"WOW!";
    cout<<i<<" ";

    i=ii;
}
void k()
{
    cout<<i<<" ";
}
};

int main()
{
    Test();
    k();    ///k was not declared in this scope

    return 0;
 }

A:
Why can I use the constructor without a previous object declaration?

A constructor is used to create a new object.  So it can't be called on a previous object.

And, if the previous works, why do I get an error when using k()?

Because k() is a non-static method of Test, so it needs a Test object to call it on.  You can't call it as a standalone function.
int main()
{
    Test t;
    t.k();

    return 0;
}

A: You can create instance of the class because the name of the class can be found with name lookup from the current (the global in this case) namespace, and the class has been defined.
You haven't declared a free function by the name k, so you cannot call such function.


text:
Q: Childwindow set as singleton Can we have Silverlight's Childwindow set as singleton? If so, can you share me a pseudo code to implement it?

A: The question would be way??
But you Can simplest way is to Simple in your App.cs
public static ChilldWindow MYGLOBAL_CHILDE_WINDOW = new SomeIMplementation()
and you can access it from everywhere App.MYGLOBAL_CHILDE_WINDOW.Show() -- to Display it


text:
Q: How can I (simply) enable CORS on my Azure webrole API I have an Azure webrole which is running an API service.  I'm trying to enable CORS so that the API can be consumed by browser scripts.  There are a quite a few questions that refer to enabling CORS on web-api applications but I haven't found one that gives an answer for webroles.
I've tried adding the magic customheaders block from this answer to my web.config but that doesn't work.
This document from Microsoft implies that the Microsoft.AspNet.Cors nuget package may be used but it's unclear to me how to get hold of the HttpConfiguration from within a webrole OnStart method.  It also seems odd that I have to decorate every one of my API methods. Is there not a single 'switch' I can flick to enable CORS for the entire service?
Related questions...

*

*What's the easiest way to verify that CORS is actually enabled?  At the moment I'm using a Blazor PostJsonAsync call and relying on that to pass but it's getting pretty tedious repeatedly reconfiguring and uploading the role to Azure to try out changes.

*Bigger question...am I fighting against the tide using a webrole?  Much of the documentation refers to web-api and web-apps.  Maybe these are the future and webroles are deprecated?

A: I would also recommend moving over to webapps. However, you might also get it to work with web roles and how you apply cors there also works for webapps if you use OWIN.
You might host your API in the web role like this:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/host-aspnet-web-api-in-an-azure-worker-role
This gives you the HttpConfiguration you need (Startup.cs).

It also seems odd that I have to decorate every one of my API methods. Is there not a single 'switch' I can flick to enable CORS for the entire service?

You can use an ICorsPolicyProvider to enable it everywhere:
// in startup.cs
config.EnableCors(new AllowAllCorsPolicyProvider());

public class AllowAllCorsPolicyProvider : ICorsPolicyProvider
{
    readonly CorsPolicy _CorsPolicy;

    public AllowAllCorsPolicyProvider()
    {
        _CorsPolicy = new CorsPolicy {AllowAnyHeader = true, AllowAnyMethod = true, AllowAnyOrigin = true};
    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(_CorsPolicy);
    }


text:
Q: Django - sorl-thumbnail - accessing thumbnail image from view functions I am currently using sorl-thumbnail and have a model.
class Entry(models.Model):

    image = ImageWithThumbnailsField(upload_to='uploads/', null=False, blank=True,
        thumbnail={
            'size':(150,150),
        'options':{'crop':'smart'}
        },
        generate_on_save=True
    )

This model creates 'filename_jpeg_150x150x_crop-smart_q85.jpg' thumbnail in 'uploads' folder and I am trying to access it from my view functions.
I'm wondering if there is a simple way to find out the thumbnail's name and path.
Thank you.

A: Tried using thumbnails_for_file() and all_thumbnails() inside sorl-thumbnail 3.2.5 utils.py, but was unsuccessful. Seemed like those functions were returning thumbnails that were parsed directly from django templates. It just didn't return all thumbnail files.
Ended up just parsing out the file path by
Entry.objects.all()[0].image.thumbnail.relative_url

relative_url shows path and filename 'uploads/test_jpg_150x150_crop-smart_q85.jpg'


text:
Q: Kernel of a morphism into blow up algebra This is related to Ueno, Algebraic Geometry 2, Example 5.28.
Let $R=k[x_1,\dots, x_n]$ and $I=(x_1,\dots, x_n)\subset R$. Let $S=R\oplus I\oplus I^2\oplus I^3\oplus\dots$ be graded $R-$algebra.
Consider $R[y_0,\dots, y_{n-1}]\to S$ by $f(y_0,\dots, y_n)\to f(x_1,\dots, x_n)$ is clearly surjective graded ring homomorphism.
It is clear that kernel contains $x_iy_j-y_ix_j\in R[y_0,\dots, y_{n-1}]$.
$\textbf{Q:}$ Is it true that kernel is exactly generated by $(x_iy_j-y_ix_j|i,j)$ for all $i,j$? If so, is there an easy way to check this?


text:
Q: Display all records from list of array in php I have a script which runs pretty well, it displays 2 records at a time. I want to actually display all the records from the array data. I am not very familiar with jquery and the script uses jquery.
Basically it works like this... the user submits a question on one page and then the question submitted displays on the a second page. You can try it here:
Submit questions: http://www.webcastviewer.com/post/submit.php
Lists questions: http://www.webcastviewer.com/post/list.php
On the "List" page: Currently it lists the two most recent questions. The most recent question is in blue/larger font at the top. The change I want is that I want it to list ALL questions with the most recent at the top (as it is now). Currently older questions disappear after two entries. I want it to show all submissions.
App.js (jquery code )
http://www.webcastviewer.com/post/js/app.js
Page code for displaying 2 records.
    <?php
//read questions
$question_file_path = 'server/question.list';
if(!file_exists($question_file_path)){
    $questions = array();
}
else {
    $questions = json_decode(file_get_contents($question_file_path), true);
}

?>

        <?php
        if(count($questions) > 0){
            ?>

            <?php
        }
        else{
            ?>

            <?php
        }
        ?>

<?php echo isset($questions[0]) ? $questions[0]: ' '  ?>

<?php echo isset($questions[1]) ? $questions[1] : ' ' ?>

There isn't question.

A: Please look at how you can do it.
I have improved some part of code and commented on them as well.
Note: Try to improve your mixing of PHP with HTML and avoid using it.

    //Added ternary operator instead of typical if else.
    <div class="<?= count($questions) > 0 ? 'questions-list' : 'questions--empty'  ?>">
    <?php
    //checking if has records else show message
        if(count($questions) > 0){
    ?>
        <?php foreach($questions as $question) ?>

<?php echo isset($question) ? $question: ' '  ?>

        <?php }

    }else{ ?>

There isn't question.

    <?php } ?>


text:
Q: Error en ejecutar mi aplicacion-Entrada duplicada Tengo un proyecto de Android y uso varios servicios de google, API facebook, y usando firebase. pero cuando la ejecuto me sale un error de duplicación y no entiendo el error

Duplicate class com.google.firebase.auth.GoogleAuthCredential found in
  modules classes.jar (com.google.firebase:firebase-auth-common:9.0.2)
  and classes.ar (com.google.firebase:firebase-*auth:17.0.0)

A: El problema es que tienes clases repetidas de Firebase debido a las dependencias que definiste en tu build.gradle, es un problema similar a :
Duplicate class org.xmlpull.v1.XmlPullParser xmlpull:xmlpull
Agrega dentro del bloque configurations de tu build.gradle lo siquiente:
 android{
   ...

        configurations {
            exclude group: 'com.google.firebase', module: 'firebase-auth'
        }

    }


text:
Q: How do you run an OR query in Peewee ORM? I'd like to run a query for a user based on username or email address.
I must be missing it, but I can't find how to run an OR query in the peewee documentation. How do you do that?

A: From the documentation

If you want to express a complex query, use parentheses and python's bitwise or and and operators:

>>> Tweet.select().join(User).where(
...     (User.username == 'Charlie') |
...     (User.username == 'Peewee Herman')
... )


text:
Q: D3.select(this) but filter I am working on an D3 forced graph and got a challenge. I added a "mouseenter" function which increase the radius of nodes if getting hovered.
.on("mouseenter", function(d) {
                    d3.select(this)
                        .transition()
                        .duration(200)
                        .attr("r", 50)

Now I want to exclude certain nodes and thought to filter would help. Unfortunately it doesn´t. Probably my code is wrong or I need to add those filtering later one. Any idea?
 .on("mouseenter", function(d) {
                    d3.select(this)
                        .filter(function() {
                            return !this.graph.nodes.name("usv"))
                        })
                        .transition()
                        .duration(200)
                        .attr("r", 50)

Best,
Kristian

A: Here's an example implementation:

<!doctype html>

<html>
  <head>
    <script src="https://d3js.org/d3.v4.min.js"></script>
  </head>

  <body>
    <svg width="500" height="500"></svg>
    <script>
      let data = d3.range(10)
        .map(function(d){
          return {
            name: Math.random() > 0.5 ? "usv" : "na",
            x: Math.random() * 480,
            y: Math.random() * 480
          };
        });

      d3.select('svg')
        .selectAll('circle')
        .data(data)
        .enter()
        .append('circle')
        .attr('cx', d => d.x)
        .attr('cy', d => d.y)
        .attr('r', 20)
        .attr("fill", d => d.name == "usv" ? "red" : "black")
        .filter((d) => {
          return d.name === "usv";
        })
        .on("mouseenter", function(){
          d3.select(this)
            .transition()
            .duration(200)
            .attr("r", 50);
        });
    </script>
  </body>
</html>


text:
Q: Jackson - Map JSON string field to class/pojo that has only one field (a string) I am writing a JSON interface/library to work with Bugzilla's webservice.
Is this possible using an annotation or something? Or am I to write a custom deserializer for every instance like this?
I've tried doing some research, and found some information about a Value Instantiator or using constructors, but isn't using constructors anti-bean like? I've found documentation to be sparse or hard to understand with the newer features.
Example:
public class Bug{
  // Bug info, strings, ints, yadda yadda.
 private User creator;   // creator of the bug, json is like   {"creator":"blahblah@email.com"}
}

public class User{
 private String username;
}
//insert setter/getter.

The reason I am using a pojo for One field is because this User class is extended by another that has more fields. While I can implement a constructor to achieve this effect, doing so means I have to implement the same constructor for all other subclasses. I feel like there is something similar to @JsonValue but for setting (I tried JsonCreator on my setter but still got the same error as I have been getting below).
"Can not instantiate value of type [simple type, class User],  from String value; no single-String constructor/factory method"
Thanks.

A: Use @JsonCreator for deserializing and use @JsonValue for Serializing. Have tested the code. Please make sure that getJsonString() is public method.
For example:
public class User{
    private String username;

    @JsonValue
    public String getJsonString() {
         return username;
    }

    @JsonCreator
    private static User parseJson(String jsonStr) {
        User u = new User();
        u.username = jsonStr;
        return u;
    }

    public static void main(String[] args) {
        User u = new User();
        u.userName = "Niraj";

        ObjectMapper m = new ObjectMapper();
        String jsonString = m.writeValueAsString(u);
        User u1 = m.readValue(jsonString, User.class);
    }
}

A: You don't need to use a @JsonCreator or @JsonValue or a construtor, Jackson will work OTTB with javabean methods:  Try this instead:
public class User{
    private String username;

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public static void main(String[] args) throws Exception {
        User u = new User();
        u.setUsername("name");

        ObjectMapper m = new ObjectMapper();
        String userString = m.writeValueAsString(u);
        System.out.println(userString);
        User u1 = m.readValue(userString, User.class);
        System.out.println(u1.getUsername());
    }
}


text:
Q: Two sites connected with wireless point to point: how to configure and ensure internet traffic goes through local broadband? Scenario:
Two offices a short distance apart. Let's call them Main and Remote. Both have ADSL broadband. Windows network in Main. Currently different subnets. 192.168.16.x in Main and 192.168.0.x in Remote, masks 255.255.255.0
We are proposing to use a wireless point-to-point connection to allow Remote users to connect to the Main network. How can we configure this? Presumably we need to use different subnets otherwise all internet traffic will go through the ADSL in Main. We want seamless access to the Main network from Remote but for local and internet traffic to stay in Remote.
There is a managed switch in Remote but it is not doing anything smart currently.

A: You need a router in both of your locations. Set the default route on both of them to the local broadband gateway. On the remote router set a route to 192.168.16.0 using the wireless link and in your main router a route to 192.168.0.0 using wireless.


text:
Q: Hibernate restrictions (And / Or) small questions about Restrictions.
i have query like this :
Where  A in(1,6) and (B not like 'Value%' or B not like 'ValueII%')

the problem is the field B not contains a fixed value, can be one or more.
Please, (N)Hibernate experts - help me with this, I cant find a working solution. Any help is greatly appreciated!

A: You can use disjunctions to handle the OR cases, as such:
IList results = session.CreateCriteria(typeof(MyType))
    .Add(Restrictions.In("A", new [] {1, 6}))
    .Add(Restrictions.Disjunction()
        .Add.Restrictions.Not(Restrictions.Like("B", "Value%"))
        .Add.Restrictions.Not(Restrictions.Like("B", "ValueII%")))
    .List<MyType>();

If you need to handle the disjunction conditions in a for loop (per your follow-up), you can use code like this:
ICriteria query = session.CreateCriteria(typeof(MyType));
query.Add(Restrictions.In("A", new [] {1, 6}))

Disjunction disjunction = Restrictions.Disjunction();
foreach (var value in values) {
    disjunction.Add(Restrictions.Not(Restrictions.Like(value, "Value%")));
    disjunction.Add(Restrictions.Not(Restrictions.Like(value, "ValueII%")));
}
query.Add(disjunction);

IList results = query.List<MyType>();

That being said, I think there may be a flaw in your logic.  If you are testing these values to "not match one pattern OR not match another pattern", then the condition will always evaluate to true (unless the patterns are the same).  Are you sure you want to be using ORs here?

A: the problem is that I don't know exact how many restrictions i have and i need to use FOR in disjunction.
Something like that:
IList results = session.CreateCriteria(typeof(MyType))
.Add(Restrictions.In("A", new [] {1, 6}))
.Add(Restrictions.Disjunction());
 for(int i = 0, i < value.Lenght;i++){
    .Add.Restrictions.Not(Restrictions.Like("B", "Value%"));
    .Add.Restrictions.Not(Restrictions.Like("B", "ValueII%"));
 }
.List<MyType>();

thanks for you help


text:
Q: What is the difference between iTerm2 and Terminal? I keep hearing that iTerm2 is much better than Terminal. However, when I downloaded iTerm2, I didn't see what made it preferable over Terminal. What are the differences between these two apps?

A: There are several features listed on their features page.
Some of the features I like are:

*

*Split pane view

*Hotkey window for instant terminal anywhere

*Search will highlight all found words (like in Chrome and Safari)

*Mouseless copy

*Instant replay (can "rewind" your session in case you forgot to note/copy something)

*Paste history

*Growl support for notification when a process completes

A: The feature I chose iTerm for is being able to cut or copy by just selecting text and paste by just using the middle button

A: @joel's answer is good, but Terminal.app gained some exclusive features in Lion:

*

*support for Lion's restore feature

*support for system services - this means I have a system shortcut for "new terminal in this folder" without strange hacks.

*support for system services means great automator integration

*document proxy in the window and generally better D&D support

*right click on a string to search in man pages or open its man page in a cool floating window. Really handy!

See:
http://www.macosxautomation.com/lion/terminal.html

A: iTerm supports opening windows in full screen by default, and there is an option to use custom full screen windows that don't have the animations for changing spaces and don't disable ⌘H.
It also has an incremental search banner instead of a find dialog. And you can select text by searching for the start and pressing tab to extend the selection by single words.

A: I use iTerm2 for my work in bioinformatics and have, for example, set it up in such a way, that it automatically opens a Genome Browser website in a specific chromosome position, when I cmd-click on the chromosome position.
Also, I tinkered with smart selection to allow me the selection of only DNA sequences, etc.
Also I set it to play a sound, if an Error message occurs in a terminal.
That's of course very specific use cases, but shows how capable iTerm2 is, compared to the simple Terminal client.

A: If you're a keen user of VIM then mouse mode in iTerm2 works properly - you can position the cursor and select text using the mouse (it kind of works in Terminal but it's buggy). Plus when you're running VIM (or other console based apps that use the 'alternate' screen (t_ti, t_te)) then the scrolling works properly too.
Also there's a very useful search facility which can be used to search the contents of all open iTerm2 tabs which can be reached by going to Window->Exposé all Tabs(⌥⌘E).
I also like the inline image display functionality which is possible using the iTerm2 tools tools which use some custom escape codes

A: I just love iTerm because it does have the auto-complete for commands.thats just awesome.
From the feature list for iTerm2's on its website:

Just type the start of any word that has ever appeared in your window
  and then Cmd-; will pop open a window with suggestions. The word
  you're looking for is usually on top of the list!

A: Besides the features already listed, iTerm2 is constantly improving, while Terminal receives minor updates every few years. Feature requests have a much better chance of being honored in iTerm2. There are some cool things coming in the next release that are not yet documented, but have a look through the recent release notes to see them.
Also, I'd note that there's some confusion about split panes in a comment in the OP. Terminal's split panes give you two views of the same window, while iTerm2's give you unlimited independent terminals in one tab.

A: From the iTerm2 web site:

iTerm2 has a lot of features. Every conceivable desire a terminal user might have has been foreseen and solved. And these are just the main attractions!

iTerm2's feature page highlights the following:

*

*Split Panes

*Hotkey Window

*Search Highlighted

*Autocomplete

*Mouseless Copy

*Paste History

*Instant Replay

*Configurability

*Unixyness

*256 Colors (or more!)

*Readability

*Mouse Reporting

*Growl Support

*Exposé Tab

*Tagged Profiles

*Multi-Lingual

*Triggers

*Smart Selection

*Shell Integration

*Automatic Profile Switching

*Inline Images

*Timestamps

*Password Manager

*Advanced Paste

*Annotations

*Badges

*Captured Output

A: I use iTerm2 since I can't configure my Mac Terminal have different colors background when I open different Terminals.


text:
Q: Django: Write a Create/Update template for a model with a ManyToMany-Through relationship In my app I have users, and each user can speak several languages, each at a different level. So this is how I wrote my models:
class Language(models.Model):
    name = models.CharField(max_length=255

class UserProfile(AbstractUser):
    languages = models.ManyToManyField(Language, through='SpeakingLevel')

class SpeakingLevel(models.Model):
    user = models.ForeignKey(UserProfile)
    language = models.ForeignKey(Language)

    LEVEL_OK = 1
    LEVEL_BAD = 2
    LEVEL_CHOICES = (
        (1, "Ok"),
        (2, "Bad")
    )
    level = models.IntegerField(null=True,
                                choices=LEVEL_CHOICES)

My doubt is how should I write the templates for the UserProfile creation/updating. I have no idea. The idea is having something like this (it's an screenshot from okcupid.com):

Of course, I can do it manually with a lot of javascript, and maybe a javascript template engine to add new languages to the list, but it sounds crazy for just handling a relationship, I'm sure I'm missing some cool Django feature to handle this.
What's the right way to do this?

A: This solution is apply when You create the UserProfile in django admin panel.
Django has something like inlines, but the problem with this is that the section with languages will not be visible while You create UserProfile, after You create that and go to the edit view, then You will see inline with languages.
Inline already has all required javascript code :)
PS. If You find some other 'cool' solution let me know in comment, I'm curious :)


text:
Q: Student grading program (I am a beginner) The program was running properly and now it not running anymore.
I wrote the code in Visual Studio first and the question is from Hackerrank.com, so the compiler from Hackerrank does not want to run this code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {
    /*
     * Complete the gradingStudents function below.
     */
    static int[] gradingStudents(int[] grades) {
       int fail = 40;

       for (int i = 0; i < grades.Length; i++)
       {
           if (grades[i] < fail)
           {
               double failcheck = Math.Round((double)grades[i] / 5, MidpointRounding.AwayFromZero) * 5;

               if (failcheck < fail)
               {
                   Console.WriteLine(grades[i]);
               }
               else
               {
                   Console.WriteLine(failcheck);
               }
           }
        }

        return grades;
    }

    static void Main(string[] args) {
        TextWriter tw = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int n = Convert.ToInt32(Console.ReadLine());
 grades = new int [n];

        for (int gradesItr = 0; gradesItr < n; gradesItr++) {
            int gradesItem = Convert.ToInt32(Console.ReadLine());
            grades[gradesItr] = gradesItem;
        }

        int[] result = gradingStudents(grades);

        tw.WriteLine(string.Join("\n", result));

        tw.Flush();
        tw.Close();
    }
}

Sample Input 0
4
73
67
38
33

Sample Output 0
75
67
40
33

A: If your problem is this ,
Then based on hackerrank problem description you should change method gradingStudents as:
static int[] gradingStudents(int[] grades)
{
    for (int i = 0; i < grades.Length; i++)
    {
        var item = grades[i];
        if (item >= 38)
        {
            var diff = 5 - (item % 5);
            if (diff < 3)
                grades[i] = item + diff;
        }
    }

    return grades;
}

A: using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {

    /*
     * Complete the gradingStudents function below.
     */
    static int[] gradingStudents(int[] grades) {
       for (int i = 0; i < grades.Length; i++)
        {

if (grades[i] >= 38)
            {
                int nextMultiple = grades[i];
                while (nextMultiple % 5 != 0)
                {
                    nextMultiple++;
                }
                if(nextMultiple - grades[i] < 3)
                {
                    grades[i] = nextMultiple;
                }
            }

        }
        return grades;

    }

    static void Main(string[] args) {
        TextWriter tw = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int n = Convert.ToInt32(Console.ReadLine());

        int[] grades = new int [n];

        for (int gradesItr = 0; gradesItr < n; gradesItr++) {
            int gradesItem = Convert.ToInt32(Console.ReadLine());
            grades[gradesItr] = gradesItem;
        }

        int[] result = gradingStudents(grades);

        tw.WriteLine(string.Join("\n", result));

        tw.Flush();
        tw.Close();
    }
}


text:
Q: Ajax Code that loads images on click next and previous for any kind of image silder that has huge no of Images using jsp I have one slider that works perfectly ..... but the images are loaded at the time of page load ...
I want to load the images on click because   I have lot of images to display so I can't load it my homepage because the page takes time to load so  I have to use Ajax that loads one image
and and append it to my list
can any body help me how to do it ...
here is the code .. its working ..
the java script part
(function($){
$.fn.imageSlider = function(options) {
    var options = $.extend({
        leftBtn: '.leftBtn',
        rightBtn: '.rightBtn',
        visible: 3,
        autoPlay: false,  // true or false
        autoPlayDelay: 10  // delay in seconds
    }, options);
    var make = function() {
        $(this).css('overflow', 'hidden');

        var thisWidth = $(this).width();
        var mod = thisWidth % options.visible;
        if (mod) {
            $(this).width(thisWidth - mod); // to prevent bugs while scrolling to the end of slider
        }

        var el = $(this).children('ul');
        el.css({
            position: 'relative',
            left: '0'
        });
        var leftBtn = $(options.leftBtn), rightBtn = $(options.rightBtn);

        var sliderFirst = el.children('li').slice(0, options.visible);
        var tmp = '';
        sliderFirst.each(function(){
            tmp = tmp + '
' + $(this).html() + '
';
        });
        sliderFirst = tmp;
        var sliderLast = el.children('li').slice(-options.visible);
        tmp = '';
        sliderLast.each(function(){
            tmp = tmp + '
' + $(this).html() + '
';
        });
        sliderLast = tmp;

        var elRealQuant = el.children('li').length;
        el.append(sliderFirst);
        el.prepend(sliderLast);
        var elWidth = el.width()/options.visible;
        el.children('li').css({
            float: 'left',
            width: elWidth
        });
        var elQuant = el.children('li').length;
        el.width(elWidth * elQuant);
        el.css('left', '-' + elWidth * options.visible + 'px');

        function disableButtons() {
            leftBtn.addClass('inactive');
            rightBtn.addClass('inactive');
        }
        function enableButtons() {
            leftBtn.removeClass('inactive');
            rightBtn.removeClass('inactive');
        }

        leftBtn.click(function(event){
            event.preventDefault();
            if (!$(this).hasClass('inactive')) {
                disableButtons();
                el.animate({left: '+=' + elWidth + 'px'}, 400,
                    function(){
                        if ($(this).css('left') == '0px') {$(this).css('left', '-' + elWidth * elRealQuant + 'px');}
                        enableButtons();
                    }
                );
            }
            return false;
        });

        rightBtn.click(function(event){
            event.preventDefault();
            if (!$(this).hasClass('inactive')) {
                disableButtons();
                el.animate({left: '-=' + elWidth  + 'px'}, 400,
                    function(){
                        if ($(this).css('left') == '-' + (elWidth * (options.visible + elRealQuant)) + 'px') {$(this).css('left', '-' + elWidth * options.visible + 'px');}
                        enableButtons();
                    }
                );
            }
            return false;
        });

        if (options.autoPlay) {
            function aPlay() {
                rightBtn.click();
                delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
            }
            var delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
            el.hover(
                function() {
                    clearTimeout(delId);
                },
                function() {
                    delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
                }
            );
        }
    };
    return this.each(make);
};

})(jQuery);
here is the html

<src>

<src>

<src>

<src>

<src>

This is the function that call Js File .
jQuery('.slider').imageSlider({
        leftBtn: '.sa-left',
        rightBtn: '.sa-right',
        visible: 5,
    });

And some CSS for formatting
So I  have a large no of Images 500 .... so i want to use ajax that loads images on click and append to the current list of images ......
any link or suggestion will be appreciated ......


text:
Q: Array issue with Vuejs and axios Hi I receive an answer from an axios like this:
axios.post('/api/hr_employee/days/'+ this.period_data.year +'/'+ this.period_data.month +'?page='+this.currentPage+'&api_token='+App.apiToken)
 .then(response => {
      this.posts = JSON.stringify(response.data.data);
      console.log(this.posts.rut);
      this.rowsQuantity = JSON.stringify(response.data.data.rut.length);
})

If I check the response it displays:
console.log(JSON.stringify(response.data.data));

{"rut":["06152617-K","06628494-8","06802969-4","06974036-7","07066149-7","07174172-9","07274753-4","07835227-2","08068401-0","08142157-9","08602937-5","08820315-1","08883533-6","09134412-2","09360615-9","09426000-0","09482390-0","09535406-8","09874855-5","10033721-5","10033741-K","10137545-5","10313233-9","10431151-2","10626085-0","10628514-4","10642899-9","10725575-3","10750262-9","10790603-7","10923452-4","10963260-0","11099111-8","11155155-3","11166398-K","11243121-7","11656483-1","11670463-3","11694645-9","11756501-7","11813180-0","11831400-K","11849551-9","11938713-2","12025353-0","12069398-0","12233298-5","12252924-K","12297111-2","12501219-1","12642557-0","12791259-9","12793546-7","12885196-8","12921934-3","12996111-2","13042688-3","13175573-2","13252171-9","13405296-1","13492547-7","13708510-0","13764500-9","13917718-5","14003387-1","14008227-9","14313469-5","14352987-8","14481738-9","14594420-1","15050542-9","15081798-6","15538007-1","15583027-1","15757306-3","15808735-9","15910256-4","15918421-8","15947022-9","16281232-7","16404869-1","16411890-8","16543379-3","16698947-7","16727358-0","16787383-9","16788913-1","16849126-3","17113779-9","17125113-3","17128461-9","17200607-8","17258553-1","17292825-0","17390237-9","17707004-1","17927553-8","17995199-1","18202568-2","18239456-4","18255994-6","18267465-6","18273096-3","18291733-8","18566961-0","18579236-6","18657051-0","18805028-k","18842465-1","18987839-7","19068615-9","19181860-1","19208732-5","19229525-4","19355444-K","19390553-6","19640455-4","19677914-0","19691447-1","19844084-1","19903195-3","19966543-K","20057484-2","20060059-2","20226059-4","20227575-3","20260330-0","20406658-2","20483426-1","20729074-2","20800385-2","20998161-0","21828453-1","21902443-6","22588139-1","22845770-1","23468753-0","23645227-1","23881022-1","24623559-7","24658304-8","24773648-4","24811238-7","24959860-7","25215942-8","25259612-7","25310541-0","25310683-2","25310734-0","25383726-8","25486922-8","25705970-7","25939855-K","26057740-9","26072855-5","26173938-0","26299443-0","26303301-9","26380591-7","26488988-k","26567665-0","26597593-3","26598819-9","26803446-3","26868737-8","26913967-6","26980959-0","27008182-7","27008183-5","27029453-7","27141399-8","27231254-0","27474935-0"],"full_name":["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"total_days":[30,30,30,21,30,30,30,30,30,30,30,30,30,30,27,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,1,30,30,30,26,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,17,30,30,30,30,30,30,30,30,30,30,29,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,26,30,30,30,30,1,30,30,16,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]}

BUT if I do this
 this.posts = JSON.stringify(response.data.data);
 console.log(this.posts.rut);
  undefined

so I wonder why does it display undefined if this.posts has same value? how can I fix it?
Thanks

A: I think it is because you stringify the response.data.data so this.posts data type become string. The string don't have rut property. That cause undefined when you log it.
I guess you don't need to JSON.stringify the response.data.data
try
this.posts = response.data.data;
this.rowsQuantity = response.data.data.rut.length;

A: That's because response from Axios is already in JSON format, but you are converting it to a string. To fix this issue, change the following line
From this:
this.posts = JSON.stringify(response.data.data);
To this:
this.posts = response.data.data;
You shall then be able to access the properties within the this.posts object

A: that's because you're trying to use the property access operator in a String value. You could fix that by calling JSON.parse(response.data.data) but I believe that axios already parses the response for you, so I think you can avoid using JSON.stringify.
JSON.stringify() returns a String value. You're getting undefined and not an error because Javascript does something called Object Wrapping (in this case it does new String(...))


text:
Q: cx_Oracle + oracle instance client 11g hang up next code works correct with instant client 10g, but hang up when using oracle instant client 11g, hangs on pool.release(conN),

import time
print '---------------------------------'
import cx_Oracle
print cx_Oracle.clientversion()
time.sleep(1)
pool = cx_Oracle.SessionPool('login', 'pass', "dbserver:1521/db", 1, 6, 2)
pool.timeout = 60
con11 = pool.acquire()
con12 = pool.acquire()
con13 = pool.acquire()
con14 = pool.acquire()
con15 = pool.acquire()
pool.release(con11)
pool.release(con12)
pool.release(con13)
pool.release(con14)
pool.release(con15)
for i in xrange(100000):
    print '-=-' + str(i) + '-=-'
    print str(pool.opened) + " " + str(pool.busy)
    con1 = pool.acquire()
    cursor = con1.cursor()
    cursor.execute("SELECT * FROM DUAL")
    count = cursor.fetchall()[0][0]
    cursor.close()
    print str(pool.opened) + " " + str(pool.busy)
    con2 = pool.acquire()
    cursor = con2.cursor()
    cursor.execute("SELECT * FROM DUAL")
    count = cursor.fetchall()[0][0]
    cursor.close()
    print str(pool.opened) + " " + str(pool.busy)
    con3 = pool.acquire()
    cursor = con3.cursor()
    cursor.execute("SELECT * FROM DUAL")
    count = cursor.fetchall()[0][0]
    cursor.close()
    print str(pool.opened) + " " + str(pool.busy)
    t1 = time.time()
    pool.release(con3)
    t2 = time.time()
    print t2 - t1
    print str(pool.opened) + " " + str(pool.busy)
    t1 = time.time()
    pool.release(con2)
    t2 = time.time()
    print t2 - t1
    t1 = time.time()
    pool.release(con1)
    t2 = time.time()
    print t2 - t1
    print str(pool.opened) + " " + str(pool.busy)
print '---------------------------------'

PS: I take look into cx_Oracle source code, it's hands in seesionpool.c on line
    status = OCISessionRelease(connection->handle,
            connection->environment->errorHandle, NULL, 0, mode);
Any ideas how to solve it?
PPS: OS Windows XP and 2008R2

A: http://cx-oracle.sourceforge.net/html/session_pool.html
Note This object is an extension the DB API and is only available in Oracle 9i.

A: I had the same symptoms yesterday: In a multi-threaded application with a session pool, sometimes releasing the session hangs for up to 2 minutes.
You are probably hitting one of the following Oracle bugs:

Bug 10157313 - Excessive CPU usage and poor performance of OCISessionRelease when using OCI session pooling (Doc ID 10157313.8)
Bug 10157313 : OCI SESSION POOLING INCREASE CPU USAGE AND TAKE LONG TO RELEASE WHEN USING 11.2

For details see Oracle Metalink.
Updating the Oracle client software to 11.2.0.3 or later (eg InstantClient 11.2.0.3) seems to help.


text:
Q: Update product from a module in prestashop I have to update the price and quantity values of specific products in a database.
As I understand, simply executing sql commands is not a great option since there are a lot of tables which have similar informations. I have read that Product() object should be created.
How should I create the Product object and then update it in the database?

A: You can check the class ProductCore in classes/Product.php for various methods and properties
Generally, you would write some code like this
//assuming you have the product id as $id_product
$product = new Product($id_product);
//change the product properties
$product->quantity = 10;
$product->price = 60.2;
//save the changes
$product->save();

Edit:
To update the quantity you can use this method:
StockAvailable::updateQuantity($id_product, $id_product_attribute, $delta_quantity, $id_shop = null);


text:
Q: I need to create a method in the acount trigger to keep an external id field value updated. (continue in body) This value has to be the name of the account. Every time an account is inserted or its name changes, it is necessary to update the external id. How can i do that? thanx.
Public static void updateAcc ();
   List<Account> accounts = [Select Id from Account where External_Id__c = ''];
   for (Account account : accounts) {
     account.External_Id__c = account.Id;
   }
   update accounts;

A: Public static void updateAcc ();
   List<Account> accounts = [Select Id from Account where External_Id__c = ''];

If you are in a trigger handler, presumably in a before insert or before update context, you should be working with the Trigger.new context variable. There is no need to perform a SOQL query.
Note that empty strings are not stored in the database. If you run a query of this kind, you must query for null, not ''.
   for (Account account : accounts) {
     account.External_Id__c = account.Id;
   }
   update accounts;

This doesn't make sense. Your question stated that you need to assign the Account's Name, not its Id, as the External Id field. Setting another field on the same object to the Id is generally a waste of time; you should simply use the Id field.
If you are in an before trigger, which you should be for this operation, it's not necessary to perform update DML so long as you directly modify the sObjects in Trigger.new. The system automatically persists changes for you.
Your code presumably should look something like this:
for (Account a : Trigger.new) {
    a.External_Id__c = a.Name;
}

although I remain skeptical of the premise of using a Name field as an external Id.


text:
Q: DDD - Modifications of child objects within aggregate I am having some difficulty working out the best way to handle a fairly complex scenario. I've seen quite a few similar questions, but none addressed this scenario to my satisfaction.
An Order (aggregate root) is created with multiple OrderLines (child entities). According to business rules, each OrderLine must maintain the same identity for the life of the Order. OrderLines have many (20+) properties and can be mutated fairly often before the Order is considered "locked". In addition, there are invariants that must be enforced at the root level; for example, each Order Line has a quantity and the total quantity for the Order cannot exceed X.
I'm not sure how to model this scenario when considering changes to OrderLines. I have 4 choices that I can conceive of, but none seem satisfactory:
1) When the time comes to modify an OrderLine, do it using a reference provided by the root. But I lose the ability to check invariant logic in the root.
var orderLine = order.GetOrderLine(id);
orderLine.Quantity = 6;

2) Call a method on the order. I can apply all invariant logic, but then I'm stuck with a proliferation of methods to modify the many properties of the OrderLine:
order.UpdateOrderLineQuantity(id, 6);
order.UpdateOrderLineDescription(id, description);
order.UpdateOrderLineProduct(id, product);
...

3) This might be easier if I treated the OrderLine as a Value Object, but it has to maintain the same identity per business requirements.
4) I can grab references to the OrderLines for modifications that do not affect invariants, and go through the Order for those that do. But then what if invariants are affected by most of the OrderLine properties? This objection is hypothetical, since only a few properties can affect invariants, but thhat can change as we uncover more business logic.
Any suggestions are appreciated...do not hesitate to let me know if I'm being dense.

A: *

*Is not optimal because it allows breaking domain invariant.

*Will result in code duplication and unnecessary method explosion.

*Is the same as 1). Using Value Object will not help with maintaining domain invariant.

*This option is what I would go with. I would also not worry about potential and hypothetical changes until they materialize. The design will evolve with your understanding of the domain and can always be refactor later. There is really no value in hindering your existing design for the sake of some future changes that may not happen.

A: One drawback of 4 as opposed to 2 is lack of consistency. In certain instances it might be beneficial to maintain a degree of consistency in regards to updating order line items. It may not be immediately clear why certain updates are done through the order while others through the order line item. Furthermore, if order lines have 20+ properties, perhaps that is a sign that there is potential for grouping among those properties resulting in fewer properties on the order line. Overall, approach 2 or 4 is fine as long as you make sure to keep operations atomic, consistent and in correspondence with ubiquitous language.

A: There is a fifth way of doing this. You can fire a domain event (e.g. QuantityUpdatedEvent(order, product, amount)). Let the aggregate handle it internally by going through the list of orderlines, select the one with matching product and update its quantity (or delegate the operation to OrderLine which is even better)

A: The domain event is the most robust solution.
However if that's overkill you can also do a variation of #2 using the Parameter Object pattern - have a single ModfiyOrderItem function on the entity root.  Submit a new, updated order item, and then internally the Order validates this new object and makes the updates.
So your typical workflow would turn into something like
var orderItemToModify = order.GetOrderItem(id);
orderItemToModify.Quantity = newQuant;

var result = order.ModifyOrderItem(orderItemToModfiy);
if(result == SUCCESS)
{
  //good
 }
else
{
   var reason = result.Message; etc
}

The main shortcoming here is it allows a programmer to modify the item, but not commit it and not realize that.  However it is easily extensible and testable.

A: Here's another option if your project is small and you want to avoid the complexity of domain events.  Create a service that handles the rules for Order and pass it in to the method on OrderLine:
public void UpdateQuantity(int quantity, IOrderValidator orderValidator)
{
    if(orderValidator.CanUpdateQuantity(this, quantity))
        Quantity = quantity;
}

CanUpdateQuantity takes the current OrderLine and the new quantity as arguments.  It should lookup the Order and determine if the update causes a violation in the total Order quantity.  (You will have to determine how you want to handle an update violation.)
This may be a good solution if your project is small and you don't need the complexity of domain events.
A downside to this technique is you are passing a validation service for Order into OrderLine, where it really doesn't belong.  By contrast, raising a domain event moves the Order logic out of OrderLine.  The OrderLine can then just say to the world, "Hey, I'm changing my quantity." and the Order validation logic can take place in a handler.

A: what about using DTO ?
public class OrderLineDto
{
    public int Quantity { get; set; }
    public string Description { get; set; }
    public int ProductId { get; set; }
}

public class Order
{
    public int? Id { get; private set; }
    public IList<OrderLine> OrderLines { get; private set; }

    public void UpdateOrderLine(int id, OrderLineDto values)
    {
        var orderLine = OrderLines
            .Where(x => x.Id == id)
            .FirstOrDefault();

        if (orderLine == null)
        {
            throw new InvalidOperationException("OrderLine not found.");
        }

        // Some domain validation here
        // throw new InvalidOperationException("OrderLine updation is not valid.");

        orderLine.Quantity = values.Quantity;
        orderLine.Description = values.Description;
        orderLine.ProductId = values.ProductId;
    }
}

*

*only issue here is that OrderLines property has public getter and user of this class can add item into collection. The only way I can think of how to prevent it, is to hide getter and add new getter which will return collection of DTO's if there is a need for that.

*the id parameter of UpdateOrderLine method can be part of DTO, it would probably work better with that

*probably you can accept OrderLine as a parameter directly instead of OrderLineDto (if you would like to use some OrderLine validation before passing to Order).