text:
Q: Multilang URL subdomains in codeigniter Currently i have multi-language setup on my system with no url change. so www.test.com can be English or Spanish or whatever. The user changes the language from the footer.
But  i am thinking maybe it is better to have separate sub-domains for each language like fr.test.com or fr.photos.test.com, etc. Then maybe even add localization like fr-fr.test.com or fr-fr.photos.test.com, etc.
1) Any benefit to add subdomains like above instead of doing what i am already doing?
2) If yes, then how to configure codeignitor to do it for language and localization?
Currently i have a language lookup table which the system uses to output to the user to change the language.

A: I think it's better not to make many subdomains (from SEO perspective every subdomain will be as different website) and use something like website.net/fr-fr/category/subcategory or something like Microsoft uses:

*

*In English:
http://support.microsoft.com/kb/324767/

*In German:
http://support.microsoft.com/kb/324767/de-DE


text:
Q: Boundary Fill Simulation (C++) I'm trying to simulate the Boundary Fill method with a matrix of integer, which in each position has a number from 0-255 that identifies the "pixel color" and I ask a position, a color to be changed an color to replace it.
The code I implemented works well for square matrices, but if it's not square I have two bugs:
1- if the number of lines is greater than the number of columns, the algorithm ignores the last line and does everything without change on this last line.
2 - if the number of columns is greater than the number of lines, I get a segmentation error around the firsts iterations.
I'd like to know from someone who could help, what I'm doing wrong. I tried to debug (with prints, if some one could show me a better way wolb be thankful). The logic seems right and this segmentation error is bizarre.
Here is the code of the function:
void BoundaryFill(int*** img, int x, int y, int newColor, int oldColor, int WIDTH, int HEIGTH){
 if(x >= 0 && x < WIDTH && y >= 0 && y < HEIGTH && (*img)[x][y] == oldColor && (*img)[x][y] != newColor){

     (*img)[x][y] = newColor; //set color before starting recursion
     BoundaryFill(img, x + 1, y, newColor, oldColor, WIDTH, HEIGHT);
     BoundaryFill(img, x - 1, y, newColor, oldColor, WIDTH, HEIGHT);
     BoundaryFill(img, x, y + 1, newColor, oldColor, WIDTH, HEIGHT);
     BoundaryFill(img, x, y - 1, newColor, oldColor, WIDTH, HEIGHT);
     BoundaryFill(img,x + 1, y + 1, newColor, oldColor,WIDTH,HEIGHT);
     BoundaryFill(img,x - 1, y - 1, newColor, oldColor,WIDTH,HEIGHT);
     BoundaryFill(img,x - 1, y + 1, newColor, oldColor,WIDTH,HEIGHT);
     BoundaryFill(img,x + 1, y - 1, newColor, oldColor,WIDTH,HEIGHT);
 } }

Here is main code:
int main(){
int x, y, new_color,old_color;

//Reads the size of the matrix
int HEIGHT; cin >> HEIGHT;
int WIDTH; cin >> WIDTH;

int** img = new int* [HEIGHT];
for (int i=0;i<HEIGHT;i++)
    img[i] = new int [WIDTH];

//Reads the matrix
for (int i=0;i<HEIGHT;i++){
    for (int j=0;j<WIDTH;j++){
        cin >> img[i][j];
    }
}

cin >> x >> y;
old_color = 1; //assuming the old color always gonna be 1
cin >> new_color;

BoundaryFill(&img,x,y,new_color,old_color ,WIDTH,HEIGHT);

//Shows the matrix
for (int i=0;i<HEIGHT;i++){
    for (int j=0;j<WIDTH;j++){
        cout << img[i][j] << " ";
    }
    cout << endl;
}

//Free the HEAP
for(int i = 0;i < WIDTH; i++)
    delete []img[i];
delete []img;}

Here is some of input files, with the matrices, that I used to test (couldn't place the numbers of the input on the matrix format, but what those numbers mean is: first 2 define the size of the matrix, number of lines and number of columns. Last three define the start position an the color that will replace. The rest is the input of values for the matrix):
More lines:

8 7 2 1 1 1 1 1 2 1 2 1 1 1 2 1 1 1 2 1 2 1 1 1 1 1 2 1 1 1 1 1 2 1 2
  1 1 1 2 1 1   1 2 1    2 1 1 1    1 1 2 2 2 1 1   1 2 2 2 1 5

More Columns:

7 8
  2 1 1 1 1 1 2 2
  1 2 1 1 1 2 1 1
  1 1 2 1 2 1 1 1
  1 1 1 2 1 1 1 1
  1 1 2 1 2 1 1 1
  1 2 1 1 1 2 1 1
  2 1 1 1 1 1 2 2
  2 1
  5

A: When you set up your arrays in main, the first subscript to img is the vertical (HEIGHT) one, and the second is the horizontal (WIDTH) one.  In BoundaryFill, you have this reversed where you use the horizontal index first and the vertical index second.
You should use (*img)[y][x] within BoundaryFill.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing Leaflet-Library in a OpenUI5-App so what am I trying to do?
I am creating an OpenUI5 webapp, the purpose of which is to route users in a given area.
For this I should use OpenStreetMap, and after a few minutes of research I came across the Leaflet-Library. So I want import the library and use it to show the given area.
My problem is that all the tutorials i came across so far just tell me how to do this with html, sadly I only have xml views.
Has anyone a tutorial for this rather specific scenario?

A: You can add the library you want to use in your Openui5 application's index.html file, inside head tag next to ui5 bootstraping, like this:
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/1.77.2/resources/sap-ui-core.js"
    data-sap-ui-theme="sap_fiori_3" data-sap-ui-resourceroots='{
            "project": "./"
        }' data-sap-ui-oninit="module:sap/ui/core/ComponentSupport" data-sap-ui-compatVersion="edge"
    data-sap-ui-async="true" data-sap-ui-frameOptions="trusted">
    </script>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin="" />
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
    integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
    crossorigin=""></script>

I don't know the library you want to use, but if you need to create any HTML elements you can use the sap.ui.core.HTML class.
This should work!


text:
Q: Scientific value of timing total lunar occultations Is there still scientific value in timing and reporting total lunar occultations? Why would I time total lunar occultations (grazing occultations are out of the question)?
When I reported observations to ILOC many years ago I never got any feedback. Is the situation better today? There are apparently new arrangements, but are they actually working, for example, how is feedback provided to observers?

A: I suspect they are no longer of much scientific value. They were originally used to refine the shape of the lunar limb, but we now have abundant data from various orbiters around the Moon. Attention has shifted to grazing occultations and occultations by asteroids, especially the latter. Apparently the International Lunar Occultation Centre (ILOC) has ceased operations and has been supplanted by the International Occultation Timing Association (IOTA).
I used to time lunar occultations back in the '50s and '60s, but nowadays I time asteroid occultations.
Source: http://lunar-occultations.com/iota/lunarreport.htm
http://www.lunar-occultations.com/iota/iotandx.htm

A: There is an upcoming lunar occultation of the Crab nebula, sometime in October I believe. This is still sufficiently interesting scientifically that they have extended the lifetime of the RXTE mission in order to observe this event. One reason is that high-energy X-rays are still not very easy to image, so occultations give relatively high precision astrometry information. I believe this was actually one of the ways they proved that Quasars must be extremely compact, and thus most likely black holes.


text:
Q: override dependency inversion laravel 5 i have RequestInterface.php like this :
    <?PHP
namespace App\Http\Requests;

interface RequestInterface {

}

and abstract class Request.php :
<?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest implements RequestInterface {

    //
}

and i have PagesRequest.php that extends from Request.php :
<?php namespace App\Http\Requests;

use App\Helpers\Helpers;

class PageRequest extends Request implements RequestInterface  {

In controller i have to inject PageRquest and override edit() method of CrudController class and check injection in another class like this :
PageController.php :
protected function update( $id, PageRequest $request){
    parent::update( $request, $id);
}

and file that i have to check injected class to have RequestInterface :
   protected function update($id, RequestInterface $request)
    {
}

But i have this error

Declaration of App\Http\Controllers\PagesController::update() should
  be compatible with
  App\Http\Controllers\MasterController\CrudController::update($id,
  App\Http\Requests\RequestInterface $request)

Parent class Request implements RequestInterface and PageRequest extended with Request so PageRequest have RequestInterface interface but i i get this error.

A: You have swapped the arguments of the update method. The method in the parent class expects the $request object in the second argument slot -  you pass it to the first when you call it from within the subclass.


text:
Q: TFS Automated Build Output Folder Permissions I have TFS 2010 automated builds setup and using a CopyDirectory activity to copy the latest build to our DEV site. This all works fine.
In our web app we use a App_Temp folder for user uploads/downloads. This folder needs write permissions on the web server for all users.
Is it possible to:
A) change permissions on the folder when it is copied, or
B) exclude this folder from being overwritten/deleted and recreated
I'm open to other solutions to this problem.
Thanks for your help.


text:
Q: .NET port of OGNL Library Does anyone know of a good .NET port of the OGNL library here?  It looks like I could use something like this and the only one I have found so far is on SourceForge here and hasn't been updated since 2005.

A: I've been looking for something like this as well. Unfortunately, there isn't anything I'm aware of that's feasible for use in a real project. Sorry!
One suggestion that might be of help is to e-mail the author directly. Oftentimes, they abandon the project because they've found that another existing project's work is more in line with what they were trying to accomplish.


text:
Q: Tratamiento de missings y maquetado final de r a excel Tengo un problema a la hora de tratar con los missings en R y luego sacar un fichero Excel sin los missings, aquí estan los datos que quiero manipular
col1=c("Sujeto1","Sujeto2","Sujeto3","Sujeto4","Sujeto5","Sujeto6")
col2=c("A",NA,NA,"G",NA,NA)
col3=c(NA,NA,NA,"K","H","Z")
col4=c(NA,"P",NA,NA,NA,"Q")
col5=c(NA,NA,NA,NA,NA,NA)
col6=c(NA,NA,NA,"B","C",NA)
col7=c("E",NA,NA,"D",NA,"Y")

data=data.frame(col1,col2,col3,col4,col5,col6,col7)

> data
 col1 col2 col3 col4 col5 col6 col7
1 Sujeto1    A <NA> <NA>   NA <NA>    E
2 Sujeto2 <NA> <NA>    P   NA <NA> <NA>
3 Sujeto3 <NA> <NA> <NA>   NA <NA> <NA>
4 Sujeto4    G    K <NA>   NA    B    D
5 Sujeto5 <NA>    H <NA>   NA    C <NA>
6 Sujeto6 <NA>    Z    Q   NA <NA>    Y

Y quiero que el output sea un Excel que quede así:

Como se puede apreciar no estan los missings y cada individuo tiene un numero diferente de columnas. Para hacer el output en Excel se tiene que utilizar el siguiente comando:
library(xlsx)
write.xlsx2(x=data,file="Data.xlsx",row.names = F)

Es la primera vez que pregunto por aquí, me he leído el manual y diría que no incumplo ningun requisito ya que en principio no parece que se necesite mucho código para hacer la transformación que pido y me parece suficientemente concreto lo que pido. De no ser así pido disculpas de antemano por las molestias ocasionadas y editaré lo que haga falta para que quede en un formato adecuado para este foro.
Muchas gracias por la ayuda, de verdad.

A: Por ser la primera vez que preguntas, dejame decirte que los has hecho más que bien. La pregunta es clara y concisa, agregas un ejemplo mínimo y reproducible,  una muestra de lo que estarías esperando, lo que estamos del otro lado no podemos pedir nada más. Ahora con respecto a tu consulta, lo que podrías hacer es un alineado de las columnas con valores hacia la izquierda haciendo que los NA se muevan a la derecha.
Partimos de tu data.frame original:
data

     col1 col2 col3 col4 col5 col6 col7
1 Sujeto1    A <NA> <NA>   NA <NA>    E
2 Sujeto2 <NA> <NA>    P   NA <NA> <NA>
3 Sujeto3 <NA> <NA> <NA>   NA <NA> <NA>
4 Sujeto4    G    K <NA>   NA    B    D
5 Sujeto5 <NA>    H <NA>   NA    C <NA>
6 Sujeto6 <NA>    Z    Q   NA <NA>    Y

Y haciendo uso de la funcionalidad base, podríamos hacer esto:
data[-1] <- t(apply(data[,-1],MARGIN=1,FUN=function(x) {c(x[!is.na(x)],x[is.na(x)])}))

El resultado:
data

     col1 col2 col3 col4 col5 col6 col7
1 Sujeto1    A    E <NA> <NA> <NA> <NA>
2 Sujeto2    P <NA> <NA> <NA> <NA> <NA>
3 Sujeto3 <NA> <NA> <NA> <NA> <NA> <NA>
4 Sujeto4    G    K    B    D <NA> <NA>
5 Sujeto5    H    C <NA> <NA> <NA> <NA>
6 Sujeto6    Z    Q    Y <NA> <NA> <NA>

Ahora simplemente salvar en el Excel tal como lo estabas haciendo.
Explicación:

*

*Con data[,-1] definimos que solo trabajaremos con todas las columnas menos la primera

*Con apply() y usando MARGIN=1 aplicamos sobre cada fila del data.farme anterior una función c(x[!is.na(x)],x[is.na(x)]) que devuelve un vector cuyos primeros valores son los que no son NA y luego los NA

*Como el resultado final se acomoda por columna hacemos un transpose con t() para respetar la orientación original

*Por último solo modificamos los valores requeridos aplicando el cambio solo a data[,-1]
Una forma un poco más compacta y que me gusta un poco más, podría ser:
data[-1] <- t(apply(data[,-1],MARGIN=1,FUN=function(x) {x[order(is.na(x))]}))

En este caso el truco es ordenar las celdas de cada fila en función a si es NA o no: x[order(is.na(x))]


text:
Q: permutation -number of numbers of four different digits formed from the digits of the number 12356 such that it is divisible by 4 The number of numbers of four different digits that can be formed from the digits of the number 12356 such that it is divisible by 4??

A: Hint: If a number ends in $12$, $32$, $52$, $16$, $36$, $56$, it is multiple of $4$. How many ways can you fill the other two digits?

A: The answer to this is quite simple. Adding to what @ajotatxe has written, any number is divisible by $4$, if the last $2$ digits are multiples of $4$. From the given list the following are possible in the last $2$ places: $12, 16,32, 36,52, 56$.
Hence $6$ ways.
Now, the remaining $2$ digits can be any of the $3$ digits from the list, as $2$ have been used up in the last $2$ places.
Therefore, the total number of ways is: $3 \times 2 \times 6 = 36$ total ways
Note: I have made the necessary edits to my answer. Apologies as I had mistaken the question... And a bunch of thanks to @Daniel Fischer


text:
Q: Hibernate not JPA compliant regarding @Access? According to my JPA 2.0 book (and online documentation), I should be able to mix field and property access within a single entity or entity hierarchy.  The annotation of @Access on the class specifies the default access.  When placed on a field or property getter @Access can specify that the default should be overridden for this field.
@Entity
@Access(AccessType.FIELD)
Class Foo {

  @Id
  int id;

  @Column(name = "myfield")
  String myField;

  @Column(name = "myProp")
  @Access(AccessType.PROPERTY)
  public int getMyProp () {
    return 3;
  }

  public void setMyProp (int p) {
    // do nothing
  }
}

This class should result in a table with three columns.  However it doesn't with Hibernate...the "myProp" column is missing from the table because apparently Hibernate takes its field vs property cue from the entity ID and runs with it...totally ignoring the JPA spec with regards to @Access.
Can anyone confirm this or did I make a stupid mistake somewhere?

A: I've seen similar (not the same but similar) issues like HHH-5004 so I wouldn't exclude that this might be a new one (the TCK doesn't seem exhaustive). But what version of Hibernate are you using? Did you try with the latest?

A: Based on the docs your code seems to be right. The @Access(AccessType.FIELD) annotation on top is unnecessary, because you annotated the field int id;
This tells hibernate to use field access. I tried a very similar example with annotations and xml config mixed. This leads to the same behaviour, so it's probably a bug in hibernate.
I tried with hibernate 3.5.3


text:
Q: Filling UIBezierPath results in pixelated image from image context I have implemented a very simple filled in circle using UIBezierPath, which I then convert to UIImage so that I can set that to a UITableViewCell's imageView. This works really well, but you can see the edges are pixelated on a Retina display. Why is that, what can be done to ensure it looks fantastic?
let colorSize = cell.frame.size.height - 20
let rect = CGRectMake(0, 0, colorSize, colorSize)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
UIBezierPath(roundedRect: rect, cornerRadius: (colorSize)/2).addClip()
CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor);
CGContextFillRect(context, rect)
var colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.imageView?.image = colorImage

A: Step 1.  Read the UIGraphicsBeginImageContext documentation:

This function is equivalent to calling the UIGraphicsBeginImageContextWithOptions function with the opaque parameter set to false and a scale factor of 1.0.

Step 2. Follow the link to the UIGraphicsBeginImageContextWithOptions documentation, which says:

scale   The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device's main screen.

Step 3. Try using UIGraphicsBeginImageContextWithOptions with a scale of 0.0:
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)

Step 4. Profit…?


text:
Q: Frequent json decoder error - decoder.py line 357, in raw_decode I dont know a bit of python and below script is output of 6 hour google research. My task is very simple. Wanted to created a text file with movie information pulled from OMDB. I dumped all movie names in a text file and ran following script. Each time I run following script I get only 15-20 movie info but afterwards I get decoder error. When I rerun by removing the movie names for which I already got the info I again get 10-15 movie info! I am not expert in Python but everything below looks fine so not sure why I am getting this.
import json
import requests
import sys
import time

if(len(sys.argv) != 2):
    print("Please provide the movie file name as input arg. Ex " + sys.argv[0] + " movie_names.txt")
    print("Please note that in movie file each movie name should be on a new line")
else:
    with open(sys.argv[1]) as f:
        for line in f:
            json_obj_movie_detail = requests.get ("http://www.omdbapi.com/?t=\"" + line.rstrip('\n') + "\"&apikey=$$$$$$$")
            j = json.loads( json_obj_movie_detail.content )
            if(j.get('Title')):
                print (j['Title']+ ";" , end='', flush=True)
            else:
                print (line.rstrip('\n') + ";" + "Could not find this movie!", end='', flush=True)

            if(j.get('Genre')):
                print (j['Genre']+ ";" , end='', flush=True)
            else:
                print ("null" + ";", end='', flush=True)

            if(j.get('Plot')):
                print (j['Plot']+ ";" , end='', flush=True)
            else:
                print ("null" + ";" , end='', flush=True)

            counter = 0

            if(j.get('Title')):
                for each_rating_source in j['Ratings']:
                    print (j['Ratings'][counter]['Source'] + ";", end='', flush=True)
                    print (j['Ratings'][counter]['Value'] + ";", end='', flush=True)
                    counter = counter + 1
            else:
                print ("null", end='', flush=True)

            print(" ")

    f.close()

would really appreciate help from Python / Json experts.
/********* Error *****/
Traceback (most recent call last):
  File "C:\Users\peacedove\movie_detail.py", line 13, in <module>
    j = json.loads( json_obj_movie_detail.content )
  File "C:\Users\peacedove\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\peacedove\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\peacedove\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)


text:
Q: Filter Django model with json values I have this function:
# create a function to upload an object one to one given a json
def upload_object_values(model, json_values, update_if_exists=True):
    if json_values:
        # the json values contain key value that match to the model
        # use a copy to avoid runtime error dictionary changing size
        for json_value in json_values.copy():
            # remove all ids in model copy
            if json_value[-3:] == '_id' or json_value == 'id':
                json_values.pop(json_value)

        # assign a value to each key which is a the field in the given model
        for key, value in json_values.items():
            setattr(model, key, value)

        # if the object is get or create, or an update if exists
        if update_if_exists:
            # if it exists
            if model.__class__.objects.seal().exists():
                # retrieve the existing object
                retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values
                # assign values into it
                retrieved_object = model
                # save
                retrieved_object.save()
                print(retrieved_object)
                print('existing, saved successfully')
            # if it does not exist
            else:
                # save
                model.save()
                print('does not exist, saved successfully')
        # else just save
        else:
            model.save()
            print('created successfully')

with sample json_values like:
{'notes': '', 'name': 'test issuer', 'phone': None}

I need to be able to filter using the json_values that I have, as shown in the line:
retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values

How may I able to assign these values inside the filter() in django?

A: To filter by JSONField in Django you should use __ (double).
YourObject.objects.filter(json_values__notes='')

YourObject.objects.filter(json_values__name='test issuer')

If you want to have deeper dict levels, the rule stays the same:
{'notes': {'casual': 'nice', 'pro': 'elegant'}, 'name': 'test issuer', 'phone': None}

YourObject.objects.filter(json_values__notes__pro='elegant')

A: I think I understand what you are trying to achieve. Try this:
retrieved_object = model.__class__.objects.seal().filter(**json_values).first()

if json_values = {'notes': '', 'name': 'test issuer', 'phone': None}, the above line is equivalent to:
retrieved_object = model.__class__.objects.seal().filter(notes='', name='test issuer', phone=None).first()


text:
Q: ClojureCLR coercion error I'm getting a compiler exception in the ClojureCLR REPL for basic coercion:
=> (class 12)
System.Int64

=> (class 12.34)
System.Double

=> (class (new System.Double 12))
CompilerException System.InvalidOperationException: No constructor in type: Double with 1 arguments
at clojure.lang.CljCompiler.Ast.NewExpr.ComputeCtor() in D:\work\clojure-clr-1.4.1-fix\Clojure\Clojure\CljCompiler\Ast\NewExpr.cs:line 73
at clojure.lang.CljCompiler.Ast.NewExpr..ctor(Type type, List`1 args, IPersistentMap spanMap) in D:\work\clojure-clr-1.4.1-fix\Clojure\Clojure\CljCompiler\Ast\NewExpr.cs:line 49
at clojure.lang.CljCompiler.Ast.NewExpr.Parser.Parse(ParserContext pcon, Object frm) in D:\work\clojure-clr-1.4.1-fix\Clojure\Clojure\CljCompiler\Ast\NewExpr.cs:line 117
at clojure.lang.Compiler.AnalyzeSeq(ParserContext pcon, ISeq form, String name) in D:\work\clojure-clr-1.4.1-fix\Clojure\Clojure\CljCompiler\Compiler.cs:line 1560, compiling: (NO_SOURCE_PATH:60)

Sorry if this is a newbish question, but  isn't behaving the same as Java interop!
Is the syntax different for .NET?

A: Interop in ClojureCLR is very similar to interop in Clojure, but platform differences do show through.
java.lang.Double is a very different creature than System.Double. The JVM's Double is a wrapper class that is distinct from the class of primitive double values.  CLR's Double actually is the class of primitive double values.  j.l.Double has many methods not paralleled in S.Double. Re your example: j.l.Double has several constructors; S.Double has none.  To accomplish what you want, use clojure.core/double:
user=> (class (double 2))
System.Double

The Java wrapper types are a likely place to run into platform differences: CLR does not have explicit wrapper types.  I don't know of any place that has tried to cover this in detail.
For hints on how to handle CLR interop for things not in the JVM, such as by-ref parameters, enums, etc., check out the wiki on the github repo for ClojureCLR.


text:
Q: Getting 404 page not found error while checking from postman I'm running the below code using goapp serve. Somehow getting 404 page not found error while checking from postman. Could you please help me to fix this
    package hello

        import (
        "fmt"
        "net/http"

        "github.com/julienschmidt/httprouter"
    )

    func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        fmt.Fprint(w, "Welcome!\n")
    }

    func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
        fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
    }

    func init() {
        router := httprouter.New()
        router.GET("/", Index)
        router.GET("/hello/:name", Hello)
//log.Fatal(http.ListenAndServe(":8080", router))

    }

In postman passing endpoint
http://localhost:8080/hello/hyderabad

A: To expand on my comment above:
A handler function (or the router from julienschmidt/httprouter) does not register itself. Instead, it needs to be registered with the http server.
The simplest way to do that is usually do register with the default ServeMux using: http.Handle("/", router)
Thus, changing the init function to the following will work:
   func init() {
        router := httprouter.New()
        router.GET("/", Index)
        router.GET("/hello/:name", Hello)
        http.Handle("/", router)
    }


text:
Q: Не сохраняются изменения git Все привет!
Ситуация такая: есть bare репозиторий на сервере. Соединяюсь сервером по ssh. при попытке "сохранить" изменения на локальном репозитории (т.е. push, commit) операции идут нормально. При просмотре на сервере git log - коммиты видит. Но изменения при этом не сохраняются.
Решение:
Виной всему оказалось моя собственная невнимательность и тупость.
Дело в том, что в пушил не в ту ветку. Правда это я понял только после того, как пересоздал репозиторий.

A: @garmayev

Ситуация такая: есть bare репозиторий на сервере.
...
Элементарно посмотреть файлы. Сервер - виртуальный дебиан, к которому я могу обратиться с помощью putty.
Может, я неправильно сформулировал проблему - изменения не сохраняются на сервере. Все коммиты - записывает, а сами файлы - нет

bare-репозитории не содержат файлов (точнее, рабочего каталога с файлами) по определению, только наборы изменений. Что характерно, буквально позавчера про это читал.
Цитата отсюда:

В удаленных репозиториях нет смысла хранить рабочие файлы на диске (как это делается в рабочих копиях), а все что им действительно нужно — это дельты изменений и другие бинарные данные репозитория. Вот это и есть «чистый репозиторий».


text:
Q: Should databases be dumped to SQL format or custom archive? I am wondering, what is the industry standard regarding dump formats, when making and storing the database dumps?
Is it better to dump it to a custom-format compressed and unreadable archive, or just simply .sql?

This is database-agnostic question, but here are examples for PostgreSQL to give the idea:
# MYDATABASE to CUSTOM ARCHIVE
pg_dump -Fc mydatabase > mydatabase.dump

vs.
# MYDATABASE to SQL
pg_dump -h localhost -U postgres pagila > mydatabase.sql

A: Ask yourself the same question that you ask whenever you need to store any Data:

How are you going to use this Data Backup?

If you need to get "into" the file and manipulate it (as a Developer might in order to restore part of a dump into a Test database) then something text-based is an obvious choice.
If the database is terabytes in size, then a custom, compressed format might be more appropriate.
Please bear in mind that backups, in themselves, are not important.
(Yes, I really did say that).
What matters is that you can recover the database ...   and backups are a really good way of supporting that.
For straight-line speed of recovery, pg_basebackup - or something based on it - should be your first choice.  Whilst pg_dump produces a portable, Logical "copy" of [part of] the database, using the output from pg_basebackup will be much, much faster.


text:
Q: AttributeError: module 'ImageFilter' has no attribute 'BoxBlur' import ImageFilter

def blur_im(path:str, output: str = "output.jpg"):
    OriImage = Image.open(path)
    OriImage.show()

    boxImage = OriImage.filter(ImageFilter.BoxBlur(5))
    boxImage.show()

    boxImage.save(output)

    return 0

Error while calling the function.
Pls help , why there is a error in calling the function and ImageFilter as an attribute BoxBlur.I have written it correctly ig what's the issue pls help.
Error in the following line :
boxImage = OriImage.filter(ImageFilter.BoxBlur(5))
Error:
AttributeError: module 'ImageFilter' has no attribute 'BoxBlur'

A: Your import statement doesn't seem right. You are using Image in the first line of your function, but where are you importing it from?
Did you mean:
from PIL import Image, ImageFilter in case you have installed Pillow?


text:
Q: What is the right screen size and density configuration of Nexus 6? My app doesn't list Nexus 6 as a supported device in Google Play Console.
I read the blog post Getting Your Apps Ready for Nexus 6 and Nexus 9 which says:

Nexus 6 has a quantized density of 560 dpi, which falls in between the
  xxhdpi and xxxhdpi primary density buckets.

There is a paragraph exactly about my problem:

Make sure you are not filtered on Google Play
If you are using the
   element in the AndroidManifest.xml file, you
  should stop using it because it's not scalable to re-compile and
  publish your app each time new devices come out. However, if you must
  use it, make sure to update the manifest to add the configuration for
  these devices (by screen size and density). Otherwise your app may be
  excluded from Google Play search results on these devices.

Well, I have to use <compatible-screens> because I'm trying to exclude my app from tablets.
My current <compatible-screens> element in Manifest looks like:
<compatible-screens>
    <!-- small size screens -->
    <screen
        android:screenDensity="ldpi"
        android:screenSize="small" />
    <screen
        android:screenDensity="mdpi"
        android:screenSize="small" />
    <screen
        android:screenDensity="hdpi"
        android:screenSize="small" />
    <screen
        android:screenDensity="xhdpi"
        android:screenSize="small" />
    <screen
        android:screenDensity="480"
        android:screenSize="small" />

    <!-- normal size screens -->
    <screen
        android:screenDensity="ldpi"
        android:screenSize="normal" />
    <screen
        android:screenDensity="mdpi"
        android:screenSize="normal" />
    <screen
        android:screenDensity="hdpi"
        android:screenSize="normal" />
    <screen
        android:screenDensity="xhdpi"
        android:screenSize="normal" />
    <screen
        android:screenDensity="480"
        android:screenSize="normal" />
    <screen
        android:screenDensity="640"
        android:screenSize="normal" />
</compatible-screens>

What is the right configuration for Nexus 6?
I have tried:
    <screen
        android:screenDensity="560"
        android:screenSize="normal" />
    <screen
        android:screenDensity="480"
        android:screenSize="large" />
    <screen
        android:screenDensity="560"
        android:screenSize="large" />
    <screen
        android:screenDensity="640"
        android:screenSize="large" />

But none of it seems to do the trick.

A: I asked Google Play support and got an answer which helped me solve the issue.
Still not 100% sure about the right screen configuration, but it seems like
<screen
    android:screenDensity="560"
    android:screenSize="normal" />

is the correct option.

My app was not compatible with the Nexus 6, though, due to a conflict in my app's Manifest. I used following feature requirements:
<uses-feature android:name="android.hardware.LOCATION" />
<uses-feature android:name="android.hardware.TELEPHONY" />
<uses-feature android:name="android.hardware.TOUCHSCREEN" />
<uses-feature android:name="android.hardware.WIFI" />
<uses-feature android:name="android.hardware.location.GPS" />
<uses-feature android:name="android.hardware.location.NETWORK" />
<uses-feature android:name="android.hardware.screen.PORTRAIT" />

But the correct version is with the features listed in all lowercase letters:
<uses-feature android:name="android.hardware.location" />
<uses-feature android:name="android.hardware.telephony" />
<uses-feature android:name="android.hardware.touchscreen" />
<uses-feature android:name="android.hardware.wifi" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-feature android:name="android.hardware.location.network" />
<uses-feature android:name="android.hardware.screen.portrait" />

It's a bit tricky one, because permissions (in <uses-permission>) like
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

should be listed in capital letters, but feature (in <uses-feature>) should be lowercase.
I haven't come across the same issue on any other device, but if Nexus 6 requires this, it's probably the right way of doing it.


text:
Q: WBR tag breaking hyperlinks I was investigating the cause of hyperlinks breaking on a friend's website. She copies over her content from email and pastes it in the Wordpress editor. In a few articles, the content between the a tags has wbr in it and that seems to break the hyperlinks. You can find it on http://chandni.org/information-about-awards-scholarships-and-more/
In case it's fixed  by the time you see the thread,
the copied content
http://www.msrlm.org/mrlif/<wbr />faqenglish.html

what is shown by wordpress
http://www.msrlm.org/mrlif/<wbr>faqenglish.html

I am guessing it's due to the fact that it uses  and not . Should I replace the former with the latter? Looking for inputs from people who're familiar with wbr tag.

A: I just checked this on a test site. I added only this link to a post.
http://www.msrlm.org/mrlif/<wbr />faqenglish.html

The result from the page source is:

http://www.msrlm.org/mrlif/<wbr />faqenglish.html

*

*Verify the site is using the latest WordPress version,

*Temporarily disable all plugins to rule out a plugin conflict,

*Switch themes to rule out a theme problem.

A: It's very likely the user in question has the administrator role, and still has the dangerous unfiltered_html capability.
Because of this, the <wbr> tag is not stripped out by the security filters, and is left as is, causing your problems. Either remove this capability or demote the user to a non-admin e.g. an editor.
As for the <wbr> tag itself, it's a standard HTML tag, not part of a plugin. It indicates to the browser an opportunity for a word break
https://html.com/tags/wbr/

The <wbr> element is used to define a word break opportunity in a string of text. It is particularly useful when you wish to define word break opportunities in a long unbroken string of text that might otherwise break improperly.

So the <wbr> tag itself is not dangerous or problematic, and may even help the formatting of the content.


text:
Q: Selenium-Server: Weird message when using browserReuseSession flag I get the error message:
sel_<NUMBER> resultHolder sel_<NUMBER> unexpected response: OK,..

It seems that the server is stuck after this message occurs.
Why is this happening and how to solve/prevent it? I've never seen this message when the browserReuseSession is off. Have you?

A: The theory is that selenium uses /dev/random and that /dev/random blocks when the entropy pool gets low.  When this happens, selenium is also blocked.
I am trying the following workaround on my Macbook:
sudo mv /dev/random /dev/random.real
sudo ln -s /dev/urandom /dev/random
Wish me luck.  :)


text:
Q: Ошибка билда под андроид При попытке сделать билд под андроид выскакивает следующее:
CommandInvokationFailure: Gradle build failed.
C:/Program Files/Unity/Hub/Editor/2019.4.40f1/Editor/Data/PlaybackEngines/AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2019.4.40f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-5.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

stderr[

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\Artom\New Game\Temp\gradleOut\launcher\build.gradle' line: 3

* What went wrong:
A problem occurred evaluating project ':launcher'.
> Failed to apply plugin [id 'com.android.application']
   > Your project path contains non-ASCII characters. This will most likely cause the build to fail on Windows. Please move your project to a different directory. See http://b.android.com/95744 for details. This warning can be disabled by adding the line 'android.overridePathCheck=true' to gradle.properties file in the project directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
]
stdout[

]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.AndroidJavaTools.RunJava (System.String args, System.String workingdir, System.Action`1[T] progress, System.String error) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
Rethrow as GradleInvokationException: Gradle build failed
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, System.String workingdir, System.String task, System.Action`1[T] progress) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
Rethrow as BuildFailedException: Exception of type 'UnityEditor.Build.BuildFailedException' was thrown.
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, System.Exception ex) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <dd2e71f8d45046b88d6d3169a8084aec>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <7105be432fb64891b07085914e6cd5c1>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

A: Как понять в чём проблема через логи?
Ищём в логе FAILURE:  (это наша ошибка), читаем его, понимаем что "Сборка не удалась с исключением"
Ищём в логе дальше * What went wrong: (это то что пошло не так), читаем его и понимаем что Your project path contains non-ASCII characters., что прямо нам говорит о том что путь с проектом содержит не читаемые символы, может в пути есть символы кириллицы?


text:
Q: What is the reason for useState() react hooks always returns the initial state? I am making a form in react with validation. I have to show the error after validation. So I used useState() hook as follows. But it seems i can't update the new state as it always returns the initial value. Where did I go wrong?
import React, { useState } from 'react';
import './index.css';

const Firstname = ({ handleInputChange, firstName }) => {

    const [error, setError] = useState('hi');

    const handleBlur = (event) => {
        const { value } = event.target;
        validateFirstName(value);
    }

    const validateFirstName = (name) => {
        if (name.trim().length === 0) {
            setError('Enter first Name');
        }
        console.log(error);
    }

    return (

        <>
            <label>First Name</label>
            <input type='text'
                placeholder='Eddard'
                name='firstName'
                value={firstName}
                onChange={handleInputChange}
                onBlur={handleBlur} />

        </>

    )
}

export default Firstname;

I tried to console.log(error) but it always returns the initial state hi.

A: This is because state updates are asynchronous.
You need to console.log(error) just before your return to see it at each render.

A: In the input, you should use defaultValue instead of value
<input type='text'
    placeholder='Eddard'
    name='firstName'
    defaultValue={firstName}
    onChange={handleInputChange}
    onBlur={handleBlur} />

It would also be better if you move the log inside the if-statement
const validateFirstName = (name) => {
    if (name.trim().length === 0) {
        setError('Enter first Name');
        console.log(error);
    }
}

A: setState is asynchronous, if you need to catch the new value you can use useEffect.


text:
Q: Laravel / Snappy: can not generate PDF or create folder This is my code:
$offer = Offer::find($id);
$url = URL::to('/offers/view/' . $id . '/pdf');

PDF::loadFile($url)
    ->callSettings()
    ->save('/tisa/src/public/pdf/offer/Tisa-ponudba_'. $offer->code .'.pdf');

I am getting following error:
RuntimeException in AbstractGenerator.php line 517:
The output file's directory '/tisa/src/public/pdf/offer' could not be created.

Any ideas what could be wrong? I can not determine if a file can not be created or is the folder path?


text:
Q: Google login without dialog I wanted to know if the following workflow would be possible for an application I am developing. The backend is a python REST API and the frontend will use AngularJS.
What I would like to do is have a login page (requires email address + password) where depending on the email domain I would either try to do a Google login using OAuth or try authenticating using credentials stored in the database. Now as far as I can see to use Google Signin I have to have a dialog that comes up asking the user to login or select their account, but if the user has already entered their email and password on my login page I don't want them to have to enter it again when Google asks for it.
Thanks


text:
Q: Perform actions on a currently running process I am currently trying to write a script which will retrieve some information from a website which is protected by Windows Security authentication prompt.
Here's a piece of code which I use to enter credentials:
$wshell = New-Object -com WScript.Shell
$wshell.Run("iexplore.exe $url_session_tool")
Start-Sleep -Milliseconds 10000
$wshell.sendkeys("$login")
$wshell.sendkeys("{TAB}")
$wshell.sendkeys("$password")
$wshell.sendkeys("{TAB}")
$wshell.sendkeys("{ENTER}")

The problem is, iexplore is running as WScript.Shell object which doesn't really support any functions that would help me retrieve some information I am looking for from the IE website.
Is there any way to import the running iexplore.exe process as InternetExplorer.Application object? Something like:
Select-object -com "InternetExplorer.Application"

Perhaps there's another (easier or more complicated) way to deal with this problem?
I'd greatly appreciate any help.

A: With Invoke-WebRequest you can supply credentials for authentication.
$cred = get-credential
invoke-webrequest -uri $url -credential $cred

https://technet.microsoft.com/en-us/library/hh849901.aspx


text:
Q: python pandas iterate over dataframe rows with iterrows is slow, can it be replaced somehow? I have the following problem. I have 2 dataframes one with only 0's and columns name as the attributes which I know them from a different text file, and one which have column from first dataframe as values and NaN's for each row. Now, I want to set 1's on the dataframe with 0's, where the second dataframe values have the attribute.
the second data frame looks like this.

the first data frame looks like this.

and i want to change the first data frame into this.

for index, row in df.iterrows():
for element in row:
    if pd.isnull(element) : break
    # row index, element column so we change the value of the column thats named element from 0 to 1.
    Final_Df.at[index,element] = 1

This is the code I am using to achieve that. df is the second dataframe with NaN values, and Final_Df is the first dataframe with 0's. Is there a way to achieve it faster somehow by not using iterrows because the dataset is larger? Any help will be appreciated, and sorry if the question is bad. Thanks in advance!

A: To test my solution, I used the following DataFrame with smaller number
of codes:
    0   1    2    3    4    5    6    7    8    9
0  fl  nc  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  fl  nc  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
2  ct  dc   fl   hi   il   ky   la   md   mi   ms
3  ct  dc   fl   il   ky   la   md   mi   ms   nc
4  hi  pr  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
5  hi  il   ky   md   mi   ms  NaN  NaN  NaN  NaN
6  hi  il   ky   la   mi   ms  NaN  NaN  NaN  NaN
7  ct  la   md   ms   nc  NaN  NaN  NaN  NaN  NaN
8  dc  md   mi   ms   nc  NaN  NaN  NaN  NaN  NaN
9  dc  md   mi   nc  NaN  NaN  NaN  NaN  NaN  NaN

To create Final_Df I started with a list of codes:
codes = ['ca', 'ct', 'dc', 'fl', 'hi', 'il', 'ky', 'la', 'md', 'mi', 'ms', 'nc', 'pr']

and created Final_Df (full of zeroes) the following way:
Final_Df = pd.DataFrame(0, index=df.index, columns=codes)

I need also a dictionary to translate codes into column numbers,
with -1 for NaN (these values will be omitted):
codeToInd = { code: ind for ind, code in enumerate(codes) }
codeToInd[np.nan] = -1

The first step of actual computation is to translate df into ind - a
Numpy array:
ind = np.vectorize(codeToInd.get)(df)

The result is:
array([[ 3, 11, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 3, 11, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
       [ 1,  2,  3,  5,  6,  7,  8,  9, 10, 11],
       [ 4, 12, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 4,  5,  6,  8,  9, 10, -1, -1, -1, -1],
       [ 4,  5,  6,  7,  9, 10, -1, -1, -1, -1],
       [ 1,  7,  8, 10, 11, -1, -1, -1, -1, -1],
       [ 2,  8,  9, 10, 11, -1, -1, -1, -1, -1],
       [ 2,  8,  9, 11, -1, -1, -1, -1, -1, -1]])

One more preparatory step is to extract the underlaying Numpy array
from Final_Df:
finDfVal = Final_Df.values

And the actual processing (setting *1*s at proper cells) is performed
with the following loop:
for r, c in np.argwhere(ind >= 0):
    finDfVal[r, ind[r, c]] = 1

After that Final_Df contains:
   ca  ct  dc  fl  hi  il  ky  la  md  mi  ms  nc  pr
0   0   0   0   1   0   0   0   0   0   0   0   1   0
1   0   0   0   1   0   0   0   0   0   0   0   1   0
2   0   1   1   1   1   1   1   1   1   1   1   0   0
3   0   1   1   1   0   1   1   1   1   1   1   1   0
4   0   0   0   0   1   0   0   0   0   0   0   0   1
5   0   0   0   0   1   1   1   0   1   1   1   0   0
6   0   0   0   0   1   1   1   1   0   1   1   0   0
7   0   1   0   0   0   0   0   1   1   0   1   1   0
8   0   0   1   0   0   0   0   0   1   1   1   1   0
9   0   0   1   0   0   0   0   0   1   1   0   1   0

Execution speed
Using %timeit I compared the execution time of my code with yours
and on this very limited data sample I got about 7 times shorter time.
I think that on a bigger DataFrame the difference should be greater.
Write what was the execution time of your code and mine.
In case of an error
To check what is goin on, try to create a DataFrame counterpart of ind,
just for display:
df.applymap(lambda x: codeToInd[x])

If everything is OK, a DataFrame with translated codes should be printed.
But in case of any missing value in codeToInd a KeyError exception
is raised, showing the missing value.
Add this missing value to codes and repeat the whole procedure.

A: Idea is create dictionary for each row in list comprehension, pass to DataFrame constructor, replace missing values to 0 and last use DataFrame.reindex for remove NaN column, change order and add non exist values to column filled by 0:
codes = ['ca', 'ct', 'dc', 'fl', 'hi', 'il', 'ky', 'la', 'md', 'mi', 'ms', 'nc', 'pr']

Final_Df = (pd.DataFrame([dict.fromkeys(x, 1) for x in df.to_numpy()])
              .fillna(0)
              .astype(np.int8)
              .reindex(codes, axis=1, fill_value=0))

Another solution:
Use get_dummies with max values per columns (for always 0,1) values and then DataFrame.reindex for change order of columns and also add some non exist columns filled by 0:
codes = ['ca', 'ct', 'dc', 'fl', 'hi', 'il', 'ky', 'la', 'md', 'mi', 'ms', 'nc', 'pr']

df = (pd.get_dummies(df, prefix='', prefix_sep='')
        .max(axis=1, level=0)
        .reindex(codes, axis=1, fill_value=0))
print (df)

A: I would suggest to use Pandas Vectorization. This tutorial is a good starting point:
https://towardsdatascience.com/how-to-make-your-pandas-loop-71-803-times-faster-805030df4f06

A: If it is not important that rows or columns that are all NaN are included you can also try the following:

*

*Melt your dataframe:

# >>> df
#      0    1    2    3    4
# 0  NaN  NaN   ct  NaN  NaN
# 1  NaN  NaN  NaN  NaN  NaN
# 2   ta  NaN  NaN   ga  NaN
# 3  NaN  NaN  NaN  NaN  NaN
# 4  NaN  NaN  NaN  NaN  NaN

molten = pd.melt(df.T)

# >>> molten
#     variable value
# 0          0   NaN
# 1          0   NaN
# 2          0    ct
# 3          0   NaN
# 4          0   NaN
# 5          1   NaN

*

*use pandas.crosstab to tabulate the entries:

tab = pd.crosstab(molten["variable"], molten["value"])

# >>> tab2
# value     ct  ga  ta
# variable
# 0          1   0   0
# 2          0   1   1


text:
Q: get selected value of Select Control in Asp.net MVC razor I have defined an select on top of my page which shows pageSize(item list pr page)
        <select name="ddlPageSize" style="text-align:left;width:80px;">
        @for (var i = 5; i <= 100; i=i+5){

             <option>@i</option>
        }
        </select>

now when i wants to set page size in pagging link like.

        @for (int i = 0; i < (int)Math.Ceiling((decimal)totalCount / (decimal)pageSize); i++)
        {
            int page = i + 1;
            string background = "transparent";//transparent
            if (pageNo == page)
            {
               background = "grey";
            }

                 @page

        }

in html anchor i wants to pass selected page size too with page Number
@page

A: You will need to change the url on ddlPageSize selected index change in jQuery.
Here is a link for the same
How to change the href for a hyperlink using jQuery
First of all add some class over your anchor so that you can easily get your Item in jQuery as.
 @page

and use jquery as below
$("#ddlPageSize" ).on("change", function() {
   var selectedValue=$(this).val();
   $(".apager").each(function(item,index){
       item.attr("href",item.attr("href")+"&pageSize="+selectedValue);
   });

});

Note that this is just an idea not implemented so far.

A: If you want to update the anchor link based on user selection, it will have to be done client side.
Also use the data attributes for the URL.  You know you will update the URL with just the current page.
@page

Attach a function to the change event of the dropdown.
$("#ddlPageSize" ).on( "change", function() {

   $("#LINKID").attr("href", $("#LINKID").data("id") + "&size=" + $("#ddlPageSize").val())

});

something like that...


text:
Q: How to get details about how Mathematica did a definite Integral Assuming[{Element[S, Reals],S>0},Integrate[Exp[-I*S*w]/(w^2 + 1)^(3/2)
   ,{w, 0, Infinity}]]

gets
 1/2 S(I π BesselI[1, S] + 2 BesselK[1, S] - I π StruveL[-1, S])

However Mathematica cannot do the indefinte integral with a variable lower or upper limit so differentiation cannot be used to see how it did this integral.
Is there any way to find out or person who can figure it out, please. Change of variable to Sw would give leading S as a divisor not a factor. Not clear where the 3 parts come from.
Thanks JM
          LaplaceTransform[1/(w^2 + 1)^(3/2), w, s]
         -(1/2) π s (BesselY[1, s] + StruveH[-1, s])

is down to 2 terms. But still unclear where they come from

A: I'm not sure how Integrate found the answer, but here's a way it could have conceivably used.
If we can express your integrand as the product of two MeijerG functions, there's a rich list of integral identities we can use. In particular we can treat your integral as a Mellin transform at s == 1 and use the general identity here:

In our case:
mei = MeijerGReduce[Exp[-I*S*w]/(w^2 + 1)^(3/2), w]

int = MellinTransform[mei, w, 1]

MeijerG[{{1/2}, {}}, {{0, 1/2, 1}, {}}, -S^2/4]/π

FullSimplify[FunctionExpand[int], S > 0]

1/2 I S (-2 + π BesselI[1, S] - 2 I BesselK[1, S] - π StruveL[1, S])

We can see int (defined above) appears in the TracePrint of the Integrate call and so maybe this is the method it chose:
TracePrint[
  Integrate[Exp[-I*S*w]/(w^2 + 1)^(3/2), {w, 0, Infinity}],
  _MeijerG,
  TraceInternal -> True
]

MeijerG[{{1/2}, {}}, {{0, 1/2, 1}, {}}, 16/S^4, -2]
...
...
long spew omitted
...

A: Thanks to everyone for their input. The real and imaginary parts of this integral are in fact given in Abramovitz and Stegun, eqns. 9.6.25 and 12.2.3 resp. sections on $K_1$ and $L_1$, though that still doesn't explain how they were worked out originally.
$$I_{-\nu}(x)-\mathbf{L}_\nu(x)=\frac{2(x/2)^\nu}{\sqrt{\pi}\,\Gamma(\nu+\tfrac12)}\int_0^\infty\sin(tx)(1+t^2)^{\nu-\tfrac12}\mathrm dt\quad \Re\nu<\frac12,\,x>0$$
There is a as much info there on the imaginary part difference function  BesselI[1, S] - StruveL[-1, S]) as StruveL individually including the asymptotic series so their small difference has been noted before. But the Taylor series that Chip found is not there, so thanks.
Unfortunately Mathematica does not recoginise this difference function and does not use the differnce asymptotic series so its computation broke down at S=35 for me.


text:
Q: Fork vs Thread in Web Server I am aware that threading is the preferred way to go, but what are some benefits of using Forking or Threading in something like a Web server?
Update: My question is about either forking off a process or to start a separate thread to deal with each connections.
Is there any other (perhaps better) way to manage the connections?

A: In many modern web applications, you are often spending a lot of time on an external resource: a database, a cache server, a filesystem, etc.  In this case, a threading model helps by not reserving memory resources for multiple processes that are going to spend most of the time idle.
The benefit of the forking model is primarily when you have existing frameworks that aren't aware of threads (most PHP, Ruby, Python, etc. applications).  Making existing apps thread-aware can take a huge amount of time and effort.  In some cases, such as where the app uses a lot of CPU, RAM bandwidth, or I/O with resource contention (i.e. a single-channel disk controller), processes aren't that much of a disadvantage.


text:
Q: How to create schema to generate a JSON Array using Schema and transformers provided by DataFaker API in Java? I am using DataFaker library to create schema for JSON Object and Array. Since the use of Format is deprecated, I am trying with Transformation Schemas. I tried examples given under the Format section of official documentation to create a schema for Json Array but wasn't successful.
Example JSON Array -
[
{
"firstName": "Oleta",
"lastName": "Toy"
},
{
"firstName": "Gerard",
"lastName": "Windler"
}
]

A: Raised the same question on Datafaker GitHub and got the solution.
JsonTransformer transformer = JsonTransformer.builder().formattedAs(JSON_ARRAY).build();
Adding the direct link here.
https://github.com/datafaker-net/datafaker/issues/720#issuecomment-1445929651


text:
Q: Flow (+ React-Native): Depending function parameters I want to type a function with two params where the second one is depending on the first. My idea was to make a function type for each possible first param ("A" and "B" in example) and combine them in another type with '|' (or) condition but this results in an error "string (Expected string literal B, got A instead string literal B)" when I try to call the function with one of the possible values of the first param.
// @flow

import React, { Component } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';

type GoToScreenA = (screen: 'A', params: { someParam: string }) => void;
type GoToScreenB = (screen: 'B', params: { someOtherParam: number }) => void;

type GoToScreen = GoToScreenA | GoToScreenB;

type Props = {
  navigation: {
    navigate: GoToScreen,
  },
};

class TestComponent extends Component<Props> {
  onPress = () => {
    this.props.navigation.navigate('A', { someParam: 'foo' });
    // flow throws: string (Expected string literal `B`, got `A` instead string literal `B`)
  };

  render() {
    return (
      <TouchableOpacity onPress={this.onPress}>
        <Text>Click Me</Text>
      </TouchableOpacity>
    );
  }
}

export default TestComponent;

A: For now I ended up with following workaround but will appreciate better answers.
// @flow

import React, { Component } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';

type NavigateOption<Screen, Params> = {
  screen: Screen,
  params: Params,
};

type NavigateOptions =
  | NavigateOption<'A', { someParam: string }>
  | NavigateOption<'B', { someOtherParam: number }>;

type Props = {
  navigation: {
    navigate: (screen: string, params?: {}) => void,
  },
};

class TestComponent extends Component<Props> {
  onPress = () => {
    this.navigate({ screen: 'A', params: { someParam: 'foo' } });
  };

  navigate = (options: NavigateOptions) => {
    this.props.navigation.navigate(options.screen, options.params);
  };

  render() {
    return (
      <TouchableOpacity onPress={this.onPress}>
        <Text>Click Me</Text>
      </TouchableOpacity>
    );
  }
}

export default TestComponent;


text:
Q: I'm unable to update the progressbar width in jquery Here the progressbar width is not updating properly.I'm using the socket.io for emitting the progress percent.
Eventhough the progress percent is 100%,it is showing as in the screenshot provided.If I manually refress the html page,it is progress bar width is updating properly.
I'm really stuck over  here.Can anyone please help me out regarding this issue ...
My app.js :
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');
var request = require('request');
var progress = require('request-progress');
var targz = require('tar.gz');

var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'node-v0.12.7.tar.gz'

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express ();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

http.listen(8085, function(){
    console.log('listening on *:8085');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

app.get('/get', function (req, res) {
 res.sendfile('views/index.html');

});

io.of('/socket_issue').on('connection', function (socket) {
        console.log("Socket connected :"+socket.id);
    });
var callback = function(state){
    console.log('received size in bytes', state.received);
    console.log('total size in bytes', state.total);
    console.log('percent', state.percent);

     io.of('/socket_issue').emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));

}

progress(request('https://nodejs.org/dist/v0.12.7/node-v0.12.7.tar.gz'), {
    throttle:0,
    delay: 0
})
.on('progress', callback)

.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
 console.log("error");
})
.on('close', function (err){
console.log("Download Complete");
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

My index.html :

Screen shot of progressbar:

A: Don't over-complicate stuff.
socket.on( 'message', function( data ){
    $( '#progressBar div' ).css( "width", data + "%" );
    $( '#progressBar div' ).html( data + "%" );
}

Then add CSS transition rule
#progressBar div {
    transition: 500ms ease-in;
}

This will eliminate need to use animate function.


text:
Q: Display multiple data into chart.js I am creating a Chart.js (http://www.chartjs.org/docs/#radar-chart-introduction) from a JSON file.
But I am doing it so with a "checkbox", the idea is click on the element desire and it will display a different data inside de same canvas.
I think I almost have but I have a problem when I want to save the data. As you can see here, with console.log I can see the data through the loop, and its fine but when its trying to keep it into data object, its wrong.
chart.js:25 CSN08101
chart.js:26 rgba(255, 99, 132, 0.2)
chart.js:27 rgba(255,99,132,1)

chart.js:25 CSN08112
chart.js:26 rgba(54, 162, 235, 0.2)
chart.js:27 rgba(54, 162, 235, 1)

chart.js:47
  Object
    datasets:
      Array[1]
        0:Object
          backgroundColor: "rgba(54, 162, 235, 0.2)"
          borderColor: "rgba(54, 162, 235, 1)"
          data: Array[19]
          label: "CSN08112 module"
          __proto__: Object
          length: 1
          __proto__: Array[0]
          labels: Array[19]
          __proto__: Object

chart.js:47
  Object
    datasets: Array[1]
      0: Object
        backgroundColor: "rgba(54, 162, 235, 0.2)"
        borderColor: "rgba(54, 162, 235, 1)"
        data: Array[19]
        label: "CSN08112 module"
        __proto__: Object
        length: 1
        __proto__: Array[0]
        labels: Array[19]
        __proto__: Object

This is my code:
$(function () {
  $('#go').click(function(){

    var checkbox_value = [];
    $(":checkbox").each(function () {
        var ischecked = $(this).is(":checked");
        if (ischecked) {
            checkbox_value.push($(this).val());
        }
    });

    var background = ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)",
                      "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)",
                      "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)"];

    var border = ["rgba(255,99,132,1)", "rgba(54, 162, 235, 1)",
                      "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)",
                      "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)"];

    var data = [];
    for (var m = 0; m < checkbox_value.length; m++) {
      var mid = checkbox_value[m];
      var backid = background[m];
      var bordid = border[m];
      console.log(mid);
      console.log(backid);
      console.log(bordid);
      $.ajax({
        url: "output.php",
        data: { MOD_CODE: mid },
        dataType: 'json',
        success: function(d){
          data[m] = {
            labels:[],
            datasets:[{
              label: mid + ' module',
              backgroundColor: backid,
              borderColor: bordid,
              data:[],
            }]
          };

          for (var i = 0; i < d.length; i++) {
            data[m].labels.push(d[i][0]);
            data[m].datasets[0].data.push(parseFloat(d[i][1]));
          }//.for
        console.log(data[m]);
        }//.success
      }); //.ajax
    } //.for

    // Create the chart with the data collected
    var ctx = document.getElementById("myChart");

    var myChart = new Chart(ctx, {
      type: 'radar',
      data: data,
      options:{
        responsive:false,
        scale:{ticks: {beginAtZero: true}}}});

  })//.click
});//.function

A: The only solution I found is with sync which apparently is not good, but if anyone find another solution feel free to post it
$(function () {
  $('#go').click(function(){

    var checkbox_value = [];
    $(":checkbox").each(function () {
        var ischecked = $(this).is(":checked");
        if (ischecked) {
            checkbox_value.push($(this).val());
        }
    });

    var background = ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)",
                      "rgba(255, 206, 86, 0.2)", "rgba(75, 192, 192, 0.2)",
                      "rgba(153, 102, 255, 0.2)", "rgba(255, 159, 64, 0.2)"];

    var border = ["rgba(255,99,132,1)", "rgba(54, 162, 235, 1)",
                  "rgba(255, 206, 86, 1)", "rgba(75, 192, 192, 1)",
                  "rgba(153, 102, 255, 1)", "rgba(255, 159, 64, 1)"];

    var ddm = 0;
    data = {
      labels:[],
      datasets:[]
    };
    for (var m = 0; m < checkbox_value.length; m++) {
      var mid = checkbox_value[m];
      var backid = background[m];
      var bordid = border[m];

      var ajaxResponse = $.ajax({
        url: "output.php",
        data: { MOD_CODE: mid },
        dataType: 'json',
        async: false,
        success: function(d){

          data.labels = [];
          data.datasets[ddm] = {data:[]};
          for (var i = 0; i < d.length; i++) {
            data.labels.push(d[i][0]);
            data.datasets[ddm].data.push(parseFloat(d[i][1]));
            data.datasets[ddm].label = mid;
            data.datasets[ddm].backgroundColor = backid;
            data.datasets[ddm].borderColor = bordid;
          }//.for
          ddm++;

          if (ddm == checkbox_value.length) {
            console.log(data);
            // Create the chart with the data collected
            var ctx = document.getElementById("myChart");
            var myChart = new Chart(ctx, {
              type: 'radar',
              data: data,
              options:{
                responsive:false,
                scale:{ticks: {beginAtZero: true}}}
            });//.new Chart
          }//.if

        }//.success
      }); //.ajax
    }//.for

  })//.click
});//.function


text:
Q: Solving recurrence relation in form of $f(n)=f(n-1)+K-n$ I asked a question (now deleted) on finding a relation between $$4,10,15,\cdots$$
I studied a little about recurrence relation and solving them. For the above sequence I observed that
$$f(n) = \left\{\begin{array}{cc} 4, & \textrm{if}\ n=1, \\  f(n-1)+8-n, & \textrm{otherwise}.\end{array}\right.$$
I looked up in Wikipedia about methods of solving recurrence relations but I was not able to determine which one is related to this.

A: Since $$f(n+1)-f(n)=K-(n+1),$$
we have, for $n\ge 2$,
$$\begin{align}f(n)&=f(1)+\sum_{i=1}^{n-1}(K-(i+1))\\&=4+\sum_{i=1}^{n-1}((K-1)-i)\\&=4+(K-1)(n-1)-\frac{(n-1)n}{2}.\end{align}$$
Note that this holds for $n=1$.
So, for your case, setting $K=8$ gives you
$$f(n)=4+(8-1)(n-1)-\frac{(n-1)n}{2}=\frac{-n^2+15n-6}{2}\ \ (n\ge 1).$$


text:
Q: How to create context menu on double click? I need to create context menu on double click as well as on long tapping. How it can be done?
I mean normally onCreateContextMenu called when user press long tap on widget. In my case I need to do the same when user double clicks on widget.
ADDED
I know that it's not really nice option, since it's not normal for Android UI. But my primary problem is to solve UI bugs for devices of some vendors - namely HTC (look this post). I have seemingly resolved described issue, but still I do have problems with context menus. So as a last resort I just thought to avoid tapping through double click. Thanx for understanding...

A: From what I gather, you have context-sensitive actions you want tied to an EditText, and HTC's changes to Android are interfering with that.
First, I would reconsider using context menus in general, as they are not particularly discoverable, so most of your users will never find them.
Second, in the case of the EditText, the odds of users discovering that a double-tap will bring up a context menu will be on par with the odds that the Earth will have an extinction-level asteroid strike today.
:: looks up in sky ::
Rather than a double-tap, one option would be to put a small ImageButton adjacent to the EditText, with a downward-facing arrowhead (akin to a Spinner), and tie that ImageButton to a PopupMenu (ideal, but only API Level 11), a PopupWindow, or an AlertDialog. Or, in a pinch, have the ImageButton display a context menu when clicked via showContextMenu(). This too is non-standard UX, but it is at least more discoverable, as users will be used to things popping up when pressing down-arrow buttons, from both Android and other OSes.
If you are absolutely convinced that you need a double-tap, AFAIK that is not a recognized touch event, so you will need to handle the low-level touch events yourself, determine when a double-tap occurs, and do so in a way that does not interfere with the usage of the EditText (e.g., setting cursor position).


text:
Q: Undefined property: Auth::$model [CodeIgniter] I know this quention might seems duplicated, but i already tried those suggestions/advice but still couldn't solve this:
environment :
$autoload['libraries'] = array('email', 'session', 'database', 'form_validation');

controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller {

public function __construct()
{
    parent::__construct();
    $this->load->library('form_validation');
    $this->load->model('Auth_model', 'Auth');
}

private function _login()
    {
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        $user = $this->model->Auth->getUser();

Model :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth_model extends CI_Model
{
    public function getUser()
    {
        $email = $this->input->post('email');
        // var_dump($email);die;
        return $this->db->get_where('t_user', ['email' => $email])->row_array();
    }
}

I Still got this error :

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Auth::$model
Filename: controllers/Auth.php
Line Number: 38

A: Change
   $user = $this->model->Auth->getUser();

into
$user = $this->Auth->getUser();

A: try this into the class you will use
Type $ this-> library -> (" library you want "). I hope it helps.


text:
Q: (laravel4) pulling data from pivot table I tried to refrain myself from asking a stupid question once again, but here i am...
So i want to check if a ID in my pivot table (tutorial_id) matches another id. However, i have no idea how to to get this ID from the pivot table.. this is what i tried:
Controller:
class TagController extends BaseController {
    public function getTutorials($tag) {
    $tag_id = Tag::where('name', $tag)->first();

    $tutorials = Tutorial::with('tags')->where('tutorial_id', '=', $tag_id->id)->get();
    return View::make('tutorials/tags', array(
        'tutorials' => $tutorials
    ));
}
}

Tutorial model:
class Tutorial extends Eloquent {
    protected $table = 'tutorials';

    public function tags() {
        return $this->belongsToMany('Tag', 'tutorials_tags', 'tutorial_id');
    }
}

Tag model:
class Tag extends Eloquent {
    protected $table = 'tags';
    public function tutorials() {
        return $this->belongsToMany('Tutorial', 'tutorials_tags', 'tag_id');
    }
}

Database looks like this:

However i now get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tutorial_id' in 'where clause' (SQL: select * from `tutorials` where `tutorial_id` = 1)

A: So you want all tutorials with tag_id->id, you can do that like this: $tag_id->tutorials
I reformatted the code for you:
public function getTutorials($tag) {
    $tag = Tag::where('name', $tag)->first();

    return View::make('tutorials/tags', array(
        'tutorials' => $tag->tutorials
    ));
}

reference: http://vegibit.com/many-to-many-relationships-in-laravel/


text:
Q: Programmatically create columns in a View This should be easy.  I want to populate a grid with a custom data source at runtime.  For some reason, it simply does not work.
Running via a unit test
[TestMethod]
public void Runtest() {
    TestForm form = new TestForm();
    TestControl control = new TestControl();
    form.Controls.Add(control);
    control.LoadData();
    form.ShowDialog();
}

The relevant Control code
public void LoadData() {
    SourceRecord[] original = new SourceRecord[] {
        new SourceRecord("1"), new SourceRecord("3"), new SourceRecord("9") };
    gridControl1.DataSource = original;
    GridColumn col = gridView1.Columns.AddVisible("SomeColumn");
    col.FieldName = "SomeName";
    //gridControl1.ForceInitialize();
}

Record info
public class SourceRecord {
    public string SomeName = "";
    public SourceRecord(string Name) {
        this.SomeName = Name;
    }
}

I end up with some column just called "Column" which displays 3 rows reading ClassLibrary1.SourceRecord.  Then my custom column "Some Name" has no data.  According to the devexpress walkthrough I only need to populate the DataSource with a class that implements IList, which I did with an Array.
How can I display just my custom column and give it the data?

A: The grid control will bind columns to properties only. Try this:
public class SourceRecord
{
    public string SomeName { get; set; }
    public SourceRecord(string Name)
    {
        SomeName = Name;
    }
}

public void LoadData()
{
    SourceRecord[] original = new SourceRecord[] { new SourceRecord("1"), new SourceRecord("3"), new SourceRecord("9") };
    GridColumn col = gridView1.Columns.AddVisible("SomeColumn");
    col.FieldName = "SomeName";
    gridControl1.DataSource = original;
}


text:
Q: What to do instead of SQL joins while scaling horizontally? What would I use instead of SQL joins when I have a large complex relational-database that just got too large to fit on a single machine? I've begun sharding the database across many machines, but as a result, I can no longer do joins efficiently.
Any tips?

A: Depending on the data you are using, you could potentially denormalize it and spread it across different DB nodes. That would make you writes a bit more tricky, but would improve read performance.

A: There are many approaches to make this work, the general idea is to shard your data in such a way as to group related data.
As a simple (trivial) example, if you have a Game database, you can shard Player and PlayerGame data by the same key (playerId). If there are other tables that are related, you can add those too, think of it as a "shard tree" of related tables. Then all the data for a given Player will be guaranteed to be in the same shard. You can then perform joins within a shard, but you cannot do inner joins across shards.
The other common technique is to replicate Global tables to all shards, these are typically tables that are not updated often, but are used in lots of joins.
With these two approaches you can:

*

*Join within the Shard Tree (but not a cross-shard inner join, e.g., between 2 players)

*Join from a sharded table to a Global table at any time

Then the other trick is distributed queries, where you may need to rollup results from many shards (e.g., a count of all Players).
Here is a white paper that describes a lot of this in more detail:
http://dbshards.com/dbshards/database-sharding-white-paper/
The key to this type of approach is to understand how you want to query the data. The answer above can also be useful, to de-normalize some data when you have to query it from a different perspective. In that case you need to write the data in two (or more) formats, and partition your shards according to each structure. Again using the simple example above, let's say you need to query all the Players for a single GameInstance. Now you could make a separate "shard tree" with GameInstance as the parent and PlayerGame as the child, sharded by GameInstanceId. Now that query will be efficient too.
The goal is to have as many single shard operations as you can, as distributed operations oddly enough are generally the "evil" of a distributed database cluster.


text:
Q: How to prove using case splitting when hypothesis is false in some cases? I am working on some exercises on Idris proofs and I keep running into the same problem in various exercises. I first describe the problem in general, and then I give a concrete example:
theorem: (some variables) -> (hypothesis using those variables) -> (proof goal)

Now suppose that I want to give the proof using case-splitting, and that in some cases the assignment of the variables makes the hypothesis false. This means that the situation can never occur, so the proof can continue. But how to tell this to Idris?
For example:
andb_true_elim_2 : (b, c: Bool) -> (b && c = True) -> c = True
andb_true_elim_2 True c prf = prf -- This is OK!
andb_true_elim_2 False c prf = ?hole -- This is the problem

As b is false, b && c = True evaluates to False = True, which is impossible, so there will never be a valid value for prf that reaches this case, so it is irrelevant.
How does one solve these kind of problems?
Thanks!

A: If you try to pattern match the proof with Refl, Idris will see that the it's impossible. You can then use the impossible keyword to tell Idris to not worry about it.
andb_true_elim_2 : (b, c: Bool) -> (b && c = True) -> c = True
andb_true_elim_2 True c prf = prf
andb_true_elim_2 False c Refl impossible


text:
Q: Ubuntu booting in mac I have installed Ubuntu on my USB drive according to the instructions here
http://ubuntuhandbook.org/index.php/2014/11/install-real-ubuntu-os-usb-drive/
and the installation went successfully and Ubuntu was running on my mac.
After I restarted the mac I couldn't be able to boot Ubuntu again from the Startup Manager, When I press (Option ⌥) key I only found the main hard drive that boots me into macOS.
How can I solve this problem and boot into the USB drive again?

A: Below is the sequence of steps needed to finish installing Ubuntu on a Mac. I assume you installed Ubuntu to use EFI booting.

*

*Boot to Ubuntu live.

*From the Desktop, press the control+option+T keys to open a Terminal window.

*Enter the command shown below.
sudo  fdisk  -l  /dev/sda

Below is the output I saw from entering this command.

Note: For a better view, click on the image or open the image in a new window.

*From the output of the sudo fdisk -l /dev/sda command, determine the device for the EFI System partition. For me, this was /dev/sda1. If you determine a different device, make the appropriate substitutions.

*Enter the commands given below to make Ubuntu appear in the Startup Manager.
sudo  bash
mkdir  efi
mount  /dev/sda1  efi
cd  efi/EFI
mkdir  BOOT
cp  ubuntu/grubx64.efi  BOOT/bootx64.efi
cd  ~
umount  efi
rmdir  efi
exit
exit

*Shutdown Ubuntu live.

*Startup the Mac and immediately hold down the option key until the Startup Manager icons appear.

*Click on the hard disk icon labeled "EFI Boot". Next, while holding down the control key, click on the circular arrow below this icon.
You are finished. Your Mac will now automatically boot to Ubuntu on startup and restart.


text:
Q: Database approach for Game Leaderboard I am working on a sever app that has multiple games and should be able to handle millions of players. Each game needs a leaderboard and must be able to show the player's current position and top 10 players, as well as the positions of the players friends.
Currently I am using two tables.
user_score

*

*id

*user_id

*game_id

*score

*created_at

user_ max_score

*

*id

*user_id

*game_id

*max_score

*created_at

*updated_at

Whenever a user plays any game for the first time data is inserted in the first and second table. If the user plays a second time and scores more than their previous score we insert data into user_score table and update user_max_score table with the new max_score.
And for getting the rank of the user I fire query like this.
SET @i=0;
SELECT id, user_id, max_score, @i:=@i+1 AS rank
FROM user_max_score WHERE game_id = $gameId
ORDER BY max_score DESC, updated_at ASC;

Is there any better approach than this?

A: One approach I am using is a single table concept. All scores posted, and then you can consolidate scores in the back ground to a summary table. This maintains front end performance, and you can handle back ground consolidation process for summary information into a cache table for the accumulated scores, in my situation I am using goLang and couchbase tables, but in mySql, you will find add a row to be much faster than upsert, where you find a record and then update. The current database modals are changing rapidly to the noSQL format due to size and scalability, the old SQL modal struggles for performance and replication get complex, for a single DB system and small user base, your are fine.
Request URL
HTTP POST   http://[some dns]:8080/v1/post_score

Request Payload
{
    'user_id'  :    '[some-user-id]',
    'game_id'  :    '[some-game-id]',
    'score'    :    [value],
    'duration' :    [time played],
    'level'    :    [level reached],
    'stars'    :    [stars gained],
    'os'       :    '[os identified]'
}

Additional fields in the Database, captured by the user agent.
'ip' : [detected user ip],
'ts" : [timestamp from the server point of view]


text:
Q: Php session variable I write a shopping cart in my local server (WAMPSERVER) with session variable. The another site is equal to my session variable $_SESSION['cart']. So I add a product to my cart the another site is also update and if I add product in another site my cart also update. How can I solve this problem.
[edit]
I mean my two site is equal in session variable name. So they conflict.

A: If you want to share session data (this is vaguely what your question sounds like), then you can either:

*

*Store the session data in a database accessible from both servers. Load $_SESSION manually depending on a manually managed cookie id.

*Setup a network filesystem that both servers share. Look up where PHP stores the session files with http://www.php.net/manual/en/function.session-save-path.php and make it available on both servers. This depends on the used network filesystem, but is potentially unreliable. (But OTOH you are using WAMP anyway..)

Some other (and likely better) solutions are listed here: Cross domains sessions - shared shopping cart cross domains

A: function: session_save_path ([ string $path ] ) maybe help. use different path for each site.

OR

This problem is like the problem in installing multiple sites in one database, in this case you should use prefix_ for your tables.

like this you should use PREFIX_ anywhere you use session.

for example in Database we have something like this:

$sql = "SELECT * FROM ".Config::getInstance()->dbprefix."users WHERE ...;";

in this case we need something like that:

$_SESSION[Config::getInstance()->domainname."card"];

A: It's very difficult to to understand what you're saying. So forgive me if I'm a bit off.
From what I understand you currently have a website(example.com) and a local website through WAMP(presumably, localhost) and you want the two $_SESSION['cart'] variables to act as one?
Or rather simpler, you want your localhost cart synchronized with your online cart and vice versa. Right?
If you have complete control over both sites, I would suggest passing an encrypted session id through the url. As in:
pseudo code
 temp_var = localhost_cookie
 mydomain.com/page.php?a=temp_var
 mydomain_cookie = gets a
 destroy temp_var

Untested and that's really all I can think of right now.


text:
Q: Unable to install Ubuntu 18.04 after cancelled installation I was attempting to install Ubuntu however halfway through the menus asking me to select the what types of files I would like to install I decided to cancel the installation by clicking the cancel button on the bottom of the window, I assumed I could come back to the installation at a later time however when I attempted to boot using the disk I had used flawlessly before. I was met with a message detailing that it;
Failed to open \EFI\BOOT\mmx64.efi - Not Found
Failed to load image \EFI\BOOT\mmx64.efi: Not Found
Failed to start MokManager: Not Found
Something has gone seriously wrong: import_mok_state() failed
: Not Found
I attempted to wipe my computer clean so I reset the computer to factory settings five times with each attempt failing to correct the issue. I am wondering if there is a way I can fully remove the corrupted pieces and attempt a clean installation of Ubuntu from the disk since I don't have any free usb's lying around. P.S. I am attempting to set up my computer so that it can dual boot. Thank you for your time.

A: The problem was that in the bootable USB the file mmx64.efi didn't exist.
Solution1:
Renamed the file grubx64.efi to mmx64.efi located at folder EFI\BOOT on USB and Reboot.
Solution2:
Copy the file grubx64.efi under the name mmx64.efi (so the USB Drive folder /EFI/BOOT now contains three files: BOOTx64.EFI, grubx64.efi and mmx64.efi).
Then, reboot


text:
Q: SlidesJS hide pagination I am using Slidesjs to use a simple scroller on my site.  However, I cannot hide the pagination that shows the 1 and 2 bullet points.
The link for the project is www.barterscloset.com
I have tried trying to hide it in css and in a Jquery.hide function.
Thanks in advance!

A: There's an option built in, add these lines to where you fire the plugin:
pagination: false,
generatePagination: false

so your whole call would look like this (if you had no other otpions set, that is)
$(function(){
    $("#slides").slides({
        pagination: false,
        generatePagination: false
    });
});


text:
Q: C# - Body content in POST request I need to make some api calls in C#. I'm using Web API Client from Microsoft to do that. I success to make some POST requests, but I don't know how to add the field "Body" into my requests. Any idea ?
Here's my code:
    static HttpClient client = new HttpClient();
    public override void AwakeFromNib()
    {
        base.AwakeFromNib();
        notif_button.Activated += (sender, e) => {
        };
        tips_button.Activated += (sender, e) =>
        {
            Tip t1 = new Tip(title_tips.StringValue, pic_tips.StringValue, content_tips.StringValue, "TEST");
            client.BaseAddress = new Uri("my_url");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            CreateProductAsync(t1).Wait();
        };
    }

    static async Task<Uri> CreateProductAsync(Tip tips)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/add_tips", tips);
        response.EnsureSuccessStatusCode();
        return response.Headers.Location;
    }

A: Thanks to this and this, I finally found the solution to send post requests with headers AND body content. Here's the code:
        var cl = new HttpClient();
        cl.BaseAddress = new Uri("< YOUR URL >");
        int _TimeoutSec = 90;
        cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
        string _ContentType = "application/x-www-form-urlencoded";
        cl.DefaultRequestHeaders.Add(key, value);
        cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
        cl.DefaultRequestHeaders.Add("key", "value");
        cl.DefaultRequestHeaders.Add("key", "value");
        var _UserAgent = "d-fens HttpClient";
        cl.DefaultRequestHeaders.Add("User-Agent", _UserAgent);

        var nvc = new List<KeyValuePair<string, string>>();
        nvc.Add(new KeyValuePair<string, string>("key of content", "value"));
        var req = new HttpRequestMessage(HttpMethod.Post, "http://www.t-lab.fr:3000/add_tips") { Content = new FormUrlEncodedContent(nvc) };
        var res = cl.SendAsync(req);

A: a little more understandable
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
    client.DefaultRequestHeaders.Add("Accept", "*/*");

    var Parameters = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("Id", "1"),
    };

    var Request = new HttpRequestMessage(HttpMethod.Post, "Post_Url")
    {
        Content = new FormUrlEncodedContent(Parameters)
    };

    var Result = client.SendAsync(Request).Result.Content.ReadAsStringAsync();
}

A: Step 1. Choose a type that derives from HttpContent. If you want to write a lot of content with runtime code, you could use a StreamContent and open some sort of StreamWriter on it. For something short, use StringContent.  You can also derive your own class for custom content.
Step 2. Pass the content in a call to HttpClient.PostAsync.
Here's an example that uses StringContent to pass some JSON:
string json = JsonConvert.SerializeObject(someObject);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync("http://www.foo.bar", httpContent);

See also How do I set up HttpContent?.


text:
Q: Create a constraint for Bottom Layout guide in a XIB I'm updated an app that was built using XIB's.  In one of the XIB's I have the view then some objects inside, one being a tableview.  I put a constraint for the bottom and it lists like so:
Bottom Space to: Superview
         Equals: 5

Depending on the device, the tableview will extend beyond the screen at the bottom, not extend all the way & sometimes lines up just right.  Out of curiosity I created a test project that uses stroyboards(which I have more experience with) & I created the same scenario but being that the View Controller Scene uses Top & Bottom Layout guides my constraint for the bottom looks like so:
Bottom Space to: Bottom Layout Guide
         Equals: 5

This works perfectly on all devices; the tableview lines up with the bottom of the screen.
So my question is how do I get the same constraint in my XIB to line up to the bottom if I don't have a Bottom Layout Guide as an option?

A: To set UITableView constraints as like below code so it will occupied whole screen.
Leading Space = 5 from mainView
Top Space = 5 from mainView
Bottom Space = 5 from mainView
Trailing Space = 5 from mainView

Hope this help you.

A: I wasn't getting anywhere with this approach, so I added a storyboard, added my objects and everything is lining up accordingly.  I don't know if this is a bug or something, but I've never had this problem before.  thanks to everyone for there help.


text:
Q: How do I indicate a user's input has ended when writing to a file in Python? I believe in C we could do ctrl+z for EOF (ctrl+z worked for this), but how do I do this in Python? I'm using '0' temporarily. I'm using Windows 10 with Python 3.11.
#create a text file and write some lines to it

f = open("newfile.txt",'w')
line = ""
while line != '0': #I'm not sure what to use to indicate the end of the user's input
    line = input()
    f.write(line + '\n')

f.close()

A: If you do press ctrl+z  for the input you would get an EOFError. So you could change your code as follows,
with open('newfile.txt', 'w') as f:
    while True:
    try:
        line = input()
        f.write(line + '\n')
    except EOFError:
        break


text:
Q: Objective C View to Controller Communication What is the proper way to accept user input in a view and then transfer it to that view's controller? I know the NotificationCenter is one option, but surely there is a more elegant way to transfer data from a view to its controller?
All help is greatly appreciated and I always accept an answer!

A: Use the delegate protocol design pattern, or target-action by subclassing UIControl. Think about how a UIButton tells a view controller that it's been pressed. In interface builder, you connect an action - a selector something like touchUpInside: to a target - the view controller that owns it. In non-IB, you directly tell the UIButton what selector and what target to use.
Both methods make sense in different cases. For a UITextField, for example, it makes more sense to use delegation because it's possible for the text field to send you any number of events, such as an event when the user begins editing, ends editing, or types a character.
For a button, it makes more sense to use target-action because there's really only one event expressed in different forms.
For swipes and drags and other gestures, use UIGestureRecognizers.

A: You are looking for delegation, where the controller set itselfs as the delegate of the view. You know it from UITableViewDelegate.

A: You're looking for Delegation or a Data Source. You can see more information about this here, Delegation and Data Sources
A brief example of this would be, something along the lines of this:
  //MyViewSubclass.h

  @protocol MyViewSubclassDelegate
  //Implement your delegate methods here.
  -(void)didTouchView;
  @end

  @interface MyViewSubclass {

     id<MyViewSubclassDelegate>delegate;
  }
  @property(nonatomic,assign)id<MyViewSubclassDelegate>delegate;

Of course, @synthesize your delegate in MyViewSubclass.m
Now in the class's header, that you want the delegate of MyViewSubclass to be, you need to conform to the `MyViewSubclassDelegate Protocol.
 #import "MyViewSubclass.h"
 @interface MyViewController : UIViewController <MyViewSubclassDelegate>

In your @implementation of MyViewController., implement the MyViewSubclassDelegate method of -(void)didTouchView.
When you initialize and create your MyViewSubclass object, you set MyViewController as the delegate:
myViewSubclass.delegate = self // Self being MyViewController.

In your MyViewSubclass, when you're ready to forward any information, or simply want to fire a method you would do [self.delegate didTouchView]
Hope this helps !

A: Make your view a subclass of UIControl and implement the target/action design pattern - use the  sendActionsForControlEvents: method to message the controller.

A: Often the UIKit objects like UITextField have delegate methods that you can implement to perform your business logic. E.g UITextField has a delegate method called - textFieldDidEndEditing: that gets called after the user has dismissed the keyboard.


text:
Q: dynamically change the connection string in ssrs reports hi i need to dynamically change the connection string in ssrs reports. We have a report built in our DEV environment but when it's moved over to our prod environments, (by someone else) we'd like to change the connection to different servers done without the promoter to give the connection string...

A: It is necessary that in the "Connection String Properties", "connection string" to start a function "fx"
set of two or more "connection string" in function with certain parameters

A: Try this out, this is how i got around to dynamic connection on SSRS report
Dynamic connections/Expression based connection string SSRS


text:
Q: Is it true that $\sigma$-field generated by finite subsets only has finite elements I know there is a rule to generate a $\sigma$-field of finite subsets, as follows:
https://math.stackexchange.com/q/200943
However, I am not clear about how to show that there is not a element in $\sigma-field$ excluded by such collection of $\mathcal{K}$