text:
Q: Is it possible to create a login for restricted visibility? I use eStore (from Elegant Themes) with Woocommerce to build a webshop. I want to add a login page for wholesalers to login and have access to different products (2014 collection) and different price of the current collection. The 2nd wholesale webshop should not be visible unless the user is logged in.
Would Multisite be the solution? (But would I still have to connect iDeal to both sites?)

A: You should be able to create a role for your wholesalers and then toggle price based on membership in that role, or limit access to certain "Pages" to members of that role. That is going to be much easier than multiple linked sites.
Your question is lacking detail and code (which might be closed source in this case anyway), so it is hard to be more specific but maybe that will get you started. Edit the question with more detail and I will revisit this.


text:
Q: An error occurred while calling o227.run I'm newer to spark , I tried to create a graphframe and do some query on that this is my code
import pyspark
from pyspark.sql import SQLContext
from graphframe import *
sc = pyspark.SparkContext()
sqlContext = SQLContext(sc)
vertices = sqlContext.createDataFrame([
("1","Alex", 28, "M","MIPT"),
("2","Emeli", 28, "F","MIPT"),
("7","Ilya", 29, "M","MSU")], ["id","name","age","gender","university"])
edges = sqlContext.createDataFrame([
("1","2","friend")
], ["src", "dst" , "type"])
g=GraphFrame(vertices,edges)
result = g.connectedComponents()

but it shows as the result the following error:

Traceback (most recent call last):
    File "", line 1, in
    File "C:\Users\ALI_PC\AppData\Local\Temp\spark-73d7bc01-3873-4423-ac2b-527e39608ece\userFiles-b2dd0ea9-9556-4bea-9931-915608bad9b0\graphframes_graphframes-0.5.0-spark2.1-s_2.11.jar\graphframes\graphframe.py", line 279, in connectedComponents
    File "C:\Spark\spark-2.2.1-bin-hadoop2.7\python\lib\py4j-0.10.4-src.zip\py4j\java_gateway.py", line 1133, in call
    File "C:\Spark\spark-2.2.1-bin-hadoop2.7\python\pyspark\sql\utils.py", line 63, in deco
      return f(*a, **kw)
    File "C:\Spark\spark-2.2.1-bin-hadoop2.7\python\lib\py4j-0.10.4-src.zip\py4j\protocol.py", line 319, in get_return_value
  py4j.protocol.Py4JJavaError: An error occurred while calling o249.run.
  : java.io.IOException: Checkpoint directory is not set. Please set it first using sc.setCheckpointDir().
          at org.graphframes.lib.ConnectedComponents$$anonfun$2.apply(ConnectedComponents.scala:280)
          at org.graphframes.lib.ConnectedComponents$$anonfun$2.apply(ConnectedComponents.scala:280)
          at scala.Option.getOrElse(Option.scala:121)
          at org.graphframes.lib.ConnectedComponents$.org$graphframes$lib$ConnectedComponents$$run(ConnectedComponents.scala:279)
          at org.graphframes.lib.ConnectedComponents.run(ConnectedComponents.scala:139)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:498)
          at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
          at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
          at py4j.Gateway.invoke(Gateway.java:280)
          at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
          at py4j.commands.CallCommand.execute(CallCommand.java:79)
          at py4j.GatewayConnection.run(GatewayConnection.java:214)
          at java.lang.Thread.run(Thread.java:745)

how can I fix this problem,thank you!

A: Exactly as stated in the exception message:

Checkpoint directory is not set. Please set it first using sc.setCheckpointDir().

you have to set checkpoint directory:
sc.setCheckpointDir(path_to_checkpoint_directory)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the growth rate for divisibility of integers For a natural number $n\geq 1$, let $PF(n)$ denote the number of prime factors (with multiplicity) of $n$. For example, since $48=2*2*2*2*3$, we have $PF(48)=5$.
For any natural number $N\geq 1$, define $$E(N)=\frac{\sum_{k=1}^N PF(k)}{N},$$ the expected value for the number of prime factors for an integer between $1$ and $N$.
I have computed, for example, that $E(2^{22})\approx 3.63,$ and the sequence generally seems to increase. (Of course, the sequence $E(N)$ is not monotonically increasing, because it decreases when $N$ is prime. But when I evaluate $E(2^m)$ for various $m$, I find it is monotonically increasing for $m\leq 22$.
${\bf Question}$: Does there exist an elementary function $g\colon\{\mathbb N}\rightarrow {\mathbb N}$ such that $$E(n)\in\Theta(g(n)).$$ Here we are using "big-$\Theta$" notation; one function is said to be "big-$\Theta$" of another function if the first is asymptotically bounded above and below by a nonzero constant multiple of the second. By "elementary function," I mean the standard definition; roughly the closure under sum, product, quotient, and composition of exponential, log, and polynomial functions.

A: This Theorem 430, on page 355 of Hardy and Wright, that he "average order" of $\Omega(n)$ is $\log \log n.$ Then they point out, formula 22.10.2, that
$$ \sum_{n \leq x} \; \Omega (n) \; = \; x \log \log x + B_2 x + o(x)  $$ and say how to find the constant $$B_2 = B_1 + \sum_p \; \frac{1}{p(p-1)}.    $$
Previously , $B_1$ was given as the constant in Merten's Theorem, first 427:
$$  \sum_{p \leq x} \; \frac{1}{p} \; = \; \log \log x + B_1 + o(1),  $$
then theorem 428,
$$  B_1 = \gamma + \sum \left\{ \log \left( 1 - \frac{1}{p} \right) +  \frac{1}{p} \right\}$$
so that $B_1 = 0.26149721\ldots$

A: Sorry, I've asked a similar question before, and the current question seems to have been answered there by Cam McLeman. The answer he gives is $PF(n)\approx ln(ln(n)).$ To me, this means that $E(N)$ should also be $ln(ln(N))$.


text:
Q: Creating a timeline in ggplot Edited below with complete and functioning code:
I am trying to create a timeline similar to the one this code creates from the Timeline package, however, the options are not very flexible.  For example, I would like to create space between each bar so they are not touching. Also, I am wondering if there is a way to add the "End_Status" column to the graph so that it it is obvious that the data stops there because the animal died.  Any help is greatly appreciated.
Example dataset:
df <- data.frame(id = c(rep(1201, 10), rep(1202, 14), rep(1203, 6),     rep(1204, 22)),
             date = c(seq(1,5,1), seq(5,7,1), seq(7,8,1), seq(2,5,1), seq(7,9,1), seq(11,17,1), seq(1,8,1), seq(8,12, 1), seq(12,26,1 )),
             schedule = as.factor(c(rep(1, 5,), rep(2, 3), rep(3, 6),
                                 rep (1, 3), rep (2, 2), rep(3, 5),
                                 rep(1,8), rep(2, 5), rep(1,3), rep(3, 12))),
             status = c(rep("", 9), "Mort", rep("", 41), "Mort"))

Code to get the output table I am interested in:
library("data.table")
library(plyr)
library(dplyr)

df<-as.data.table(df)
z <- df[, unique(id)]
################
value_change_first <- function(x,a) { for(i in 1:length(x[,schedule])) {
ifelse(x[a,schedule] == x[a+1,schedule],
       x <- x[-(a+1)],
       a <- a+1)}
return(x)
}

value_change_second <- function(x,a) {
for(i in 1:length(x[,schedule])) {
ifelse(x[a,schedule] == x[a+1,schedule],
       x <- x[-(a)],
       a <- a+1)}
return(x)
}

#################
output_1 <- c()

for(i in 1:length(z)){
ids <- df[df$id==z[i],]
out<-value_change_first(ids,1)
output_1<-as.data.frame(rbind(output_1, out))}

#################
output_2 <- c()

for(i in 1:length(z)){
ids <- df[df$id==z[i],]
out<-value_change_second(ids,1)
output_2<-as.data.frame(rbind(output_2, out))}

################
output_1$End_Date <- output_2$date
output_1$End_Status <- output_2$status
names(output_1)[names(output_1)=="date"] <- "Start_Date"

output <- output_1[c(1:2, 5, 3, 6)]

From here I can use the Timeline Package to get something close to what I want:
require(timeline)
tl <- timeline(output,
           label.col=names(output)[4],
           text.color= NA,
           group.col=names(output)[1],
           start.col=names(output)[2],
           end.col = names(output)[3])
tl + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor    = element_blank())

My question is how to build something similar in ggplot.  Furthermore, I want to specifically add the "Mort" message at a given date by individual from the output dataframe.
I ended up getting this to work like I want:
### creating a end status column that includes mortalities and failures
output$End_Status_Date<-NA
for(i in 1:nrow(output)){
if(output$End_Status[i] == "Mort"){
output$End_Status_Date[i]=as.character(output$End_Date)[i]
}
}

for(i in 1:nrow(output)){
if(output$End_Status[i] == "Failure"){
output$End_Status_Date[i]=as.character(output$End_Date)[i]
}
}

### data structuring
output$id<-as.factor(output$id)
output$End_Status_Date<-as.numeric(output$End_Status_Date)
output$End_Status[output$End_Status == ""] <- NA
output$End_Status<-as.character(output$End_Status)
output$End_Status<-as.factor(output$End_Status)

library(ggplot2)

g2 <- ggplot() +
geom_segment(data=output, aes(x=Start_Date, xend=End_Date, y=id, yend=id,    color=schedule), linetype=1, size=2) +
geom_point(data=subset(output, is.na(End_Status)==FALSE),
         mapping=aes(x=End_Status_Date, y=id, shape=End_Status,   fill=End_Status), size=4)+
scale_colour_manual(values=c("blue4", "chartreuse4", "darkmagenta"))+
scale_fill_manual(values=c("white", "red"))+
scale_shape_manual(values=c(21,24))+
xlab("Time")+
ylab("Individuals")+
theme_bw() + theme(panel.grid.minor = element_blank(), panel.grid.major =   element_blank())

g2

A: You did most of the work already. The key here is just to use geom_rect and take advantage of your y-axis labels to set the ymin and ymax values.
ggplot(output, aes(xmin = Start_Date, xmax = End_Date,
                   ymin = as.numeric(id) - 1, ymax = as.numeric(id),
                   fill = schedule)) +
  geom_rect() +
  geom_text(aes(x = End_Date, y = id, label = End_Status))


text:
Q: My access to word merge code is not working I have made a form in access and I'm trying to code a "merge to word" button but my code has a problem and I dont know how to fix it.
Here's the code:
Private Sub Command102_Click()
Dim LWordDoc As String
Dim oApp As Object

'Path to the word document
LWordDoc = "C:\school\information tech\document.docx"

If Dir(LWordDoc) = "" Then
  MsgBox "Document not found."

Else
  'Create an instance of MS Word
  Set oApp = CreateObject(Class:="Word.Application")
  oApp.Visible = True

  'Open the Document
  oApp.Documents.Open FileName:=Document.docx
End If
End Sub

If someone could help that would be great. Ill attach screenshots of the error I get when I click the button and the code as the debugger is pointing to the problem. (pointing to the start of the "oApp.Documents.Open FileName:=Document.docx" line)
Thanks heaps

A: Since you create a variable to hold the filename, try using that:
oApp.Documents.Open FileName:=LWordDoc


text:
Q: Bound click loses context of my Class. JS I have this problem that I probably understand but don't know how to handle, if there is a way.
I have a class simplified as this:
function DrawingTable(canvas_id){
  this.canvas_id = canvas_id;
  bind_events()

  function bind_events(){
  $(get_canvas()).click(function(e){
    var canvas = get_canvas() //works
    do_something_in_the_instance_who_called_click()
  }

  function get_canvas(){return document.getElementById(canvas_id)}

  function do_something_in_the_instance_who_called_click(){
    alert(this.canvas_id) //fail!
  }

}

Because when the click() is invoked for what it looks this is not inside the instance anymore, but I need to change attributes from there. Is there a way, given that may be multiple instances?
I don't really know how but the get_canvas() works :)
I'm using jQuery but likely not relevant

A: That happens because you are calling the function without any object context, but you can store the this value:
function DrawingTable(canvas_id){
  var instance = this;  // <-- store `this` value

  this.canvas_id = canvas_id;
  bind_events()

  function bind_events(){
  $(get_canvas()).click(function(e){
    // Note also that here the `this` value will point to the
    // canvas elemenet, `instance` should be used also

    var canvas = get_canvas();
    do_something_in_the_instance_who_called_click();
  }

  function get_canvas(){return document.getElementById(canvas_id)}

  function do_something_in_the_instance_who_called_click(){
    alert(instance.canvas_id); // <-- use stored `this` value
  }

}

The this value is implicitly set when you make a function call, for example:
obj.method();

The this value will point to obj, if you make a function call without any base object, e.g.:
myFunction();

The this value inside myFunction will point to the global object.


text:
Q: ¿Como tomar un valor de un Json dentro de otro Json en android studio? la verdad soy un poco nuevo en el tema de las apps, entonces estoy haciendo una, la app conecta con un webservice que me devuele un Json y tomo los valores de ese Json y los muestro dentro de la app, el código de ese webService es el siguiente:
 class app_android_residuos_rv extends Controller
 {

public function busqueda()
{
    $success = false;
    $message = "";
    $caja = "";

    if($recepcionResiduosRevalorizables = recepcionResiduosRevalorizables::all()){
        $success = true;
        $message = "Documentos cargados correctamente";
    } else {
        $success = false;
        $message = "Error al cargar los datos";
    }
    for ($i = 0; $i < count($recepcionResiduosRevalorizables); $i++) {
        $recepcionResiduosRevalorizables[$i]->caja;
    }

   return response()->json([
    'data'   =>  $recepcionResiduosRevalorizables,
    'success' => $success,
    'message' => $message
   ]);
}

Ese webservice me devuelve el siguiente Json:

{"data":[{"id":88,"carton":"66.00","emplaye":"45.00","observaciones":"chsvito","fecha_hora_captura":"2020-10-12 11:17:16","numero_pallets":66,"caja_id":840,"caja":{"id":840,"numero":"35"}},{"id":99,"carton":"22.00","emplaye":"66.00","observaciones":"resentido","fecha_hora_captura":"2020-10-13 15:19:52","numero_pallets":65,"caja_id":816,"caja":{"id":816,"numero":"1"}}],"success":true,"message":"Documentos cargados correctamente"}

Como podrán notar dentro del Json tengo otro con el nombre "caja" y dentro del Json "caja" tengo los valores: "id" y "número"
El código de mi aplicación para consumirlo es el siguiente:
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_SELECT, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            progressDialog.dismiss();
            try{

                progressDialog.hide();
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("data");

                Toast.makeText(ListActivity.this,jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                for (int i = 0; i<jsonArray.length(); i++){
                    JSONObject o = jsonArray.getJSONObject(i);
                    Model item = new Model(
                            o.getString("id"),
                            o.getString("carton"),
                            o.getString("emplaye"),
                            o.getString("observaciones"),
                            o.getString("numero_pallets"),
                            o.getString("fecha_hora_captura"),
                            o.getString("caja")
                    );
                    listItems.add(item);

                    adapter = new MyAdapter(listItems,getApplicationContext());
                    recyclerView.setAdapter(adapter);

                }
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            progressDialog.hide();
            Toast.makeText(ListActivity.this, "ERROR",Toast.LENGTH_SHORT).show();
        }
    }){
        protected Map<String , String> getParams() throws AuthFailureError {
            Map<String , String> params = new HashMap<>();
            params.put("id", "kl");
            return params;
        }
    };
    RequestHandler.getInstance(ListActivity.this).addToRequestQueue(stringRequest);
}

Hasta aquí todo bien, el código me trae los valores tal cual los necesito, el problema esta en la linea que dice :
  o.getString("caja")

Ya que este me trae como valor el Json "caja" ejemplo, me muestra el siguiente valor:
 "caja":{"id":816,"numero":"1"}

Cuando yo necesito únicamente el valor de "numero" dentro de "caja" y no se como invocarlo, he investigado, e incluso trate de hacerlo como se haría en una vista de laravel, pero nada me sale, agradecería su ayuda.
Añado imagén de como se ve:

A: De acuerdo a la estructura de tu json, el elemento "caja" es un objeto:

por lo tanto si deseas obtener un valor dentro del objeto "caja", simplemente crea un JSONObject y obtén su valor de "numero":
new JSONObject(o.getString("caja")).getString("numero")

Este sería el código :
                Model item = new Model(
                        o.getString("id"),
                        o.getString("carton"),
                        o.getString("emplaye"),
                        o.getString("observaciones"),
                        o.getString("numero_pallets"),
                        o.getString("fecha_hora_captura"),
                        new JSONObject(o.getString("caja")).getString("numero")
                );


text:
Q: scala code coverage using scct, how to exclude files by regex using scct in my project there are some files I would like to be excluded
my build file :
object myBuild extends Build {

  lazy val americanNinja1 = Project(id = "American-Ninja", base = file("americanNinja")).settings(ScctPlugin.instrumentSettings: _*)

 //more code .....
}

how can i add setting to the scct to exclude all .html files (for example)
looking at the github project of scct i see that there is a filter option
https://github.com/sqality/scct/blob/master/src/main/scala/com/sqality/scct/CoverageFilter.scala
and there was an issue that was solved for this matter :
https://github.com/mtkopone/scct/issues/60
any idea how to do this ?
Thanks!

A: I have fixed similar problem two days ago, but I had to fork SCCT and SBT-SCCT as well and fix some things. First problem was that SBT-SCCT wasn't passing the "scctExcludePackages" setting to SCCT correctly. Also I have modified SCCT so that it excludes based on package name instead of file name. I know this doesn't solve your issue, but use this as an inspiration and feel free to contribute:
https://github.com/RadoBuransky/sbt-scct/commit/b301a9cb21447c3a531707437b95e5f39e9ce336
https://github.com/RadoBuransky/scct/commit/d6244d54ef00f01f6019d7cf1bd0fd927ce75e08

A: You could take a look at https://github.com/scoverage/sbt-scoverage which is a fork of SCCT and supports exclusions, but it does not support multi project builds at the moment.


text:
Q: Docker compose django, nginx, daphne expose internet in EC2 Hello i need expose the containers to internet i read thats is with ip table and works in in the instance but i can't access by internet for the moment and this is my configuration:
EC2 instance:
Ubuntu
Docker vserions:
Docker version 20.10.7, build f0df350
docker-compose version 1.25.0, build unknown
docker-compose.yml
version: '3.1'

services:
  redis:
    image: redis
    command: redis-server --port 6379
    ports:
      - '6379:6379'
    environment:
      - REDIS_MODE="LRU"
      - REDIS_MAXMEMORY="800mb"

  server:
    build: .
    command: daphne rubrica.asgi:application --port 8000 --websocket_timeout -1 --bind 0.0.0.0 -v2

    volumes:
      - .:/src
      - ${AWS_CREDENTIALS_PATH}:/root/.aws/
    ports:
      - "8000:8000"
    links:
      - redis
    env_file:
      - .env

  nginx:
    image: nginx
    volumes:
      - ./nginx/:/etc/nginx/
    links:
      - server
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - server
    command: ["nginx", "-g", "daemon off;"]

networks:
  docker-network:
    driver: networktest

network
sudo docker create --name networktest --network <instance ip> --publish 8080:80 --publish 443:443  nginx:latest

and this is the rules in my instance

If someone can help me to know what i need or a can't see in the configuration.


text:
Q: Xcode 9 - linker command failed with exit code 1 While compiling the application getting as following error
" compiled with older version of Swift language (3.0) than previous files (4.0) file "
Could you please help me?

A: Delete the derived data and do a clean build.
And if you are building a framework, make sure you've selected Generic IOS Device while building or set the Build for Active Architecture only as true in Build Settings.

A: I think this happens because you changed your app name or maybe the target
look to solve this problem see your target in Podfile
and then come back to your xcode in the targets
select your target app and in linked Frameworks and Libraries (the last one down) see if there's
any pods with light color and a strange name than your target in the podfile
and remove it using the minus button down .

A: Use the xcworkspace to build instead of the xcproject?
This usually happens when using Cocoapods and you are building from the xcproject which doesn't know about the cocoapod libraries.

A: I'd rather fix the specific problem, but if none of the other answers worked a full reset can solve it.  If you are getting this error and you are also getting error readouts that refer to "duplicate symbol files", AND all other efforts have failed, then a full reset could work for you.
What worked for me:

*

*Read the error report to identify the repo that supposedly contains duplicate files.

*Drag repo to the trash.

*re-clone your repo.

*set up your repo with correct remote tracking. git remote add <url.git>, or git remote set-url <url.git>
This absolutely worked for me. In my case for some elusive reason, when I ran git pull upstream develop for a local dependency, git would pull in/generate duplicate files from multiple commits.
After following the above steps, the issue went away and git pull upstream develop was no longer pulling from multiple commits at once. Perhaps there was a weird git cache for my repo.

A: I had the two copies of files in the codebase. Deleting one copy helped code to build successfully

A: I am probably late for you, but for future devs in problems...
If you have been manipulating the podfile or creating new targets or maybe changing the name of any of them, check that in build phases options your just have correct pod framework for the name of the targets.

A: if you have pod
first clean project and close Xcode then open terminal and go to folder of Project then pod update
open the project and run
in my case work!

A: I fixed this problem today by running the app in the simulator using the target associated with the bundle file named in the Build Settings-->Bundle Loader setting of the test target.  Previously I had deleted my derived data folder while working on a different target that has a different Product Name than the one associated with the test target bundle file.  Rerunning the app in the simulator must have recreated the bundle file in the derived data folder that the test target is looking for and then my tests started running fine.


text:
Q: the difference between "here" and "in here" I have this confusion about whether to use "here" or "in here"
For example, if I am in an event and speaking with somebody, and I want to express that someone else is also present in this event. Should I say "xxx(the person's name) is also in here" or just  "xxx(the person's name) is also here"
Also, when I am travelling in some places and talking with the locals, should I say "I just arrived here two days ago" or "I just arrived in here two days ago"
Also, do they always have the same meaning?
Thanks

A: Think of "in here" as a more specific version of "here".  In many cases you can substitute "here" for "in here", without really losing any meaning.

John just texted that he's at the event, so I know he's in here/ here somewhere.

However, "in here" is not a substitute for "here", as it means something is inside, or at least within, some fairly specific location.  While it's possible in your second example, it sounds strange to use "in here" with something like an entire city, because it suggests the person or thing is either visible or can be located with a brief search.
Some examples of using "in here" to emphasis the idea of an enclosed area:

It's too dark in here.  Could you turn on another light?
Let me check the pantry.  I know there is sugar in here somewhere.
Captain, we have a problem.  I think the alien is in here with us.

A: Regarding your first question, if you are in a room or some kind of enclosed space, it would be correct to say, "in here." For example, let's say someone asks you, "Is John Smith here?" You could say, "Yes, he's in here somewhere." Or you could just say, "Yes, he's here." Of course, if the event is outdoors, just say, "He's here." You can't say "in here" if you're outdoors.
Regarding your second question, if you're trying to tell them how long you've been in town, say, "I just arrived here two days ago." "In here" usually refers to being in some kind of enclosed space.


text:
Q: Python VSCode: Run Main file in Python Interactive Window This seems like a basic question, but I can't seem to find a setting/process for it.
In VSCode's Python extension, there is an option to right-click (or keyboard shortcut) in the editor and Run Current File in Python Interactive Window.  This works great.
Is there a way to Run Main File in Python Interactive Window so to speak? If you are building a package/module and are making changing in a non-main file, you currently need to switch back to that main file editor tab before running it as described above.
It would be nice to link module/package files to run the main file from anywhere in the package and not have to switch files in the editor.  This would make building/debugging a separate module file much faster using the Python Interactive Window. Thanks

A: Create a launch option that names the main python file instead of the current file and choose it in the debug/run sidebar.
You might need to set the cwd property to the correct value.
Now when you press F5 the main python file is run.


text:
Q: how to sort out files according to excel I have an Excel file that contains long product tag name like(for now, just working on 3 of them):

*

*4049047000037

*4049047000044

*4049047118954

and i have a folder on my desktop called "1" containing .jpg files with tag names like:

*

*4049047000037.jpg

*4049047000044.jpg

*4049047118954.jpg

i want to write a code, if tag name in my excel, i want to copy that .jpg file to an other folder.
import os
import pandas as pd
movdir = ["C:\Users\muhammedcan\Desktop\1"]
basedir = "C:\Users\muhammedcan\Desktop\2"
i=0

#to see what i have in my folder
print os.listdir("C:/Users/muhammedcan/Desktop/1/")

df= pd.read_excel("deneme.xls", sheetname= "sayfa4")
df1= df.columns[1]

listSepalWidth = df[df1]
print listSepalWidth

#to make file name and product tag name same
for i in listSepalWidth:
    i=str(i)+(".jpg")
    print i

can you help me with copying file into an other file if it is exist in my excel?
this is my result so far:
['4049047000037.jpg', '4049047000044.jpg', '4049047000068.jpg',
'4049047000075.jpg', '4049047000082.jpg', '4049047000105.jpg',
'4049047118947.jpg', '4049047118954.jpg']

4049047000037.jpg
4049047000044.jpg
4049047118954.jpg
4049047000068.jpg
4049047000075.jpg
4049047000082.jpg
4049047118947.jpg
4049047000105.jpg

I used following code, and I am recieving error.
from shutil import copyfile

copyfile("C:\Users\muhammedcan\Desktop\1", "C:\Users\muhammedcan\Desktop\2")

Error is:
    C:\Python27\python.exe "C:/Users/muhammedcan/Desktop/summer
    courses/programing/MP4/solution/my_work.py"
    Traceback (most recent call last):
  File "C:/Users/muhammedcan/Desktop/summer courses/programing/MP4/solution/my_work.py", line 3, in <module>
    copyfile("C:\Users\muhammedcan\Desktop\1",

Process finished with exit code 1

A: The following should do what you are looking for:
import os
import glob
import pandas as pd
import shutil

source_folder = r"C:\Users\muhammedcan\Desktop\1"
destination_folder = r"C:\Users\muhammedcan\Desktop\2"

available_filenames = [os.path.basename(fn) for fn in glob.glob(os.path.join(source_folder, '*.jpg'))]
df = pd.read_excel("deneme.xls", sheetname="sayfa4")

for tag_name in df.iloc[:,1]:
    filename = "{}.jpg".format(tag_name)

    if filename in available_filenames:
        print "{} - found".format(filename)
        shutil.copyfile(os.path.join(source_folder, filename), os.path.join(destination_folder, filename))
    else:
        print "{} - not found".format(filename)

If first creates a list of .jpg filenames found in the source_folder. It then loads the Excel file into pandas and iterates over the second column. If the tag name is found in the list of available_filenames the shutil.copyfile() function is used to copy the file from 1 to 2. Note os.path.join() is used to safely join parts of a file together.

To make it into a function to let you also do 'pdf' you could do:
import os
import glob
import pandas as pd
import shutil

source_folder = r"C:\Users\muhammedcan\Desktop\1"
destination_folder = r"C:\Users\muhammedcan\Desktop\2"

df = pd.read_excel("deneme.xls", sheetname="sayfa4")

def copy_files(source_folder, destination_folder, extension):
    available_filenames = [os.path.basename(fn) for fn in glob.glob(os.path.join(source_folder, '*.{}'.format(extension)))]

    for tag_name in df.iloc[:,1]:
        filename = "{}.{}".format(tag_name, extension)

        if filename in available_filenames:
            print "{} - found".format(filename)
            shutil.copyfile(os.path.join(source_folder, filename), os.path.join(destination_folder, filename))
        else:
            print "{} - not found".format(filename)

copy_files(source_folder, destination_folder, 'jpg')
copy_files(source_folder, destination_folder, 'pdf')

This assumes the same deneme.xls is used for both. If not it could be passed as another argument to the function.


text:
Q: Creating a table inside a table in sqlite 3 (python) I'm trying to create a sqlite database for a recipe storing program, that holds in the recipe table, the number of people, ingredients, cooking temperature and cooking time. I intend on creating another table inside the ingredients part, to store the 'id' (which will auto increment); the mass number (for example, 200); the mass type (for example, g) and the food type (for example, flour).
I'm using this code to try to get the variables and to store them:
    def setIngredientsInRecipe(recipeName):
        cursor.execute("""INSERT INTO %s(ingredients) CREATE TABLE\
                    (ID INT PRIMARY KEY AUTO_INCREMENT, MassNumber VARCHAR(10), MassType VARCHAR(50) FoodType VARCHAR(50))""" % (recipeName))
        print ""
        massNoInput = raw_input("Please enter your first ingredient mass(just the number): ")
        massTypeInput = raw_input("Now please input the mass type (grams etc): ")
        foodInput = raw_input("Please enter your first ingredient type: ")

        cursor.execute("""INSERT INTO %s(ingredients(MassNumber)) VALUES('%s')""" % (recipeName,massNoInput))
        cursor.execute("""INSERT INTO %s(ingredients(MassType)) VALUES('%s')""" % (recipeName,massTypeInput))
        cursor.execute("""INSERT INTO %s(ingredients(FoodType)) VALUES('%s')""" % (recipeName,foodInput))

        return recipeName

Obviously I'm going to add some number checks in later, to see if the input is valid first.
It's crashing out on the first cursor.execute line, saying that it's a syntax error...
If anyone could explain to my how to fix this, I'd be most grateful, I've been looking at this bit of code for ages!
Thanks,
Ryan :)

A: Use two tables, one for recipes, and one for ingredients, and have for each ingredient record the ID of the recipe it belongs to:
CREATE TABLE recipe(ID, People, CookingTime);
CREATE TABLE ingredient(ID, RecipeID, MassNumber, MassType, FoodType);

To add one ingredient to a recipe, just insert one record into that table
(here, 42 is the ID of the recipe):
INSERT INTO ingredient(RecipeID, MassNumber, MassType, FoodType) VALUES (42, ...)


text:
Q: Saving data and displaying it in a form Rails 4 I have created a call report form with my contact's first name & contact's last name in my scaffold. Although I can clearly see the fields in the form and I can go ahead and edit them, the fields of contact_first_name & contact_last_name are always empty after being saved and returning to my view. I don't know what to do or how to approach this issue.
Any suggestions would be greatly appreciated.

A: There could be many problems:

*

*contact_first_name or contact_last_name could be misspelled.

*in controller they may not be permitted

*you might be overriding these fields somewhere

*etc etc

Possible solutions or the directions to the solution are:

*

*check database for their existence

*check spells

*check them in permit list

*check the logs

But Code would be helping for both you and answering persons. So please post code with your question.


text:
Q: How to crawl a website after login in it with username and password I have written a webcrawler that crawls a website with keyward but i want to login to my specified website and filter information by keyword.How to achive that. i posting my code so far i have done .
public class DB {

public Connection conn = null;

public DB() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test";
        conn = DriverManager.getConnection(url, "root","root");
        System.out.println("conn built");
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

public ResultSet runSql(String sql) throws SQLException {
    Statement sta = conn.createStatement();
    return sta.executeQuery(sql);
}

public boolean runSql2(String sql) throws SQLException {
    Statement sta = conn.createStatement();
    return sta.execute(sql);
}

@Override
protected void finalize() throws Throwable {
    if (conn != null || !conn.isClosed()) {
        conn.close();
    }
}
}

public class Main {
public static DB db = new DB();

public static void main(String[] args) throws SQLException, IOException {
    db.runSql2("TRUNCATE Record;");
    processPage("http://m.naukri.com/login");
}

public static void processPage(String URL) throws SQLException, IOException{
    //check if the given URL is already in database;
    String sql = "select * from Record where URL = '"+URL+"'";
    ResultSet rs = db.runSql(sql);
    if(rs.next()){

    }else{
        //store the URL to database to avoid parsing again
        sql = "INSERT INTO  `test`.`Record` " + "(`URL`) VALUES " + "(?);";
        PreparedStatement stmt = db.conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, URL);
        stmt.execute();

        //get useful information
        Connection.Response res = Jsoup.connect("http://www.naukri.com/").data("username","jeet.chatterjee.88@gmail.com","password","Letmein321")
                 .method(Method.POST)
                    .execute();
        //http://m.naukri.com/login
        Map<String, String> loginCookies = res.cookies();
        Document doc = Jsoup.connect("http://m.naukri.com/login")
                  .cookies(loginCookies)
                  .get();

        if(doc.text().contains("")){
            System.out.println(URL);
        }

        //get all links and recursively call the processPage method
        Elements questions = doc.select("a[href]");
        for(Element link: questions){
            if(link.attr("abs:href").contains("naukri.com"))
                processPage(link.attr("abs:href"));
        }
    }
}
}

And the table structure also
 CREATE TABLE IF NOT EXISTS `Record` (
 `RecordID` INT(11) NOT NULL AUTO_INCREMENT,
 `URL` text NOT NULL,
  PRIMARY KEY (`RecordID`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Now i want to use my username and password for that crawling so that crawler can log in to the site dynamically and crawl infomation on the basis of keyword..
Lets say my username is lucifer & password is lucifer123

A: your approach is for stateless web access, which usually works for web services. sites are stateful. you authenticate once and after that, they use the session key stored in your cookie to authenticate you ( other means of authentication is also possible), so it is required. you must send parameters that your browser is sending. try monitoring what your browser send to site with firebug, and reproduce that in your code
--update--
Jsoup.connect("url")
  .cookie("cookie-name", "cookie-value")
  .header("header-name", "header-value")
  .data("data-name","data-value");

u can add multi cookie | header | data. and there is function for adding values from Map.
to find out what must be set, add fire bug to your browser, they all have their default developer console which can be started with F12. go to the url u want to get data and just add all thing in there to your jsoup request.
i added some images from your site result

i marked important part in red.
u can get required cookies in your code with sending these info to site and get cookie from that and after getting response.cookies you attach these cookies to every request u make ;)
p.s: change your password A.S.A.P


text:
Q: "Ghost" ng-click function Just when I thought I knew Angular pretty decently, I run into this situation:
Can someone explain how this is possible?
DEMO: http://jsfiddle.net/u08jgd4g/1/
HTML

  <button ng-click="WTF" ng-bind="labelText()"></button>

    Hello, World!

JS
var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {

    var show = true;

    $scope.labelText = function() {
        return !show ? 'Hide' : 'Show';
    };

    $scope.showMe = function() {
        show = !show;
        return show;
    };

};

If you haven't caught the issue yet: the button has an ng-click function that doesn't exist, yet when you click on the button, the div toggles and the button value changes.

A: It's not because the function doesn't exist, it's because that click is triggering a $digest cycle. So the cycle runs and evaluates your ngShow and ngBind functions.
Those 2 functions simply flip a variable to the opposite of what it was and apply the result. So all that's happening is you trigger a digest cycle and trip your functions that are bound in the view.

A: This is happening because you have used ng-click function, which runs a digest cycle after evaluation of expression given on ng-click directive. Resultant all the watcher function gets evaluated which why your value is getting toggle on each click.
Behind the scene when you use ng-show directive with an expression, angular internally puts that expression inside the watcher array which there under $scope object. You can see the collection of watcher's object inside the $scope.$$watchers object.


text:
Q: ValueError: could not convert string to float: '59:46.5' while reading timstamp I have timestamp in my data of this format 59:46.5
My data looks like this

I am applying clustering techniques to detect outliers but I got errors
File "pandas_libs\lib.pyx", line 615, in pandas._libs.lib.astype_intsafe
ValueError: invalid literal for int() with base 10: '59:46.5'
import pandas as pd# visualization
import matplotlib.pyplot as plt# algorithm
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler
import numpy as np

df = pd.read_csv("D:/user/Iotdata/data.csv")


text:
Q: python not finding _ldap What I'm looking to do is install and use python on a python install that isn't the system default.
It's a 64-bit Python.NET install, version 2.7.11.
I've installed pip, and the latest 64-bit wheel for python-ldap. I could not use the version available on PyPl as it is only 32-bit.
To test if I can import ldap I run:
    dpython.exe -c "import ldap"
Which returns:
File "<string>", line 1, in <module>
    File "C:\Program Files\Thinkbox\Deadline8\bin\lib\site-packages\ldap\__init__.py", line 22, in <module>
    import _ldap
ImportError: DLL load failed: The specified module could not be found.

Checking pip for what I thinks is installed:
pip list

Returns:
pip (8.1.2)
python-ldap (2.4.25)
setuptools (24.3.0)
wheel (0.29.0)

What's really strange is that I've successfully installed and used this exact same wheel on my system's python install (the one located in C:\Python27).
What am I missing to get python to find this module?


text:
Q: Set up project files I've done a bit of research just recently and am learning the command line, which has included node and bowser. From the information I've gathered so far, I think you can set up project files. Or maybe I'm wrong. I always set up the same folder/file structure for a project, e.g.:
index.html
/js
    jquery.latestversion.js
    custom.js
/images
/css
    styles.css
    bootstrap.css

Now this is where I'm not too sure. I want a way to set up this folder structure, create the files (with predefined snippets inside some) and also download the latest versions of jquery and bootstrap (with specific options, normally only just the grid).
Are there any specific programs/scripts I should be using to do this?

A: Yeoman is what you are looking for. It allows you to create generators to initialize your projects structure. You can develop your own generator to fit your directories structure.
Check it out : http://yeoman.io/


text:
Q: Perform a dynamic button click when the button ids found on the form I create a button dynamically on the form for each product like this:
Button btnStore = new Button();
btnStore.Text = "Store";
btnStore.Height = 30;
btnStore.Width = 80;
btnStore.Name = "btnStoreCV" + name + row[7].ToString();
btnStore.Location = new Point(ptX + 750, ptY);
btnStore.Click +=btnStore_Click;
btnStore.Visible = false;
pt.Controls.Add(btnStore);

Then on another button click i search the form for all the product buttons and if it finds it, I want it to perform the click event of that button.
This is what i have so far but its not working:
private void btnSaveCounts_Click(object sender, EventArgs e)
{
    foreach (Panel p in pnls)
    {
       IEnumerable<Button> Buttons = p.Controls.OfType<Button>();
       foreach (Button Button in Buttons)
       {
            if(Button.Name.Contains("CV"))
            {
               MessageBox.Show("YES");
            }
       }
    }
}

I have tried this aswell:
private void btnSaveCounts_Click(object sender, EventArgs e)
{
    foreach (Panel p in pnls)
    {
         IEnumerable<Button> Buttons = p.Controls.OfType<Button>();
         foreach (Button Button in Buttons)
         {
             if(Button.Name.Contains("CV"))
             {
                Button.Click += Button_Click;
                Button.PerformClick();
                //MessageBox.Show("YES");
             }
         }
    }
}

void Button_Click(object sender, EventArgs e)
{
   StoreNumbers(0, sender);
}

Is there a way to perform the button's click event.


text:
Q: Node on Linux thinks its out of date I have a couple of Discord bots running on a VPS (Ubuntu) and I am using Docker to deploy them into containers. Both of these bots are running fine, so I am trying to launch a third one for something else. I have set it up the exact same way, however when I try and run the container, the bot logs into Discord, but then this error pops up and the app stops.
Your node version is currently 12.20.0
Please update it to a version >= 14.x.x from https://nodejs.org/

My other apps are running fine on version 12.20.0 so I am not sure what the issue is. If I have to update I will, but I don't know how to update Node on Linux.
This is the contents of my Dockerfile:
FROM node:12.20.0

# Create the directory!
RUN mkdir -p /usr/src/bot
WORKDIR /usr/src/bot

# Copy and Install our bot
COPY package.json /usr/src/bot
RUN npm install

# Our precious bot
COPY . /usr/src/bot

# Start me!
CMD ["node", "index.js"]


text:
Q: how to save value from HTML id for comparing in for loop I want to compare two values in a for loop, already tried using #tmpid.val ,not working.
<template name="productpendingstatus">

       {{#each totaltemplate}}

{{this.META.TEMPLATE_NAME}}

{{this._id}}	 <want to compare this value in code below>

                {{#each productt}}
                {{#if $eq <value of id tmpid> this.TemplateID.value }}//this is ques

                  <input type="checkbox">
                  {{this.ProductId.value}}

                {{/if}}
                {{/each}}

       {{/each}}

    </template>

A: To reference a parent data context in a template, Spacebars now provide the "../" notation:
<template name="productpendingstatus">
       {{#each totaltemplate}}

{{this.META.TEMPLATE_NAME}}
{{this._id}}	 <want to compare this value in code below>

                {{#each productt}}
                {{#if $eq ../_id this.TemplateID.value }}

                  <input type="checkbox">
                  {{this.ProductId.value}}

                {{/if}}
                {{/each}}

       {{/each}}
    </template>

A: You can use a helper to get the parent data
<template name="productpendingstatus">
{{#each totaltemplate}}

{{this.META.TEMPLATE_NAME}}
    {{this._id}}

      {{#each productt}}
      {{#if isPending }}

        <input type="checkbox">
        {{this.ProductId.value}}

      {{/if}}
      {{/each}}

{{/each}}

and then on js file
 Template.productpendingstatus.helpers({
  isPending: function(){
    var parentData = Template.parentData();
    return parentData._id === this.TemplateID.value;
  }
});


text:
Q: EE Failed to activate virtual core keyboard: 2(EE) I upgraded my Manjaro Linux using command
   sudo pacman -Syu

then when I rebooteEE Failed to activate virtual core keyboard: 2(EE)d a day later, I got blank screen with blinking cursor and also sometimes
[drm:drm_atomic_helper_commit_cleanup_done [drm_kms_helper] *ERROR* [CRTC:26:pipe A] flip done timed out

I am able to access the terminal using Alt-Ctrl-F2
On checking journalctl, I am getting this error:-
https://i.stack.imgur.com/Zdrbh.jpg
I googled a lot. I checked my space. it has 46% free using df command and I have set /tmp to 777 acc to one of questions blog, still error persists these seems to be unrelated. What shall I do?


text:
Q: How to get notified when a user cancelled a sharing activity? I am developing an app that allows the user to start an activity that shares some sound file. I want to know if the user canceled sharing of sounds.
My Code:
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(Utils.createFile(Utils.getRingtone_name()[1], "share")));
                sendIntent.setType("audio/*");
                startActivity(sendIntent);

I want to do some action if the user cancelled sharing. How can I achieve this?

A:
I am developing an app that in it user share some sound file

You have not described how you are doing this. For this answer, I am going to guess that you are referring to ACTION_SEND or ACTION_SENDTO, as those are the typical Intent actions used for "share" sorts of operations.
If this guess is incorrect, please edit your question to provide the actual Java code that you are using to "share some sound file".

i want to know when user cancel sharing of sounds

There is no way for you to know what the user did, or did not do, with the content that you share via ACTION_SEND or ACTION_SENDTO.
If you are implementing your own ContentProvider for serving the sound file, you can know whether another app has requested that content. However, that still does not imply that the user actually completed some action with that content. For example, if the other app is an email client, it might have read the content to create an email attachment for its compose window, but then the user elected not to send the email.

User can cancel this by pressing back button

Pressing the BACK button does not necessarily imply that the user did not share the content.

Based on your comments, I think you are asking a different question: how do you know if the user chose something from the activity chooser that may appear when you try to share something?
On Android 5.1 and higher, you can use the three-parameter createChooser() method to arrange to find out what the user chose through the standard system chooser dialog. Prior to that, the only way that I know of to know what the user chose is to not use the system chooser dialog, but to handle that yourself. You can create your own "chooser", to choose among the available options given to you by queryIntentActivities() on PackageManager.

A: There is no way for you to know whether the sharing intent was successful or not OR user really shared it or discarded. Does not matter what you share - text, image, sound or video etc.
I think you are asking exactly this - Successful share intent for android.


text:
Q: js to update dynamic table field with attributes in select options I have a dynamic table where the select option has multiple attributes. What i want to do is to get these multiple attributes populated to adjusent cells in the same row next to the select element.The select element is in the first cell in the dynamic row.

<!DOCTYPE html>

            <select name="savings_account_number[]" id="savings_account_number" class="form-control">
                <option value="610005" pro_id="6" available_bal="4500" cap_gl="10101" account_number="610005">610005</option>
                <option value="510006" pro_id="5" available_bal="8900" cap_gl="10102" account_number="510006">510006</option>
            </select>

            <input name="pro_id[]" id="pro_id"/>

            <input name="available_bal[]" id="pro_id"/>

            <input name="cap_gl[]" id="cap_gl"/>

            <input name="account_number[]" id="account_number"/>

I want this to happen for the onchange activity

A: If correctly understood, this is a possible solution using jQuery:

        <select name="savings_account_number[]" class="form-control">
        <option value="610005" pro_id="6" available_bal="4500" cap_gl="10101" account_number="610005">610005</option>
        <option value="510006" pro_id="5" available_bal="8900" cap_gl="10102" account_number="510006">510006</option>
        </select>

        <input name="pro_id[]" id="pro_id"/>

        <input name="available_bal[]" id="available_bal"/>

        <input name="cap_gl[]" id="cap_gl"/>

        <input name="account_number[]" id="account_number"/>

        <select name="savings_account_number[]" class="form-control">
        <option value="1245" pro_id="5" available_bal="454" cap_gl="3659" account_number="65987">1245</option>
        <option value="6598" pro_id="43" available_bal="3215" cap_gl="64545" account_number="645444">6598</option>
        </select>

        <input name="pro_id[]" id="pro_id"/>

        <input name="available_bal[]" id="available_bal"/>

        <input name="cap_gl[]" id="cap_gl"/>

        <input name="account_number[]" id="account_number"/>

Note that I've corrected the second input's id, which had the same identifier as the first one.
Also, the select change eventhandler is raised explicetly to load the current value on load.


text:
Q: How to send a hashed password to DRF and get authenticated I'm working on authenticating users in Django, and I know that Django keeps all the passwords hashed in the data base,
so in order to secure the user credentials, I have to hash the password in my front end (Angular2) before sending it to my back end (Django rest framework).
The problem is that I don't know if Django excepts hashed passwords or is he capable of comparing it to the existing one, and if so , can any one pin point me to the right way.
any help is appreciated, thanks

A: You do not need to hash the password in Angular. Django will not understand a password hashed by Angular, since Django hashes passwords in a different way and has no information indicating that what you are sending is a hash. Even if you were able to has them the same way, Django would hash it again, which would not work. That is,
H(password) != H(H(password))

For a single hash function, H.
Send the password as plain text to the server. Protect the password by transferring all data over TLS/SSL. Django will accept the plain text password, compare the hashes, and authenticate the user as normal.


text:
Q: NHibernate: how to do lookup a specific date in Nhibernate How I can lookup a specific date in Nhibernate?
I'm currently using this to lookup one day's order.
 ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(Order))
            .Add(Expression.Between("DateCreated", date.Date.AddDays(-1), date.Date.AddDays(1)))
            .AddOrder(NHibernate.Criterion.Order.Desc("OrderID"));

I tried the following code, but they did bring the data for me.
Expression.Eq("DateCreated", date)

Expression.Like("DateCreated", date)

Note:
The pass in date value will be like this 2010-04-03 00:00:00,
The actual date value in the database will be like this 2010-03-13 11:17:16.000
Can anyone let me know how to do this?
Many thanks.

A: Since your database field has date and time information, querying for a single date will have to use between or greater than / less than. It's not clear from your question which query isn't working, but the second example using Expression will not work because the time portion does not match the time portion of the database record.


text:
Q: Mock interface based on type object I want to mock some interfaces based on type object. I need this to call constructor via reflection. It will look like that:
        var type = typeof (T);
        var constructors = type.GetConstructors();
        var constructor = constructors.First();
        var parameters = constructor.GetParameters();
        var objects = new object[parameters.Count()];
        //TODO create mock parameters and add to aobject array
        constructor.Invoke(objects);

Is it possible to achieve sth like that? Does any mock framework give finctionality for this? Or maybe it can be done using BCL?

A: bump was partially right, but this what I want to get is a mock cretated via reflection and solution for this will look like that:
public static object DynamicMock(Type type)
{
   var mock = typeof(Mock<>).MakeGenericType(type).GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
   return mock.GetType().GetProperties().Single(f => f.Name == "Object" && f.PropertyType == type).GetValue(mock, new object[] {});
}


text:
Q: Getting value from selected multiple checkbox I have a form to selecting some items using GET method like:
<form action="room_selected.php" method="get" id="formget" name="formget">
<input type="checkbox" id="room_id[]" name="room_id[]" value="1">
<input type="text" id="room_price[]" name="room_price[]" value="150000">

<input type="checkbox" id="room_id[]" name="room_id[]" value="2">
<input type="text" id="room_price[]" name="room_price[]" value="250000">

<input type="checkbox" id="room_id[]" name="room_id[]" value="3">
<input type="text" id="room_price[]" name="room_price[]" value="350000">

If I select checkbox contain value 1 and value 3, in room_selected.php only appear room 1 and room 3 including price150000 and price 350000.
I try using for but not working, like :
<?php
for ($i=0;$i<count($_GET['room_idi']);$i++) {
echo $_GET['room_idi'][$i].$_GET['room_price'][$i];
}
?>

A: The problem here looks to be that because you are only selecting two checkboxes, your for loop will loop only twice. So the PHP page will see two checkbox values, and three text field values;
You could try something like this instead;
<form action="room_selected.php" method="get" id="formget" name="formget">
<input type="checkbox" id="room_id[]" name="room_id[]" value="1">
<input type="text" id="room_price[]" name="room_price_1" value="150000">

<input type="checkbox" id="room_id[]" name="room_id[]" value="2">
<input type="text" id="room_price[]" name="room_price_2" value="250000">

<input type="checkbox" id="room_id[]" name="room_id[]" value="3">
<input type="text" id="room_price[]" name="room_price_2" value="350000">

<?php

if (count($_GET['room_id']) > 0) {
    foreach ($_GET['room_id'] as $roomId) {
        $textFieldName = "room_price_" + $roomId;

        echo $roomId . ' = ' . $_GET[$textFieldName];
    }
}

?>


text:
Q: Register Ranges in HLSL? I am currently refactoring a large chunk of old code and have finally dove into the HLSL section where my knowledge is minimal due to being out of practice. I've come across some documentation online that specifies which registers are to be used for which purposes:

*

*t – for shader resource views (SRV)

*s – for samplers

*u – for unordered access views (UAV)

*b – for constant buffer views (CBV)

This part is pretty self explanatory. If I want to create a constant buffer, I can just declare as:
cbuffer LightBuffer: register(b0) { };
cbuffer CameraBuffer: register(b1) { };
cbuffer MaterialBuffer: register(b2) { };
cbuffer ViewBuffer: register(b3) { };

However, originating from the world of MIPS Assembly I can't help but wonder if there are finite and restricted ranges on these. For example, temporary registers are restricted to a range of t0 - t7 in MIPS Assembly. In the case of HLSL I haven't been able to find any documentation surrounding this topic as everything seems to point to assembly languages and microprocessors (such as the 8051 if you'd like a random topic to read up on).

Is there a set range for the four register types in HLSL or do I just continue as much as needed in a sequential fashion and let the underlying assembly handle the messy details?

Note
I have answered this question partially, as I am unable to find a range for u currently; however, if someone has a better, more detailed answer than what I've given through testing, then feel free to post it and I will mark that as the correct answer. I will leave this question open until December 1st, 2018 to give others a chance to give a better answer for future readers.

A: Resource slot count (for d3d11, indeed d3d12 case expands that) are specified in Resource Limit msdn page.
The ones which are of interest for you here are :

*

*D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT (which is t) = 128

*D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT (which is s) = 16

*D3D11_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT (which is b) = 15 but one is reserved to eventually store some constant data from shaders (if you have a static const large array for example)

The u case is different, as it depends on Feature Level (and tbh is a vendor/os version mess) :

*

*D3D11_FEATURE_LEVEL_11_1 or greater, this is 64 slots

*D3D11_FEATURE_LEVEL_11 : It will always be 8 (but some cards/driver eventually support 64, you need at least windows 8 for it (It might also be available in windows 7 with some platform update too). I do not recall a way to test if 64 is supported (many nvidia in their 700 range do for example).

*D3D11_FEATURE_LEVEL_10_1 : either 0 or 1, there's a way to check is compute is supported

You need to perform a feature check:
D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS checkData;

d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &checkData);

BOOL computeSupport = checkData.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x

Please note that for some OS/Driver version I had this flag returning TRUE while not supported (Intel was doing that on win7/8), so in that case the only valid solution was to try to either create a small Raw / Byte Address buffer or a Structured Buffer and check the HRESULT
As a side note feature feature level 10 or below are for for quite old configurations nowadays, so except for rare scenarios you can probably safely ignore it (I just leave it for information purpose).

A: Since it's usually a long wait time for these types of questions I tested the b register by attempting to create a cbuffer in register b51. This failed as I expected and luckily SharpDX spit out an exception that stated it has a maximum of 14. So for the sake of future readers I am testing all four register types and posting back the ranges I find successful.

*

*b has a range of b0 - b13.

*s has a range of s0 - s15.

*t has a range of t0 - t127.

*u has a range of .

At the current moment, I am unable to find a range for the u register as I have no examples of it in my code, and haven't actually ever used it. If someone comes along that does have an example usage then feel free to test it and update this post for future readers.

I did find a contradiction to my findings above in the documentation linked in my question; they have an example using a t register above the noted range in this answer:
Texture2D                     a[10000] : register(t0);
Texture2D                     b[10000] : register(t10000);
ConstantBuffer<myConstants>   c[10000] : register(b0);

Note
I would like to point out that I am using the SharpDX version of the HLSL compiler and so I am unsure if these ranges vary from compiler to compiler; I heavily doubt that they do, but you can never be too sure until you try to exceed them. GLSL may be the same due to being similar to HLSL, but it could also be very different.


text:
Q: How do I execute oracle query using shell scripting and send the results in the email I am new to Unix scripting. I have an oracle DB which has a username, password, hostname, port and servicename. I want to connect the database and run the query and in the end the result should be email to me or other people. Result should be displayed in the body of an email.

A: This is a sample shell script to connect through SQL*Plus, SPOOL the output and send it as email in the message body.
#!/bin/sh -- or bash or ksh

sqlplus -s /nolog <<EOF
CONNECT username/password@sid
SPOOL /u01/spool.csv
--do something
SPOOL OFF
EXIT;
EOF

mail -s "Subject" email@address.com < /u01/spool.csv

A: PFB functionality breakup to connect oracle, email query result(as body) using shell Script with example :

*

*Connect to Oracle Database

*Set Headers for formatted output

*Run sql query and store result to temp file(query_output.dat)

http://www.folkstalk.com/2012/06/connect-to-oracle-database-in-unix.html

*

*Send output as body. Ex
mailx -s "subject" mail_address <query_output.dat
rm query_output.dat


text:
Q: Strategy for managing multiple Bibtex files My work involves producing various documents with citations (e.g., journal articles, conference presentations, reports, etc.).
Publications cite references, and references can be specific to a given publication, or to a set of publications built around a study, or a set of studies, or a research program. A reference may even cross-over into multiple research programs.
I'm a big fan of the DRY Principle (i.e., Don't Repeat Yourself).
However, I'm also a big fan of making projects portable.
Satisfying both principles seemingly leads to a conflict in relation to bibtex files.

*

*Is it a good strategy to have a single master bibtex file for all projects and adopt some automated copying system whereby each publication gets a copy of the overall bibtex file (or a subset)?

*Or is it better just to have lots of little publication specific bibtex files?

*Or is there some other system that people find works best?

*What tools can assist?

A: I have one master BibTeX file, which is versioned by itself in a Git repository. When writing a paper (each is also versioned as a separate Git repository), I include the master .bib file as a Git submodule. It puts the master .bib file as a subdirectory of my paper 'project'.
This way I have one copy of my bibliography, and my projects are portable as requested in the question.
Furthermore, Git submodule points to a specific version of the master BibTeX file. Therefore my paper always uses the original .bib file state, even if I have updated it in the master repository since (e.g. even changed reference keys). Similarly I could have paper-specific changes to the master file via branching.
The approach would also work with multiple authors/bibliographies - just include multiple submodules.
This is the general idea. To spare an overlong answer here, my blog has more details of the solution with sample repository structure to illustrate.

A: Nbibtex.  See my answer to the how to avoid bibtex error message "repeated entry" for an entry appearing in several bibtex files? question.

A: I use Mendeley to store and organize my articles, then use separate internal libraries for each project.  Each library can then be exported to a bibtex file.  It also has the added benefit of a shortcut (CTRL-K to get a latex entry copied to the clipboard).

A: I just keep everything in one big BibTeX database and use the search function in JabRef.
If I really need to give away a subset of the references to a co-worker (and don't want to send the whole file), I generate a new, smaller .bib-File using the "New subdatabase based on AUX file" from the Tools menu in JabRef.
But ultimately, you'll just adopt a system that works best for you. Mendeley has been suggested, I've also heard good things about CiteUlike.

A: While JabRef allows for exporting references from a bib file based on an aux file, I like to have an automated build based on a makefile.
Following on from Habi's response, I did a little Googling and found bibexport.
It seems well suited to maintaining a centralised bib file, and automating the extraction of references based on citations in a document.

*

*http://www.ctan.org/tex-archive/biblio/bibtex/utils/bibexport/
Update:
I'm quickly discovering there are many tools for automating the above process.

*

*http://ctan.org/pkg/bibtools

*http://www.ctan.org/tex-archive/biblio/bibtex/utils/bibtool/

A:
Is it a good strategy to have a single master bibtex file for all projects and adopt some automated copying system whereby each publication gets a copy of the overall bibtex file (or a subset)? Or is it better just to have lots of little publication specific bibtex files?

When I start a new draft, I use a script to create a template that includes all my bibtex files, to which I link using symmetric links. I can see the advantage of having one large bib file, but the downside for me is that I'll probably spend a lot of time looking for the right reference in that file, whereas small, topic-based files allow me to work quicker.

What tools can assist?

Mendeley not only allows you to organise, tag, ... your papers, but also to create collections and synchronize whole, exported .bib files with them. I believe this could be helpful to you.

A: I used to use a single master bibfile (using aux2bib from bibtools to make subsets if needed).  The trouble is that I now write papers together with other people, and we don't share a master bibfile (or even a common format for bibtex keys).
So I currently have lots of papers in different Subversion repositories, each with its own set of bibfiles.  One thing that helps is a script I wrote for grepping all the bibfiles and finding the distinct entries.  So when I need a new entry for a project, I can see if I already have it somewhere else.
This is certainly suboptimal.  Maybe Mendeley is the solution but I haven't tried it.

A: A reasonable approach would be to have some central database system and export work-specific .bib files for each article, report etc. Ideally, this system would allow to save work-specific literature selections (to be able to modify and re-export them easily when the tex document evolves).
Until now I did not find such a system.


text:
Q: Linting not working for Typescript 3.7 in tslint Angular 9 I upgraded to Angular version 9 which comes with Typescript 3.7. I use tslint and my linting isn't recognizing new features such as optional chaining or null coalescing. Do I need to switch to eslint, or is there a way to fix this?

A: As I see they fixed it into 6.0.0beta version lint. The official migration to ESlint will be in angular10 source


text:
Q: Reading gdb values correctly after mov Here are two lines of a binary I am debugging in gdb. This was C code compiled by gcc for an IA32:
8049345:    8b 45 08                mov    0x8(%ebp),%eax
8049348:    89 04 24                mov    %eax,(%esp)

I have a display $eax set up so it will show the value after each step. After the first line, the display says: 6: $eax = 134527652.
I can x 134527652 or x $eax and I see 0x804baa4 <input_strings+100>:    "1 1 1 1 1 1" Why do display and x give me different results?
The next line I believe says to move eax into the address stored by esp? I had a display $esp setup and it says: 2: $esp = (void *) 0xffffd540.
Before the second mov, I x 0xffffd540 and see: 0xffffd540:    "" after the mov I repeat and see:
0xffffd540:  "\244\272\004\bY\233\004\b\210\325\377\377\214\325\377\377\220\325\377\377\224\325\377\377\230\325\377\377\234\325\377\377\001"

I thought this line was going to mov eax into this address, but I am obviously not understanding something here? Let me know if you would like to see any other lines from the binary.

A: I think your confusion may be caused by the fact that the x command is printing the data at address 0xffffd540 as a string. Presumably before the store to that address, the first byte at 0xffffd540 is a 0 byte, treated as terminating a string, and thus you're seeing "", the empty string. After writing the value 0x804baa4 to this address, you're seeing its representation in bytes:
\244\272\004\b

where \244 (octal escape) is 0xa4, \272 is 0xba, \004 is 0x04, and \b (the escape for backspace character, U+0008) is 0x08.
You see more junk after it in the string printed because there doesn't happen to be a null terminator anymore.


text:
Q: Symfony2 and FOSRestBundle - Only Allow Users to Edit Data That They Own Symphony Version 2.2 (yah, I know).
FOSRestBundle: 1.5.3
Current Scenario
I have a REST Api driving an angular page.  Let's say that each user has a token associated w/ their user record.  Consider the following Urls.

*

*GET /api/user/{token}/messages

*POST /api/user/{token}/messages

*GET /api/messages/{messageId}

*GET /api/user/{token}/votes

*POST /api/user/{token}/votes

So the user can GET and POST messages.  The user can make votes and see them.
(I have about 30 diff routes like this - the URLs are all over the place).
Question
How can I verify that the user is allowed to GET/POST data for the token they're providing?
I do realize I could copy/paste some code to check the given user vs the user from the URL.  Or I could write a service w/ a checkUser() function on each endpoint.
My hope, though, is that there is some way of doing this that doesn't require me to check the user on each endpoint's entry point.

A: Don't send the authentication in the Endpoint.  An endpoint typically should be Idempotent, and should individually identify a particular resource.
Send your authentication tokens in HTTP headers.
With that said, as a strategy, baking in your security using @wonde is a good idea.  I have implemented a custom base controller class in the past, but the filter and event handling built into symphony provides an even sexier solution.

A: i would create a before filter and add the checkUser() hook in there , that way you don't have to check the user permission on each endpoint
example


text:
Q: How to remove scientific notation on a matplotlib log-log plot I know that this question has been asked before, but I tried all the possible solutions and none of them worked for me.
So, I have a log-log plot in matplotlib, and I would like to avoid scientific notation on the x-axis.
This is my code:
from numpy import array, log, pi
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import matplotlib.ticker as mticker

plt.rc('axes.formatter', useoffset=False)

tc = array([7499680.0, 12508380.0, 23858280.0, 34877020.0, 53970660.0, 89248580.0, 161032860.0, 326814160.0, 784460200.0])

theta = array([70, 60, 50, 45, 40, 35, 30, 25, 20])

plt.scatter(theta,tc)

ax=plt.gca()

ax.set_xscale('log')
ax.set_yscale('log')

ax.xaxis.set_major_formatter(mticker.ScalarFormatter())
ax.xaxis.get_major_formatter().set_scientific(False)
ax.xaxis.get_major_formatter().set_useOffset(False)

plt.show()

And this is the output:

As you can see, the numbers on the x-axis are still in scientific notation. I would like to display them as 20, 30, 40... I tried every possible solution with no result.
Thank you very much to everyone that will help.
NB. I can't use the plt.loglog() command, because I am doing some curve fitting on the data and I need it like that.
NB2. I noticed a very weird thing happening: if I change the code to yaxis.get_mayor_formatter()..., it works on the y-axis! It is just on the x one that it's not working. How is it possible?
Edit: maybe it is not clear, but if you look at the code, there are 3 methods that should affect the display of the x-ticks: plt.rc('axes.formatter', useoffset=False), ax.xaxis.set_major_formatter(mticker.ScalarFormatter()) and ax.xaxis.get_major_formatter().set_scientific(False). They are 3 methods that should all do the trick alone, according to what I found around, but they don't. Of course I also tried them one by one and not all together.

A: Those are minor ticks on the x-axis (i.e. they are not on integer powers of 10), not major ticks. matplotlib automatically detemines if it should label the major or minor ticks - in this case because you don't have any major ticks displayed in the x range, the minor ticks are being labelled). So, you need to use the set_minor_formatter method:
ax.xaxis.set_minor_formatter(mticker.ScalarFormatter())

The reason it works on the y-axis is because those ticks are major ticks (i.e. on integer powers of 10), not minor ticks.

A: The following can be used as a workaround (original answer):
from matplotlib.ticker import StrMethodFormatter, NullFormatter
ax.yaxis.set_major_formatter(StrMethodFormatter('{x:.0f}'))
ax.yaxis.set_minor_formatter(NullFormatter())

A: If you want to set just the xaxis to no longer use scientific notation you need to change the fromatter and then you can set it to plain.
ax.xaxis.set_minor_formatter(mticker.ScalarFormatter())
ax.ticklabel_format(style='plain', axis='x')

A: If you want to disable both the offset and scientific notaion, you'd use ax.ticklabel_format(useOffset=False, style='plain')


text:
Q: System.InvalidOperationException: ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'updateEmp' that has parameters: I am getting this error while try to update data from gridview:

System.InvalidOperationException: ObjectDataSource 'ObjectDataSource1'
  could not find a non-generic method 'updateEmp' that has parameters:
  id, name, u_name, pass, mail, address, city, dob, cnic, designation,
  ph_no, emp_name, emp_id.

Here is my Asp code for object data source
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="deleteEmp" SelectMethod="GetAllEmployees" TypeName="fmsWeb.datagridDemo" UpdateMethod="updateEmp" ConflictDetection="OverwriteChanges">
                <DeleteParameters>
                    <asp:Parameter Name="emp_id" Type="String" />
                </DeleteParameters>
                <UpdateParameters>
                    <asp:Parameter Name="id" Type="String" />
                    <asp:Parameter Name="name" Type="String" />
                    <asp:Parameter Name="u_name" Type="String" />
                    <asp:Parameter Name="pass" Type="String" />
                    <asp:Parameter Name="mail" Type="String" />
                    <asp:Parameter Name="address" Type="String" />
                    <asp:Parameter Name="city" Type="String" />
                    <asp:Parameter Name="dob" Type="String" />
                    <asp:Parameter Name="cnic" Type="String" />
                    <asp:Parameter Name="designation" Type="String" />
                    <asp:Parameter Name="ph_no" Type="String" />
                </UpdateParameters>
            </asp:ObjectDataSource>

And this is my class code where the method is defined
 public static List<Employees> GetAllEmployees()
 {
    List<Employees> listemp = new List<Employees>();

    using (MySqlConnection con = new MySqlConnection(@"server=127.0.0.1;user id=root;database=fms"))
    {
       MySqlCommand cmd = new MySqlCommand("Select * from emp", con);
       con.Open();
       MySqlDataReader dr = cmd.ExecuteReader();
       while (dr.Read())
       {
           Employees em = new Employees();
           em.emp_id = dr[0].ToString();
           em.emp_name = dr[1].ToString();
           em.u_name = dr[2].ToString();
           em.pass = dr[3].ToString();
           em.mail = dr[4].ToString();
           em.address = dr[5].ToString();
           em.city = dr[6].ToString();
           em.dob = dr[7].ToString();
           em.cnic = dr[8].ToString();
           em.designation = dr[9].ToString();
           em.ph_no = dr[10].ToString();
           listemp.Add(em);
       }

    }
    return listemp;
}

public static void deleteEmp(String emp_id)
{
   using (MySqlConnection con = new MySqlConnection(@"server=127.0.0.1;user id=root;database=fms"))
   {
                MySqlCommand cmd = new MySqlCommand("Delete from emp where emp_id=@empID", con);
                MySqlParameter param = new MySqlParameter("empID", emp_id);
                cmd.Parameters.Add(param);
                con.Open();
                cmd.ExecuteNonQuery();
   }
}

public static string updateEmp(String id, String name, String u_name, String pass, String mail, String address, String city, String dob, String cnic, String designation,String ph_no)
{
   using (MySqlConnection con = new MySqlConnection(@"server=127.0.0.1;user id=root;database=fms"))
   {
      MySqlCommand cmd = new MySqlCommand("UPDATE `emp` SET `emp_id`= @id,`emp_name`=@name,`u_name`=@u_name,`pass`=pass,`mail`=@mail,`address`=@address,`city`=@city,`dob`=@dob,`cnic`=@cnic,`designation`=@designation,`ph_no`=@ph_no WHERE emp_id=@id",con);
      MySqlParameter paramID = new MySqlParameter("@id", id);
      cmd.Parameters.Add(paramID);
      MySqlParameter pname = new MySqlParameter("@name", name);
      cmd.Parameters.Add(pname);
      MySqlParameter pu_name = new MySqlParameter("@u_name", u_name);
      cmd.Parameters.Add(pu_name);
      MySqlParameter p_pass = new MySqlParameter("@pass", pass);
      cmd.Parameters.Add(p_pass);
      MySqlParameter pmail = new MySqlParameter("@mail", mail);
      cmd.Parameters.Add(pmail);
      MySqlParameter add = new MySqlParameter("@address", address);
      cmd.Parameters.Add(add);
      MySqlParameter pcity = new MySqlParameter("@city", city);
      cmd.Parameters.Add(pcity);
      MySqlParameter pdob = new MySqlParameter("@dob", dob);
      cmd.Parameters.Add(pdob);
      MySqlParameter pcnic = new MySqlParameter("@cnic", cnic);
      cmd.Parameters.Add(pcnic);
      MySqlParameter desig = new MySqlParameter("@designation", designation);
      cmd.Parameters.Add(desig);
      MySqlParameter ph = new MySqlParameter("@ph_no", ph_no);
      cmd.Parameters.Add(ph);
      con.Open();
      int i=cmd.ExecuteNonQuery();
      return Convert.ToString(i);
   }
}

Select and delete method is working perfectly fine but on update I have error

A: Your Emloyee objcet doesn't have a id and name properties.
It has emp_id and emp_name.
Change the paramters to reflect that:
Instead of this:
<asp:Parameter Name="id" Type="String" />
<asp:Parameter Name="name" Type="String" />

Do this:
<asp:Parameter Name="emp_id" Type="String" />
<asp:Parameter Name="emp_name" Type="String" />

A: Change your query to:
"UPDATE emp SET emp_name=@name,u_name=@u_name,pass=@pass,mail=@mail,address=@address,city=@city,dob=@dob,cnic=@cnic,designation=@designation,ph_no=@ph_no WHERE emp_id=@id"

AS Your searching constraint is id, better avoid updating it in case it is somehow primary or unique key


text:
Q: D3.js Failed to load resource: the server responded with a status of 404 (Not Found) I'm trying a tutorial and the domain request isn't loading. The links are working okay, but I'm still getting a error. I'm working on a dashboard in D3.js. I appreciate your help!
d3.json("https://oec.world/attr/country/", function(country_error, countries) {
  if (country_error) return console.arn(country_error);
  countries.data.forEach(function(d) {
    country_attrs[d.id] = d;
  });
});

d3.json("https://oec.world/hs/export/2011/show/all/all/", function(error_2011, json_2011) {
  if (error_2011) return console.warn(error_2011);
  json_2011.data.forEach(function(d) {
    data[d.origin_id] = {
      "export_val_2011": d.export_val,
      "id": d.origin_id
    }
  });

  d3.json("https://oec.world/hs/export/2010/show/all/all/", function(error_2010, json_2010) {
    if (error_2010) return console.warn(error_2010);
    json_2010.data.forEach(function(d) {
      if(data[d.origin_id]) {
        data[d.origin_id]["export_val_2010"] = d.export_val
      }
    });


text:
Q: IBM MQ: DISPLAY CHANNEL command - syntax error I'm trying to Display IBM MQ channels using
https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_7.5.0/com.ibm.mq.ref.adm.doc/q086040_.htm
I defined a channel named MYMQ.SVRCONN, however, this gives me a syntax error:
runmqsc
DISPLAY CHANNEL MYMQ.SVRCONN
 5 : DISPLAY CHANNEL MYMQ.SVRCONN

AMQ8405: Syntax error detected at or near end of command segment below:-
DISPLAY CHANNEL
I get the same problem with:
DISPLAY CHANNEL *

Any suggestions why?
I'm struggling to understand this syntax:
>>-DISPLAY CHANNEL--(--generic-channel-name--)------------------>

so bonus points if you can explain how syntax works.

A: The ( and ) are part of the required syntax.
In the examples you give the commands should be:
DISPLAY CHANNEL(MYMQ.SVRCONN)

or
DISPLAY CHANNEL(*)

Most MQSC command have a similar syntax of:
<command> <object type>(<object name>) [optional parameters]

A few examples:

*

*DEFINE CHL(MYMQ.SVRCONN) CHLTYPE(SVRCONN) MCAUSER('xyzuser')

*ALTER CHL(MYMQ.SVRCONN) CHLTYPE(SVRCONN) DESCR('Test channel')

*DISPLAY CHL(MYMQ.SVRCONN) MCAUSER
The QMGR object is one of the exceptions where the object type does not need to be followed by a object name since when you run these commands you are connected to a specific queue manager:

*

*DIS QMGR CHLAUTH CONNAUTH

*ALTER QMGR CHLAUTH(ENABLED)
A few things to note:

*

*IBM MQ will always fold to UPPER case anything that is not surrounded in single quote ' characters.

*Some DISPLAY commands by default display only a subset of all parameters on an object.  You can use the special parameter ALL to have it display all of them or you can indicate specific parameters you would like to display.

*DISPLAY commands can also use a WHERE clause, for example: DIS CHL(*) WHERE(MCAUSER eq 'xyzuser') DESCR


text:
Q: ActionScript 3.0: How to get the use count of a library item in Animate? In an Animate project, I can see the use count of each item in the library. I open the library with Ctrl + L and I can see that some items are used 1 time, 19 times, or 0 times.
I want to use CS5 JavaScript to get the use count for each item.
There seems to be no way to just do this:
let count = fl.getDocumentDom().library.items[1].getData('useCount');

Or
let count = fl.getDocumentDom().library.items[1].useCount

I have attempted to make the item the selection of the document and then get how many items are selected, as in the code below, but an error shows up saying that the first argument in line 6 is invalid.
var doc = fl.getDocumentDOM();
var library = doc.library;
var item = library.items[1];
library.selectItem(item.name);
doc.selectNone();
doc.selection = [item]; // Error: selection: Argument number 1 is invalid.
fl.trace(doc.selection.length);

I have searched around on the internet and haven't yet found an answer to this exact question.
How do I do this?


text:
Q: Anyone used CSS blueprint with Sharepoint sites Anyone used the blueprint (http://www.blueprintcss.org/) with Office Sharepoint server publishing sites?
If yes, what do you think? Any catches or problems ? does it really save time and make it easy to make the site working fine cross browsers?

A: I used Blueprint CSS with SharePoint (MOSS) on a project last year.
I'm a UK-based contractor and this was for a 3 month project with 1 technical resource (me). The company involved (large UK company providing services to the banking industry) had an existing intranet installation and wanted to move to a MOSS publishing site based intranet.
The design was column based with a fixed width (960px) so I took a look at the CSS frameworks available at the time and Blueprint looked simple and flexible (design tool at http://kematzy.com/blueprint-generator/ to build a custom grid).
Blueprint itself worked well, and the problems I encountered using it would be pretty much the same as any MOSS project that involves large customisations to the master page / page layouts. I did end up writing my own reset CSS rather than use the default one as I didn't want to completely clobber the MOSS styles. Gotchas:

*

*SharePoint uses quirks mode (the html doesn't define a doctype) so adding a doctype means plenty of fiddling with the shipped CSS styles to get it all working.

*The control rendering is the normal asp.net mess of nested tables etc., which combined with the quirks mode meant that getting things to stay in the grid was always somewhat tricky.

*I only had to support IE (6 & 7) as it was an internal intranet, and even the inconsistencies in their rendering caused a few problems. Short of using control adapters to try and generate sane html, I think this would only get worse supporting other browsers as well.

Having said all that, it worked well with the master pages and was great with page layouts (different columns/layouts and having a 'magazine style' front page). And we got the project done with time to spare so yes, I'd use it again and recommend it - as long as you're happy to be knee-deep in CSS quite quickly..

A: Being an accessibility evangelist I also went down the same path of using Blueprint in an effort to make things more standards-compliant. TO be honest I would not do it again.
Trying to beat MOSS 2007 into submission and make it accessible is a lost cause. Even great projects like the AKS (Accessibility Kit for SharePoint) do little more than add a summary paramater to the swarm of nested tables rendered by woefully out-dated .NET controls.
Short of rewriting all these controls there's just no point. SharePoint publishing sites that don't use too many of these might be slightly easier to manage. But IMO you'd be better of waiting for 2010 which does a much better job of this.
If meeting WCAG is important now then you're far better off going with another CMS that does this out-of-the-box, or at least let's you do it without too much pain.


text:
Q: goto HTML document location dynamically My page adds # to the html programatically and have this in the  tag
function InsertTag(){
//Add  to the middle of this document
}

window.addEventListener('load', InsertTag, false);

my question is how can I make the document then jump to #spot?

A: Here's a suggestion: use id's instead. If you have:

Then page.html#something will take you straight to that div. It doesn't have to be a div, it can be used on any element. If you can manipulate the DOM to add that anchor, I am pretty sure you'll be able to do this.

Now... To get there, you can use:
// this approach should work with anchors too
window.location.hash = 'something';

// or scroll silently to position
var node = document.getElementById('something');
window.scroll(0, node.offsetTop);

See it in action here: http://ablazex.com/demos/jump.html
There are subtle differences between the methods. Eg: The first one will cause the location on the address bar to be updated, the second one won't.
If you want it to look nicer you can use a jQuery plugin, like ScrollTo.

A: Try
window.location = currentUrl+'#spot';
where currentUrl is a variable having the address of the current url

A: You can try this.
var el = document.getElementById('spot');
var eloffsetTop = el.offsetTop;
window.scroll(0,eloffsetTop);


text:
Q: c# delegate -> typescript c# code
enum myEnum
{
    aa = 0,
    bb,
    cc,
}

public delegate void MyDelegate(myEnum _myEnum, params object[] _params);

public Dectionary<myEnum , MyDelegate> dicMyDelegate = new Dectionary<myEnum , MyDelegate>();

public void GameDelegate(myEnum _myEnum, MyDelegate _Func)
{
    if(dicMyDelegate .ContainsKey(_myEnum))
    {
        MyDelegate Func;
        dicMyDelegate.TryGetValue(_myEnum, out Func);
        Func += _Func;
    }
    else
    {
        dicMyDelegate.Add(_myEnum, _Func);
    }
}

public void GameCallBack(myEnum _myEnum)
{
    if(!dicMyDelegate.ContainsKey(_myEnum)) return;
    MyDelegate Func;
    dicMyDelegate.TryGetValue(_myEnum, out Funk);
    if(Func == null) return;
    Func(_myEnum);
}

==================================================
cocos creator TypeScript. i don't know.... plz. i'm now study.
public delegate void MyDelegate(myEnum _myEnum, params object[] _params);

public Dectionary<myEnum , MyDelegate> dicMyDelegate = new Dectionary<myEnum , MyDelegate>();

It is difficult to replace the above code with a type script.
I am searching the internet all day.
declare module "Delegate"
{
    export function MyDelegate(_myEnum: myEnum , args: any[]) : void;
}

import {MyDelegate} from 'Delegate';

A: In JavaScript and TypeScript, functions are first class citizens, so you don't need to solve the problem in the same you do in C#.
function example(name: string) : string {
    return 'Hello ' + name;
}

function acceptsFunction(func: Function) {
    // Calling the function that was passed as an argument
    const result = func('Steve');
    console.log(result);
}

// Calling a function, passing another function as an argument
acceptsFunction(example);

In the example above, you can pass the function as an argument, and call it with arguments - all with no additional complication.
You can improve type safety by specifying what kind of function must be passed:
function acceptsFunction(func: (name: string) => string) {


text:
Q: jQuery select one value from a variable I am new to jQuery and i have a problem about getting the value that i need from a variable.
More specific I have this list on html file.

News & articles

 News

 Articles

Contact Us

Now i want to use the same function both to mainmenu and submenu.
$("#menu li").click(Menu_function);

My problem is that when i click on submenu, variable $(this) has two values. one for the li inside the submenu and one for the li of mainmenu.
now i would like to do something like this in my function:
var currentId = $(this).attr('id');

How could I get only one value?
Any help appreciated.

A: You'll want
$('#menu').click(function(evt) {
  var currentId = $(evt.target).closest('li').attr('id');
});

A: You can add the click function to both items using an "each" selector:
$('#menu li').each( function(index) {
    $(this).click( function() {
      var id = $(this).attr('id');

      // do whatever you need to here
    });
});

A: You may use each method of jquery to traverse all of them and add onclick on them.
something similar what dcp has mentioned in his answer:
$('#menu li').each( function() {
    // add click method on this element ($(this))
    $(this).click( function() {
    });
});


text:
Q: Check for matching values in columns- python/pandas I have a CSV file with Lat and long values of two models (Model 1 and Model 2) as shown below. I am trying to achieve following

*

*Search the first row Lat/ Long values of model 1 in every row of model 2 columns Lat/ Long values. If the Lat/ Long values of model 1 are found in model 2 then, print their respective area name such as 'Papa' in the new column. The process is repeated for the rest of the rows in model 1 and then will model 2.

*If the Lat/Long values of model 1 didn't match with model 2, then print NOT matched in the output.``

Minimal working example:
import pandas as pd

df3= pd.read_csv("compare.csv")
Output=df3.loc[:, df3.columns.isin(list('LatLong'))]

Searched for the existing answers (1), (2) but could not found the solution.
sample_data.csv
Model 1                         Model 2
Lat            Lon        Name        X        Y
-33.348652  138.751659  Kastan  -41.735983  145.532112
-41.735983  145.532112  Ldon    -37.222005  145.921452
-37.222005  145.921452  Papa    -33.348652  138.751659
-37.222005  145.921452  tine    -34.779284  138.522352
-37.222005  145.921452  Farm    -31.543177  118.4565685
-27.112811  150.904878  Loy     -38.2536    146.574569

A: One way using pandas.merge:
df["Output"] = df["Model 1"].merge(df["Model 2"],
                                   how="left",
                                   left_on=["Lat", "Lon"],
                                   right_on=["X", "Y"],
                                  )["Name"].fillna("NOT MATCHED")

Output:
     Model 1              Model 2                              Output
         Lat         Lon     Name          X           Y
0 -33.348652  138.751659  Bastyan -41.735983  145.532112         Papa
1 -41.735983  145.532112   Eildon -37.222005  145.921452      Bastyan
2 -37.222005  145.921452     Papa -33.348652  138.751659       Eildon
3 -37.222005  145.921452     Quar -34.779284  138.522352       Eildon
4 -37.222005  145.921452     Coll -31.543177  118.456569       Eildon
5 -27.112811  150.904878      Loy -38.253600  146.574569  NOT MATCHED

Sample data used:
from io import StringIO

data = """Model 1,Model 1,Model 2,Model 2,Model 2
Lat,Lon,Name,X,Y
-33.348652,138.751659,Bastyan,-41.735983,145.532112
-41.735983,145.532112,Eildon,-37.222005,145.921452
-37.222005,145.921452,Papa,-33.348652,138.751659
-37.222005,145.921452,Quar,-34.779284,138.522352
-37.222005,145.921452,Coll,-31.543177,118.4565685
-27.112811,150.904878,Loy,-38.2536,146.574569"""

df = pd.read_csv(StringIO(data), sep=",", header=[0,1])

A: Another way would be
#drop the multilevel columns and cross merge
 s=df.droplevel(level=0, axis=1).merge(df.droplevel(level=0, axis=1), how='cross', suffixes=('','_y'))

#filter the matches row_wise and rename columns
#s[((s['Y_y']==s['Lon'])|(s['X_y']==s['Lat']))].filter(regex='_y$', axis=1).rename(columns=lambda x: x.split('_')[0])
s[((s['Y_y']==s['Lon'])|(s['X_y']==s['Lat']))].filter(regex='_y$|Name', axis=1).rename(columns={'Name_y':'Output'}).rename(columns=lambda x: x.split('_')[0])

Outcome
      Name        Lat         Lon   Output          X           Y
2   Bastyan -37.222005  145.921452     Papa -33.348652  138.751659
6    Eildon -33.348652  138.751659  Bastyan -41.735983  145.532112
13     Papa -41.735983  145.532112   Eildon -37.222005  145.921452
19     Quar -41.735983  145.532112   Eildon -37.222005  145.921452
25     Coll -41.735983  145.532112   Eildon -37.222005  145.921452

A: Try this
import pandas as pd

df3 = pd.read_csv("compare.csv", header=[1])

df3['Output'] = df3[['Lat', 'Lon']].merge(df3[['Name', 'X','Y']],
                                          how="left",
                                          left_on=["Lat", "Lon"],
                                          right_on=["X", "Y"])["Name"].fillna("NOT MATCHED")

cols = pd.MultiIndex.from_product([["Model 1"], df3.columns[:2]])
cols = cols.append(pd.MultiIndex.from_product([["Model 2"], df3.columns[2:]]))

df3.columns = cols

print(df3)

Output
    Model 1                 Model 2
    Lat         Lon         Name    X           Y           Output
0   -33.348652  138.751659  Bastyan -41.735983  145.532112  Papa
1   -41.735983  145.532112  Eildon  -37.222005  145.921452  Bastyan
2   -37.222005  145.921452  Papa    -33.348652  138.751659  Eildon
3   -37.222005  145.921452  Quar    -34.779284  138.522352  Eildon
4   -37.222005  145.921452  Coll    -31.543177  118.456569  Eildon
5   -27.112811  150.904878  Loy     -38.253600  146.574569  NOT MATCHED


text:
Q: Moodle - Adding an element to the settings menu I'm trying to develop a plugin in Moodle. One of the requirements is to add an element to the Settings Menu, in which I was able to achieve with the help of this guide

https://docs.moodle.org/dev/Local_plugins#Adding_an_element_to_the_settings_menu

And this is my code in local/myplugin/lib.php
<?php

function local_myplugin_extends_settings_navigation($settingsnav, $context) {
        // question_extend_settings_navigation
    global $CFG, $PAGE;

    // Only add this settings item on non-site course pages.
    if (!$PAGE->course or $PAGE->course->id == 1) {
        return;
    }

    // Only let users with the appropriate capability see this settings item.
    /*if (!has_capability('moodle/backup:backupcourse', context_course::instance($PAGE->course->id))) {
        return;
    }*/

    if ($settingnode = $settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) {
        $strfoo = get_string('classrecord', 'local_myplugin');
        $url = new moodle_url('/course/classrecord.php', array('id' => $PAGE->course->id));
        $foonode = navigation_node::create(
            $strfoo,
            $url,
            navigation_node::NODETYPE_LEAF,
            'myplugin',
            'myplugin',
            new pix_icon('i/grades', $strfoo)
            );
        if ($PAGE->url->compare($url, URL_MATCH_BASE)) {
            $foonode->make_active();
        }

        $settingnode->add_node($foonode);

    }
}

?>

I allowed the students to see the element "Class Record" in the settings menu

My concern is that how can I hide/show Class Record I added?
Any ideas would be great!

A: If you want only certain users to see the link, then create an appropriate capability in local/myplugin/db/access.php, e.g. 'local/myplugin:viewclassrecord', defaulting to being assigned to the 'student' role. Then check for it in the function you have defined.
e.g.
if (!has_capability('local/myplugin:viewclassrecord', $context)) {
    return;
}