text:
Q: Error while running python with xammp server I am new in running python with xammp server. I have done all the required setup to run python in xammp server by following this link Running Python scripts with Xampp. While trying to running my code i always get an error.

**Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at postmaster@localhost to
inform them of the time this error occurred, and the actions you
performed just before this error.
More information about this error may be available in the server error
log.**

My error log says this:
[Tue Jan 19 10:29:34.529875 2021] [cgi:error] [pid 11652:tid 1860] [client ::1:50570] malformed header from script 'python.py': Bad header: Hello World
i am attaching the code for my file too.
#! C:\Users\"UserName"\AppData\Local\Programs\Python\Python39\python.exe
print("Content-Type: text/html\n\n")
import cgi

print("Hello Python")

i have tried everything i could to search for the solution but nothing is helping. Please help me finding a solution. Thank you

A: Update the \n\n to use a carriage return (\r\n\r\n), and add another in.
This should make your HTTP headers valid, as they may not be terminating correctly.
Edit: You can also try multi-line print instructions such as
print "Content-type: text/html"
print ""

This is interpreting the body as the header (never terminated) so terminating this correctly should fix it.


text:
Q: Geometric meaning of a nondegenerate critical point Let $f\!:M\!\rightarrow\!\mathbb{R}$ be a smooth function on a manifold and $p\!\in\!M$. Is there any way to geometrically/visually characterize the conditions

*

*$p$ is a critical point (i.e. $D(f)_p\!=\!0$) and

*$p$ is a nondegenerate critical point (i.e. $\det D^2(f)_p\!\neq\!0$)?
If $f(x)=\langle x,a\rangle$ is a height function on a surface, then $f$ is linear, so $D(f)_p\!=\!f\!:\, T_pM\rightarrow T_p\mathbb{R}\!=\!\mathbb{R}$. Thus $f$ is the zero map at those $p$ for which $T_pM$ is perpendicular to $a$, i.e. the critical points of $f$ are those points at which $T_pM=a^\bot$. But what about higher dimensions and different $f$s?
And what about nondegeneracy?

A: Consider the case where $M$ is an open subset of $\mathbb{R}^2$ and visualize $f$ by visualizing its graph in $\mathbb{R}^3$. In the neighborhood of a point $p$, the function $f$ has an expansion into Taylor series. Then

*

*$p$ is a critical point if this expansion has no linear terms. This occurs whenever $f$ attains a local minimum or a local maximum but it can also occur e.g. if $p$ is a saddle point.

*$p$ is a nondegenerate critical point if the quadratic terms of the Taylor series expansion give a nondegenerate quadratic form. There are three cases: $p$ is a local minimum (so think locally $f(x, y) = x^2 + y^2$) $p$ is a local maximum (so think locally $f(x, y) = - x^2 - y^2$, or $p$ is a saddle point (so think locally $f(x, y) = x^2 - y^2$). This follows from the three possible distributions of signs of eigenvalues of the Hessian.

The reason we care about nondegeneracy is that if $p$ is a degenerate critical point then the behavior of $f$ in a neighborhood of $p$, even in a very qualitative sense and in a very small neighborhood, may depend on higher-order terms in the Taylor series (e.g. consider $f(x, y) = x^2 + y^4$ vs. $f(x, y) = x^2 - y^4$). Nondegeneracy allows us to only consider the linear and quadratic terms.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIScrollView + UIWebView = NO scrollsToTop It looks like a problem which could have simple solution, but I haven't found anything what could lead the way to it. I'm using UIWebView inside of UIScrollView and tapping on statusBar (to scroll content to top) is not working.
I've made simple test application to see if it's really UIWebViews fault. And it really is.
//  scrolls to top on status bar tap
UIScrollView *sv = [[UIScrollView alloc] init];
sv.frame = CGRectMake(0, 0, 320, 480);
sv.contentSize = CGSizeMake(320, 1200);
[self.view addSubview:sv];

// doesn't scroll
UIScrollView *sv = [[UIScrollView alloc] init];
sv.frame = CGRectMake(0, 0, 320, 480);
sv.contentSize = CGSizeMake(320, 1200);

UIWebView *wv = [[UIWebView alloc] init];
wv.frame = CGRectMake(0, 0, 320, 100);
[sv addSubview:wv];

[self.view addSubview:sv];

So, I think maybe there's something I could disable to make UIWebView not to mess with scrollToTop? Or some kind of workaround also would be nice.
Any ideas?

A: I ran into this last night until I finally found the answer buried in a comment to a comment.  The idea of that original post is that when you add the UIWebView to your UIScrollingView, you use the following:
- (void) ensureScrollsToTop: (UIView*) ensureView {
    ((UIScrollView *)[[webView subviews] objectAtIndex:0]).scrollsToTop = NO;
}

This seemed fishy to me since the first sub-view of a UIWebView claims to be a UIScroller which is not a subclass of UIScrollView.  However, since UIScroller supports the scrollsToTop property, the cast just gives us a way past the compiler warning:

Class List:
    Class = UIScroller
    Class = UIView
    Class = UIResponder
    Class = NSObject
Supported Methods:
    ...
    Method _scrollToTop
    Method setScrollsToTop:
    Method scrollsToTop
    ...
Supported Properties:
    Property scrollsToTop

EDIT:
Just another quick note about where this actually needs to occur: in the webViewDidFinishLoad callback.  Calling it on UIWebView construction isn't good enough because at that time the UIWebView hasn't created it's child views yet, which are the ones causing the problem:
- (void)webViewDidFinishLoad:(UIWebView *) wv {
    [self ensureScrollsToTop: wv];
}

EDIT #2:
now, in iOS 5, as noted in iPhone OS: Tap status bar to scroll to top doesn't work after remove/add back use UIWebView's new @property scrollView, making ensureScrollsToTop implementation unnecessary for projects that aren't using deployment targets lower than iOS 5.0 .

A: In iPhone OS, if there is more than one UIScrollView (or its subclass, for example UITableView, UIWebView) in the current viewController, the system doesn't know which UIScrollView should be scrolled to the top.
Quick fix: for all the UIScrollViews that you don't want to support scrollsToTop, just set the scrollsToTop as NO, then every thing works perfect.
self.scrollView1.scrollsToTop = NO;
self.scrollView2.scrollsToTop = NO;
self.scrollView1.scrollsToTop = YES; // by default scrollsToTop is set as YES, this line is not necessary

A: Webviews by default will have YES for scrollsToTop-value. I've written a simple class for this specific issue. In my app we're having multiple webviews and scrollviews. This makes it all much easier.
https://gist.github.com/hfossli/6776203
It basically sets scrollsToTop to NO on all other scrollViews than the one you are specifying.

A: I want to add my case, I add an UIWebView on an UIScrollView, as h4xxr said:

If there is more than one scrolling view a scrollViewDidScrollToTop message is ignored

So, I get a simply way to make it work on webView: just set the scrollView·s scrollsToTop property false.
And when tap the status bar, it won`t got intercepted by the scrollView, and the webView scrolls to the top!
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.frame = self.view.bounds;
    scrollView.scrollsToTop = false; //igore scrollView`s scrollsToTop
    [self.view addSubview:scrollView];

    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = scrollView.bounds;
    [scrollView addSubview:webView];


text:
Q: Basic redirect with HttpHandler (c#) I have a website which has recently moved to another domain (same but with different extension).
The old site finishes with .co.uk and the new one is .com
I want to use a httphandler to redirect all requests (if they are for .co.uk) to the equivalent page but with the .com extension (and to also rewrite the URL to match the change in location from .co.uk to com)


text:
Q: world in a dewdrop Novel where final paragraphs zoom out to reveal that entire world of story has taken place in a universe contained in a drop of dew on a leaf or blade of grass in the garden of an older couple, who I believe were British. Can anyone identify this novel?

A: It's James Blish's "Surface Tension".
Plot summary from Wikipedia:

A human colonization ship crash-lands on a distant planet which is earth-like but whose only landmass is completely covered in shallow puddles of water and mostly microscope life forms. Normal humans could not survive on this planet, so the crew must genetically engineer their descendants into something that can survive. (Blish coined the term pantropy to refer to this concept.) They decide to create a race of microscopic aquatic humanoids to complete their mission and colonize the planet.
The majority of the story concerns one groups of these genetically engineered colonists and their intelligence, curiosity, and evolving technology. In particular, the tiny aquatic humanoids develop a "space ship", or rather "air ship", which enables them to pierce the previously impenetrable surface tension of the water and travel through what is, to them, hostile space—open air—to other worlds in other puddles of water.

A: It seems like one of those stories:

*

*The Diamond Lens by Fitz James O'Brien

"The Diamond Lens" is probably his most famous short story, and tells the story of a scientist who invents a powerful microscope and discovers a beautiful female in a microscopic world inside a drop of water

*The Drop of Water by Hans Christian Andersen

The man looking through the microscope is named Cribbley Crabbey and he watches the little creatures tear each other apart in a drop of puddle water.


text:
Q: 3D Triangulation similar to Hawkeye Forgive me if this question has been asked before, but I'd like to know where to start to achieve stereo vision to convert 2D coordinates into 3D coordinates.  I'm trying to track balls like Hawkeye in 3D.  I have two high speed cameras and I'm able to detect the ball in each camera.  I understand that I need to calibrate the cameras, synchronize them and run some algorithm to remove lens distortion etc.  However, I don't know what the next step is to convert the 2D coordinates to world 3D coordinates.
Does anybody know how to perform triangulation who can assist me with this?  Also the cameras will not be parallel to each other, but at different angles, so somehow, I need to know the location of each camera in terms of their 3D coordinates.
Any help with this would be gratefully received.
Many thanks

A: I have recently found fragment of 'Learning OpenCV' book. It seems to be a good source of knowledge about either theory behind and implementation in opencv. Although, the API in book is outdated, the general mechanism still is up-to-date. To sum up, they recommend:

*

*Remove distortion (you can do this already if you have calibrated cameras)

*Adjust distances and angles between cameras

*Find the same features on both images

*Estimate depth by simple calculation considering object's position on an image.

A: To convert 2D into 3D for two calibrated cameras you would use these formulas:
z = focal*baseline/disparity
x = z*u/focal
y = z*v/focal
where
focal - the focal length of you camera in pixels
u = column-Cx, Cx~image_width/2 but calibration will give you more precise value
v = -row+Cy, Cy~image_height/2
Baseline - horizontal distance between cameras
disparity - difference in horizontal position of the ball in two images
Strictly speaking you need to do rectification only for working with dense stereo. For sparse stereo you only need calibration.


text:
Q: How to patch group in aws sso using SCIM I am new to aws sso, so don't know much about it. I was reading this
When I am trying to add user in a group I am getting 400. I am passing the group-id in URL and user id through body.
request_url_user = https://scim.us-east-1.amazonaws.com/{tenant_id}/scim/v2/Groups/groupID
User-Agent: Mozilla/5.0
Authorization: Bearer <bearer_token>

{
   "schemas":[
      "urn:ietf:params:scim:api:messages:2.0:PatchOp"
   ],
   "Operations":[
      {
         "op":"add",
         "path":"members",
         "value":[
            {
               "value":userID
            }
         ]
      }
   ]
}

r = requests.patch(request_url_user, headers=headers,data= body)
I am not sure, why I am getting 400 as I have literally the same syntax and everything.
PS- They have this constraint in doc.

Only displayName, members, and externalId attributes are allowed in
the request.

The id I am using to add a member is Group id and user id, not the external id. i have created the sso group manually, so there is no external id there. Any way I can add external id to it or any workaround this ?


text:
Q: Dspace JSPUI statistics not show values I just installed Dspace 4.2. I added some items. But when I access the Community, collection or item statistics in the JSPUI view it does not show any value to me.

Any help ?
Thanks in advance.

A: if it is a fresh installation I strongly suggest to use a more recent version. My recommendation is to use dspace 5.10
https://github.com/DSpace/DSpace/releases/tag/dspace-5.10
that is the best one in terms of stability, otherwise you can try dspace 6.3
Anyway, the latest version of the 4.x series is the 4.9 https://github.com/DSpace/DSpace/releases/tag/dspace-4.9
The issues is probably due to issue in the SOLR statistics core but without additional information, logs file, is difficult to guess. Take a look to what is logged in the ${dspace.dir}/log/dspace.log ${dspace.dir}/log/solr.log when you access the statistics page


text:
Q: Django: make field editable depending on the value of other field I'm new to Django, and I haven't found the answer yet in the extensive documentation. I'm asking for pointers to research, not for working code. That being said, here's my problem:
In one of my models theres a BooleanField (it gets rendered in the admin form as a checkBox). Let's call it 'A'. It only makes sense to edit other field (say, CharField 'B') if A is checked.
So, is there a way to make B read only, or even changing its content to an empty string, dinamically, if A is checked? Thank you.
(Django 1.5.2, Python 2.7.5)

A: You're going to need several things to make this work. You may be able to skip some of them depending if you mainly care abut the UI, or the data integrity in the db.
Since the user can (presumably) check/uncheck Field A on the client-side you need some Javascript to enable/disable the appearance of Field B. These docs show how to load custom JS in your ModelAdmin class:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-asset-definitions
In your ModelForm you may want to do some check in the __init__ method against the value of self.instance.field_a and substitute some kind of ReadOnlyWidget for Field B for the initial display of the form. These docs show how to give your ModelAdmin a custom form class:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
If you are writing some Javascript to do that dynamically it make be easier to skip this step and just do it client-side.
Finally you can use Django model validation to ensure that Field B is saved with a null value if Field A is checked:
https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects


text:
Q: Is there any way to trigger v-dialog from vuex store? I have a component just for dialog box and I want to trigger the components v-dialog from specific value on vuex store programmatically . Is there any way to achieve.

A: Make a state and it's getter on which basis you want to trigger dialog box. Add getter in computed properties of component then use it for dialog box.


text:
Q: Why the echo doesn't reset when I reload the browser? I am new here and I'm learning PHP recently. I'm using the xampp server.
So the problem is:
<?php
    if(isset($_POST['submit'])) { //this is from input type submit
        echo "it works";
    }
?>

So, when I click submit then it shows "it works". but when I reload the browser it does not go away.Here the text above form does go away when I reload the browser

A: It's normal.
When you submit your form, it show "It works", but when you reload the page, usually, your browser ask you if you want resend or reuse the same parameters (because the browser reuse the exact HTTP request, so resubmit the form)
Click on the URL, and press Enter to reload the page and not resend the. same request, which is a little bit different


text:
Q: Symfony4 swiftmailer doesnt exist in container im having troubles sending an email in symfony4. I'm following documentation so I installed swiftmailer using composer req mailer command. My method looks like this
public function sendAccountActivationLink(Array $data, \Swift_Mailer $mailer)
{
    $message = (new \Swift_Message('Hello Email'))
        ->setFrom('myemail@gmail.com')
        ->setTo($data['email'])
        ->setBody(
            $this->renderView(
                'mails/registration.html.twig',
                ['data' => $data]
            ),
            'text/html'
        )
    ;

    $mailer->send($message);
}

it says that Swift_Mailer class requires an transport interface, but there is nothing about it in the docs.
I tried to call mailer through container
$this->get('mailer')->send($message);

but it says Call to a member function has() on null
In addition ill paste my yml config
swiftmailer:
    url: '%env(MAILER_URL)%'
    spool: { type: 'memory' }
    transport: smtp
    username: myemail@gmail.com
    password: password
    host: localhost
    port: false

and the mailer url
MAILER_URL=gmail://myemail@gmail.com:password@localhost


text:
Q: Android Download file- Jackson readvalue failing to load the java class - heap size error I am trying to download an apk file  through a rest service via http GET. The format recieved is JSON. I am able to recieve the data but it fails while deserializing to a java object. I get Outofmemory error.
I am running the file download process in an Asyn Task. Is there other better options to achieve the same functionality. The apk is about 2 MB. The data from a wcf service is Base64 encoded in json
private  class DownloadFile extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... sUrl)
    {
        try
        {
             URL url = new URL(sUrl[0]);
              HttpURLConnection c = (HttpURLConnection) url.openConnection();
              c.setRequestMethod("GET");
              c.setRequestProperty("Content-Type", "application/json");
              c.setRequestProperty("Accept", "application/json");
              c.setRequestProperty("Device","13");
              c.setRequestProperty("Authorization","toughsecurity");
              c.setDoInput(true);
              c.connect();
              String PATH = Environment.getExternalStorageDirectory() + "/download/";
              File file = new File(PATH);
              file.mkdirs();
              File outputFile = new File(file, "app.apk");
              FileOutputStream fos = new FileOutputStream(outputFile);
             if(c.getResponseCode()==HttpURLConnection.HTTP_OK)
          {

                OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/download/"+"temp.txt");

                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = c.getInputStream().read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }

                out.flush();
                out.close();

                InputStream in=new FileInputStream(Environment.getExternalStorageDirectory() + "/download/"+"temp.txt");

               ObjectMapper mapper=new ObjectMapper();

              AppDownload download= mapper.readValue(in, AppDownload.class);

                 byte[] data1=Base64Coder.decodeLines(download.Data);
                  byte[] content = data1;
                int size = content.length;
                InputStream is1 = null;
                byte[] b = new byte[size];
                is1 = new ByteArrayInputStream(content);
                byte[] buffer = new byte[1024];
                 int len1 = 0;
                 while ((len1 = is1.read(buffer)) != -1) {
                     fos.write(buffer, 0, len1);
                 }
                 fos.close();

          }

             c.disconnect();

        }
        catch (Exception e)
        {
            Log.e("Jackson error",e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
      //  mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
       // mProgressDialog.setProgress(progress[0]);
    }

}

A: i wouldn't be surprised if the JSON library is barfing on a 2MB JSON file.
i know it probably isn't an option to change the API, but it's pretty strange to be returning binary data in JSON. it's not made for that. the API should provide two endpoints ... one that gets the object meta data including a link to the content, and one that returns the content only in binary form.
you could also try another JSON library.


text:
Q: How to make node.js and mysql work together? Thanks in advance for your help!
I am making a node/express app and I want to use a mysql database. But I can't seem to connect to the database.
I know I'm supposed to use the node-mysql module (https://github.com/felixge/node-mysql), but I must be doing it wrong.
I'm completely new to this. Do I have to create a database and then create a table? Is there a way to create a database elsewhere so it doesn't get erased every time I restart the app?
Here's my code. Can someone answer the questions above and tell me what I'm doing wrong below? Thanks!
var express = require('express'),
  routes = require('./routes'),
  user = require('./routes/user'),
  http = require('http'),
  io = require('socket.io'),
  path = require('path');

var app = express();
var server = http.createServer(app);
sio = io.listen(server);

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

var mysql      = require('mysql');
var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  port     : app.get('port')
});

connection.connect();

connection.query('CREATE TABLE tesTable (integer int, textfield VARCHAR(100), PRIMARY KEY(integer))',
                  function(err, result){
                      if(err) {
                          console.log(err);
                      } else {
                          console.log("Table testTable Created");
                      }
                  });

By the way, in package.json, I listed
"mysql": "2.0.0-rc2"

as a dependency and did
'npm install'

A: You can just create your tables in the database as you normally do and it will be persistent enough not to be deleted anytime you restart your app. You can connect to your database by using the following code if you want:
    var mysql = require('mysql');

app.use( connection(mysql, {
    host: 'myhost',
    user: 'user_name',
    password: 'password',
    port: 3306,          //port mysql
    database: 'database_name',
    multipleStatements: 'true'  //false by default

}, 'pool'));

req.getConnection(function(err, connection) {
    connection.query("SELECT * FROM `table_name`;",function (error,row){
        if(!error){
                       //do something.....
        }
        else console.log("Error : "+err);
        });
    //do something else...
});

A: My first suggestion, besides the question about any errors, is that you should try this
var mysql      = require('mysql');
var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  port     : your_MySQL_port
});

The port: app.get('port') in your given example returns your http server port, but not the port of your MySQL server.
Check https://github.com/felixge/node-mysql#connection-options at 'port'.
To get your MySQL port to insert in your_MySQL_port on Linux or Mac OS, just open a terminal an type:
ps ax | grep mysqld

as result you will see something like --port=1234 in the generated output. In this case 1234 is your_MySQL_port.
In this exmaple your code should look like:
var mysql      = require('mysql');
var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  port     : 1234
});

A: You might want to read a few tutorials on MySQL in general before jumping into it with Node, but in case you feel adventurous, here's a very brief tutorial on how I'd go about setting up MySQL on my machine.
I am assuming that you have access to the MySQL shell. If you're using a frontend the process may be different.
After installing MySQL and configuring an account, you'd want to log into the MySQL shell with the command
mysql -u me -p

followed by the password for the MySQL user when prompted.
Next, you'll want to create a database. You'd do this with the command
create database mydatabase;

then
use mydatabase;

Next you'll want to create a table. Run the CREATE TABLE query in the shell to set up a table. You could do this in Node, but then you'd be running the command needlessly every time you started the app.
Now you should be able to connect using node-mysql
var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  database : 'mydatabase',
  port     :  3306 // or whatever your mysql port is
});

A: I was facing same issue so how i solve it...
Mysql Part

1-I have already installed wamp and can access to phpmyadmin.
2-Using phpmyadmin i have created a database and a table say it users(please insert 2,3 rows data using insert menu option) look like
check

> http://prntscr.com/72gsxc

3-Make sure wamp is running and mysql service is also running.
4-Click wamp and mouseover MYSQL and then click my.ini and search there port by default it is 3306.

Node Part

    var pool =  mysql.createPool({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'cricstream_2',
        port     : 3306
    });

    var readTable = 'SELECT * FROM countries';

        pool.getConnection(function(error, connection){
          connection.query(readTable, function(err, rows){
            if(err) throw err;
            else {
                console.log(rows);
            }
          });
         });

A:
Do I have to create a database and then create a table?

Yes, you should create the database and the table ahead of time, that is correct.

Is there a way to create a database elsewhere so it doesn't get erased every time I restart the app?

Yes, you typically install MySQL server on a computer, this installation manages a run of databases, which you can remove/backup/duplicate etc, and create new databases.  Your NodeJS app would just be making a connection to your MySQL server installation.


text:
Q: split() method fail I'm reading a text file with the following format:
Room1*Exposition*Work 1 | Work 2 | Work 3 | Work n
Room2*Exposition*Obra 1 | Work 2 | Work 3 | Work n

Using the following:
try {

            String path="contenidoDelMuseo.txt";
            File myFile = new File (path);
            FileReader fileReader = new FileReader(myFile);

            BufferedReader reader = new BufferedReader(fileReader);

            String line = null;

            while ((line=reader.readLine())!=null){

            String [] fields = line.split("\\*");

}

An IndexOutOfBoundsException is thrown each time I try to access fields[1]. Why?
Edit: the whole code for the class is
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Buscar.java
 *
 * Created on 23/04/2009, 06:22:54 PM
 */

package interfaces;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/**
 *
 * @author Alirio
 */
public class Buscar extends javax.swing.JFrame {

    static ArrayList<String>obras = new ArrayList<String>();
    static ArrayList<String>salas = new ArrayList<String>();
    static ArrayList <String> exposiciones = new ArrayList <String>();

    /** Creates new form Buscar */

    public Buscar() {
        initComponents();

        try {

            String ruta="contenidoDelMuseo.txt";
            File myFile = new File (ruta);
            FileReader fileReader = new FileReader(myFile);

            BufferedReader reader = new BufferedReader(fileReader);

            String line = null;

            while ((line=reader.readLine())!=null){

                System.out.println(line);
            String []camposABuscar = line.split("\\*");
            salas.add(camposABuscar[0]);

            System.out.println(camposABuscar[0]);
            System.out.println(camposABuscar[1]);
            //System.out.println(camposABuscar[1]);
            // exposiciones.add(camposABuscar[1]);

            //String []obrasABuscar = camposABuscar[2].split("\\|");

            /*
            for (int contador =0; contador <obrasABuscar.length; contador++)
            {

                obras.add(obrasABuscar[contador]);
            }*/

            //System.out.print(obras.get(0));
            }

            reader.close();
        }

        catch (IOException ex){
            ex.printStackTrace();

        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        Buscatext = new javax.swing.JTextField();
        Criterios = new javax.swing.JComboBox();
        Buscar = new javax.swing.JButton();
        labelBusqueda = new javax.swing.JLabel();
        labelCriterios = new javax.swing.JLabel();
        BotonSalir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(null);

        jPanel2.setBackground(new java.awt.Color(255, 153, 0));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Buscador", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
        jPanel2.setToolTipText("Hola");

        Criterios.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-Seleccione-", "Autor", "Sala", "Piso", " " }));

        Buscar.setText("Buscar");
        Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BuscarActionPerformed(evt);
            }
        });

        labelBusqueda.setText("Busqueda:");

        labelCriterios.setText("Criterios:");

        BotonSalir.setText("Salir");
        BotonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(labelBusqueda, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Buscatext, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE))
                .addGap(63, 63, 63)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(labelCriterios)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(Criterios, 0, 179, Short.MAX_VALUE)
                        .addGap(56, 56, 56)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(BotonSalir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(Buscar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                        .addGap(60, 60, 60))))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {Buscar, Criterios});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelBusqueda)
                    .addComponent(labelCriterios))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Buscatext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Criterios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Buscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BotonSalir)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {Buscar, Criterios});

        jPanel1.add(jPanel2);
        jPanel2.setBounds(20, 180, 720, 130);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/LOGOTIPO.jpg"))); // NOI18N
        jPanel1.add(jLabel1);
        jLabel1.setBounds(10, 10, 250, 150);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondos/iconoconejo.gif"))); // NOI18N
        jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel3MouseClicked(evt);
            }
        });
        jPanel1.add(jLabel3);
        jLabel3.setBounds(710, 0, 50, 50);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondos/background_1.jpg"))); // NOI18N
        jLabel2.setText("jLabel2");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(0, 0, 980, 980);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 763, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 619, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>

    private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
        ClaveAdministrador CA= new ClaveAdministrador();
        CA.setVisible(true);
}

    private void BotonSalirActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        InterfazSeleccion A= new InterfazSeleccion();
        A.setVisible(true);
        this.setVisible(false);
}

    private void BuscarActionPerformed(java.awt.event.ActionEvent evt) {

        String s = Buscatext.getText ();

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Buscar().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton BotonSalir;
    private javax.swing.JButton Buscar;
    private javax.swing.JTextField Buscatext;
    private javax.swing.JComboBox Criterios;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel labelBusqueda;
    private javax.swing.JLabel labelCriterios;
    // End of variables declaration

}

A: I bet the first "line" of your file is actually blank, so your first time through the loop the split does nothing and hence the array is empty.  You could just check the size of the fields[] array before attemtping to use it, if its null (or length = 0) move on to the next line.

A: I ran the code with your data.  It worked...

A: I tried your the split method on your given text. I tried splitting it like you did yourself. Everything worked perfectly. I think there is something wrong when you are reading from your text file. I would suggest that you check that first.

A: This may be a silly answer, but does the file contain a blank line at the end?
Also, try printing out the line you're splitting just before you split it.  That way you can see what strings your code is actually trying to split.


text:
Q: prev() is not working it seems i have my code like this in one file...
      $d = new db();
class db
{
 function fetchform()
 {
    global $wpdb;
    $content='';
    $result = $wpdb->get_results("select * from kp_contact_form",ARRAY_A);
    $path =plugins_url().'/kp_contactus/ajax.php';
    $content.='<form action="'.$path.'" method="POST">';
    $content.= '
';
    foreach ($result as $row )
    {
        $content.='
'.$row['label'].'
        <input type="'.$row['type'].'" name="'.$row['name'].'" required>
        Remove	';
    }
    echo $content;
  }
}

here i am printing above function data

        <?php $d->fetchform(); ?>

Now i am trying to get name attribute of input type
 $(".remove").click(function(){
        alert("hii");
        var fid=$(this).prev().attr('name');
        alert(fid); // giving undefined
  }

when i am doing alert i am getting undefined... i don't know what's going wrong with my code..
can anybody help me
Thanks in advance

A: The previous element for .remove is... nothing! This is because .remove is the first element inside the td. You need to grab the parent element, its previous sibling, finally the input element within:
var fid = $(this).parent().prev().find("input").attr('name');

A: It doesn't work because the a is inside a td and thus doesn't have a sibling. What you can do is:
$(this).closest('td').prev().find('input').attr('name');

This selects the closest td parent, selects the previous td, then the input inside that.
Clarification:
I chose closest() instead of parent() because if you happen to wrap the a inside another element later on closest() will still work.

A: this is the remove link, it's the only child for the td, so no prev(), try this:
$(this).closest('tr').find('input').attr('name')


text:
Q: SQL Server Grant CRUD to Users on One Schema I have a schema called training. I want users who will be trained to have CRUD permissions on any object on that schema. I do not want them to have any other permissions on any other object outside that schema, and I also do not want them to have create/drop permissions for the schema itself. What is the least permissions to grant this type of access?
Currently, I set up the schema training with dbo as the owner. Then I created a role called training_modify and added the training schema as a securable with "Select", "Update", "Insert", and "Delete" explicitly granted. Finally, I will add users to that role.
Is this the right approach? Does it have any unintended consequences?

A:
Is this the right approach?

This is the correct approach, users with that role will only be able to perform CRUD operations on objects in the training schema and nothing else. This is the least privilege approach and is correct.
True least privilege would actually be assigning permissions to only the specific objects in that schema, but as you've indicated users should have access to all objects, then applying permissions schema-wide is appropriate.

I do not want them to have any other permissions on any other object
  outside that schema

You may not actually want this. Consider the public server role. For any object that does not have explicit permissions (GRANT or DENY), permissions are inherited from the public role for a user (any user, all users).
Since you cannot revoke public membership from a user, you would need to explicitly DENY permission on every single object just to prevent users from seeing the object listed in Management Studio - is this really necessary? They have no access beyond seeing the object exists, users still cannot interact with them.
Public access grants users, by default, nothing more than access to a few system catalog views to allow all users to view the name and definition of basic objects and some basic DB/Server info (see this article for more info).


text:
Q: Force all Kotlin Sealed classes to have a standard entry? I am investigating Kotlin Sealed Classes.
I wish to force all my Sealed classes to have a standard value of NO_OP.
for example:-
Sealed Class 1
sealed class Operation {
    object NO_OP: Operation()
    class Add(val value: Int) : Operation()
    class Substract(val value: Int) : Operation()
    class Multiply(val value: Int) : Operation()
    class Divide(val value: Int) : Operation()
}

Sealed Class 2
sealed class ScreenState {
    object NO_OP: ScreenState()
    class Error : ScreenState()
    class Loading : ScreenState()
    data class Data(val someData: SomeData) : ScreenState()
}

Is there any approach I can take that will force all sealed classes in separate files to
always specify the NO_OP value?

A: If you want force override it as a field for a certain sealed class:
sealed class ScreenState {
    abstract val NO_OP: ScreenState

    class Error : ScreenState() {
       override val NO_OP: ScreenState
          get() = TODO("Your implementation")
    }
}

If you need something like an interface:
sealed class ScreenState : NoOp<ScreenState> {
    override val NO_OP: ScreenState = Error()

    class Error : ScreenState()
}

interface NoOp<T> {
   val NO_OP: T
}

A: That seems not possible at the moment in the language.
However, we can move the NO_OP out from the sealed hierarchies and use Coproduct from the Arrow Library to define an ad-hoc sealed hierarchy:
import arrow.generic.coproduct2.Coproduct2

sealed class Operation {
    class Add(val value: Int) : Operation()
    class Substract(val value: Int) : Operation()
    class Multiply(val value: Int) : Operation()
    class Divide(val value: Int) : Operation()
}

object NO_OP

typealias Operations = Coproduct2<NO_OP, Operation>

Or we can fix one of the type parameters in Coproduct, and have:
typealias SomeThingWithNoOp<T> = Coproduct<NO_OP, T>

However, this is not ideal as it makes the hierarchy nested. With the top-level being Coproduct, and the nested level being the customized hierarchy.
This may be addressed with Arrow-Meta's union type plugin in the near future.

Another way of seeing the problem is treating NO_OP as the sentinel value. So we may encode NO_OP as null or None(From Arrow Option):
sealed class Operation {
    class Add(val value: Int) : Operation()
    class Substract(val value: Int) : Operation()
    class Multiply(val value: Int) : Operation()
    class Divide(val value: Int) : Operation()
}

typealias Operations = Operation?

import arrow.core.Option

sealed class Operation {
    class Add(val value: Int) : Operation()
    class Substract(val value: Int) : Operation()
    class Multiply(val value: Int) : Operation()
    class Divide(val value: Int) : Operation()
}

typealias Operations = Option<Operation>

From my experience, encoding it as nullable may be easier to use, as Kotlin has the nullable type support built-in. While encoding it as Option, Coproduct or defining NO_OP in each of the sealed hierarchies would make it more obvious(especially by using Coproduct or NO_OP in the sealed hierarchy).

Ref:

*

*Coproduct: https://0-9-0.arrow-kt.io/docs/generic/coproduct/

*Option: https://arrow-kt.io/docs/apidocs/arrow-core-data/arrow.core/-option/


text:
Q: GitKraken is not ignoring cache files in .gitignore The following is a snippet from my local .gitignore file:
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

Despite this, GitKraken detects hundreds of StyleCop cache files of the form:
a/b/c.d/StyleCop.Cache

as unstaged, new files in my project directory. Other Git tools like Git Bash and Visual Studio's built-in Git support are correctly ignoring the cache files and not ignoring directories that end in .Cache.
I've tried adding the line:
*.Cache

to the projects .git/info/exclude file and even added a global ignore file that my .gitconfig points to using the key core.excludesfile with the exclusion, but GitKraken still detects the StyleCop cache files. If I add the *.Cache pattern to the end of my local .gitignore file, then GitKraken ignores the files, but I am not in charge of the contents of the .gitignore file for this project and would need to make an argument for modifying it for a specific tool that only I am using.
How can I get GitKraken to ignore the .Cache files without modifying my local .gitignore file?

A: After exchanging some emails with Axosoft, I have a partial solution to the problem. Changing the exclusion pattern !*.[Cc]ache/ to !*.[Cc]ache/** appears to resolve the issue without adding special patterns for StyleCop to the .gitignore file, and without changing the behavior of other git tools.
It appears that the .gitignore file takes precedence over the .git/info/exclude file and global core.excludesfile option, so as long as the repository's .gitignore has the exclusion pattern, there isn't a way to override it, and the .gitignore must be modified.

A: I had to make these changes for GitKraken to understand my exclusions.
Broken in GitKraken (works elsewhere):
UWP/**/*

!UWP/MyApp/
!UWP/MyApp/*/

!UWP/MyApp/Assets/*
!UWP/MyApp/Package.appxmanifest

Fixed, works everywhere:
UWP/**
UWP/MyApp/**

!UWP/MyApp/Assets/*
!UWP/MyApp/Package.appxmanifest

A: Try deleting those files from your repository and look at your unstaged files inside of gitkraken. Sometimes they need to be 'reset' before the gitignore goes into effect.
Alternatively inside of gitkraken, on the far right window with the "unstaged files", you can right click the files you want to ignore and select ignore -> all files with extension .Cache


text:
Q: UIView doesn't scroll inside UIScrollView in vertical I have UIViewController. It has a UIView with three objects(UILabel, UIImageView, UITextView) inside UIScrollView. When I try scroll vertical nothing happens. I use autolayout. Before I made it without UIView inside UIScrollView but there is an empty space in the bottom.
@IBOutlet weak var scrollView: UIScrollView! {
    didSet {
        scrollView.delegate = self
        scrollView.scrollEnabled = true
        self.scrollView.frame.size = scrollView.contentSize //12
    }
}

A: if you are using auto layout no need to set the frame of scrollview, give your view which is subview of scrollview height constraint e.g. 800 and set scrollview and outer view width constraint to match the width for each device and set scrollview frame using autolayout, this will start scrolling.
refer this link for further details

A: The problem is that you're setting the scroll view's frame size to be equal to the scroll view's content size. A scroll view will only scroll if its content is larger than its frame. Instead, set the scroll view's frame size to match the container view's size, and set the content size's height to the bottom of the text view.

A: When we are using scrollview with auto layout it little bit confuting but it you see scroll view's behavioral then you will easily get idea about it.
for scrollview set constraint as 0 for four sides.
then check out the size of you view (which you added in scrollview) and set it to scrollview content size.
for view set equal weight constraint with scrollview width.
I hope it will help you.


text:
Q: Monte Carlo for Random Bond Ising ferromagnet The set-up:
Consider the Ising model on an $L \times L$ square lattice, where the coupling of each bond is chosen to be $+J$ (ferromagnetic) with probability $(1-p)$ and $-J$ (antiferromagnetic) with probability $p$.
For $p=0$ we have the standard Ising ferromagnet with two ground states (all up and all down). For $p \lesssim 0.11$ we will still have a ferromagnet, and the ground states still fall into the classification of 'mostly up' and 'mostly down', but there will be regions of opposing spins. These can take various different shapes while not changing the energy, and so introduce a large degeneracy into the ground state space. But the different shapes can be locally moved between by rotations of $O(1)$ spins at an $O(1)$ energy cost, so they are not like the deep wells of a spin glass.
The question:
Suppose we wish to calculate the thermal average of the energy at a temperature below the Curie temperature (and hence within the ferromagnetic phase). How many Monte Carlo steps are required to do this (equivalenlty: what is the autocorrelation time), assuming that we start in an initially random state? How much does it depend on the Monte Carlo used (such as Metropolis or Heat Bath, and with or without parallel tempering)?
Since energy only depends of the length of domain walls, and so doesn't care whether the system is in a 'mostly up' or 'mostly down' state, my intuition makes me think that it is not necessary to wait for the $\exp(L)$ required for the system to flip between these. So just local changes should be enough, and hence the autocorrelation should be polynomial at most. Is this true? Another issue is that the initially random state will be around 50% spin up and 50% spin down, and hence needs to break the symmetry to move towards a ground state. What is the time required to do this?
The background
There's a lot of statements out there in the literature about the feasibility of Monte Carlo studies in certain cases. They tell you that frustration (which this model has) is bad and will lead to inefficient Monte Carlo. They tell the same for spin glasses (which this model is at $T=0$ and high $p$, but not in the regime discussed above). But definitions of inefficiency seem to vary over time and between authors. For me it means higher than polynomial wih $L$. But for some people even polynomial scaling seems enough to claim inefficiency. It seems difficult to find a consistent overview of the issue. But this is a model that I have a particular interest in, and would really like to know at least what the autocorrelation time for the energy is.


text:
Q: Retrieving only firstname and surname of persons in DBpedia Hi I am newbie in using DBpedia and SPARQL. I want to retrieve firstname and lastname of all Norwegian persons that are stored on DBpedia like below:
Henrik Ibsen
Iver Fossum
etc.

Here is my query:
PREFIX      dbo:  <http://dbpedia.org/ontology/>
PREFIX  dbpedia:  <http://dbpedia.org/resource/>
SELECT ?person
WHERE
{ ?person  dbo:birthPlace  dbpedia:Norway
}

Thanks to all!

A: I would suggest using SPARQL to explore the properties.  Try the following to find which properties are most useful for your purposes:
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbpedia: <http://dbpedia.org/resource/>
SELECT ?person ?p ?o
WHERE{
   ?person dbo:birthPlace dbpedia:Norway .
   ?person ?p ?o .
   FILTER isLiteral(?o)
}

The FILTER is optional and used here to eliminate all of the type triples, etc. that probably aren't useful for this query.

A: Here you go:
PREFIX  dbo:  <http://dbpedia.org/ontology/>
PREFIX  dbpedia:  <http://dbpedia.org/resource/>

SELECT distinct ?firstname ?lastname WHERE {

?person dbo:birthPlace dbpedia:Norway .
?person foaf:givenName ?firstname .
?person foaf:surname ?lastname .

}


text:
Q: Saving Word2Vec for CNN Text Classification I want to train my own Word2Vec model for my text corpus. I can get the code from TensorFlow's tutorial. What I don't know is how to save this model to use for CNN text classification later? Should I use pickle to save it and then read it later?

A: You can use pickle to save it to disk. Then when you are creating the CNN model, load the saved word embedding table and use it to initialize the TensorFlow variable that holds the word embeddings for your CNN classifier.

A: No pickling is not the way of saving the model in case of tensorflow.
Tensorflow provides with tensorflow serving for saving the models as proto bufs(for exporting the model). The way to save model would be to save the  tensorflow session as:
             saver.save(sess, 'my_test_model',global_step=1000)
Heres the link for complete answer:
            Tensorflow: how to save/restore a model?


text:
Q: Keeping Address Info in PostgreSQL DB How can I integrate all valid addresses (such as city, street) belonging to a country into the database? (Except for manual insert)
I have created my city, street, country and etc. tables, but is it possible to pull this information from somewhere while filling them?


text:
Q: How to make a tkinter button open only one Toplevel? I need a tkinter button to open only one Toplevel
but I tried using a counter that changes to 2 when one Toplevel is made and a if loop so it checks if the counter is 1, (it will make a Toplevel window if its 1)
but when I run the program I can make many windows by clicking the button multiple times
I think the solution of using a counter doesn't work
    def menu_window(self): # this is in a class

    self.frame4 = tk.Frame(self.master, padx=30, pady=30)
    self.frame4.grid()

    Counter = 1  ### COUNTER
    button2 = tk.Button(self.frame4, text="Review your Quiz", command=lambda: PreviewQuiz(self.master, self.frame4,
                                                                                Counter))
    button2.grid(row=3, column=2, padx=40, pady=15, ipadx=28)
    button3 = tk.Button(self.frame4, text=" Start your Quiz ")
    button3.grid(row=4, column=2, padx=40, pady=5, ipadx=30)

class PreviewQuiz:
    def __init__(self, master, frame4, Counter):
        if Counter == 1:   # CHECK IF COUNTER IS 1
            self.master = master
            self.review_q = tk.Toplevel(self.master)
            self.frame5 = tk.Frame(self.master, padx=50, pady=20)
            self.frame5.grid()
            self.Counter = 2  # SET COUNTER TO 2

A: Just disable the button when the user clicks on it and enable it only when the top-level is closed.
Here is an example taken from the code you provided in your newest post:
import tkinter as tk

class Run:
    def __init__(self, master):

        self.master = master

        self.button = tk.Button(master, text="TopLevel", command=self.make_new)
        self.button.pack()

    def make_new(self):
        self.button['state'] = 'disabled'

        new = tk.Toplevel(self.master)

        lbl = tk.Label(new, text='only one topLevel')
        lbl.pack()

        new.protocol("WM_DELETE_WINDOW", lambda : self.button.configure(state='normal') or new.destroy()) # or make a method to change the state

master1 = tk.Tk()
i = Run(master1)
master1.mainloop()

A: Your code does not run, which makes it difficult to debug. There are however a few things:
When you assingn a value to counter in menu_window() you end the value with a ".", which makes it a float, not an integer.
You call PreviewQuiz with the counter argument, but when you update the counter you do it to an instance variable of PreviewQuiz, not of menu_window() class so next time you call PreviewQuiz you will still use 1.0.


text:
Q: Output PDF from database via PHP and display it via Javascript I'm trying to display a PDF file that I stored in my database as a BLOB file. Although I have tried a couple of ways I still can't seem to get it right.
Here is how I (try to) download a PDF file from my database:
function fillArrays(){
$idArray = array();
    $sql = "SELECT oglas_id,slika,prioriteta FROM deska WHERE deska.datumz <= CURRENT_DATE AND deska.datumk >= CURRENT_DATE;";
    $result = mysqli_query($GLOBALS['conn'],$sql);
    $resultCheck = mysqli_num_rows($result);
    if($resultCheck>0){
        while($row = mysqli_fetch_assoc($result)){
            array_push($GLOBALS['idArray'],$row['oglas_id']);
            $b64Doc = chunk_split(base64_encode(file_get_contents($row['slika']))); // THIS LINE!
            $file = "data:application/pdf;base64,".$b64Doc; // THIS LINE!
            array_push($GLOBALS['imgArray'],$file); // THIS LINE!
            array_push($GLOBALS['prArray'],$row['prioriteta']);
        }
    }else{
        die("Oops there seems to be an error(arr)");
    }
}

The code I've marked "THIS LINE!" should put all my PDF files from the database into an array of PDF files called $imgArray. Then I json_encode the array and assign it to the imgArray variable in JavaScript:
var imgArray = <?php echo json_encode($imgArray) ?>;

And finally, I try to display the same PDF file 4 times in a table created via JavaScript. (I call createTable() in main PHP file):
var idArray = window.idArray;
var imgArray = window.imgArray;
var prArray = window.prArray;

var screenH = screen.height/2.1;
var screenW = screen.width/2.1;

var tdW;
var tdH;

function createTables(){

    if(idArray.length>2){
        rows=2;
        cols=2;
        tdW='100%';
        tdH='100%';
    }else if(idArray.length==2){
        rows=1;
        cols=2;
        tdW='100%';
        tdH='100%';
    }else if(idArray.length==1){
        tdW='100%';
        tdH='100%';
    }

    var table = '';
    for(var r=0;r<rows;r++){
        table += '
';
        for(var c=0;c<cols;c++){
            table += '';
            table += '<embed src="'+imgArray[1]+'" type="application/pdf" style="max-height:'+screenH+';max-width:'+screenW+';">';
            table += '	';
        }
        table += '
';
    }
    document.write("
"+table+"
");
}

See at the bottom of the code where I try to embed the pdf file. Output on the site is this:

The language is Slovene and it says that the PDF file is corrupted.

A: You json_encode the data server-side but then don't call JSON.parse on the client-side. This means you are outputting JSON-encoded data directly into the


text:
Q: Using python modules in node.js Is it possible to create a glue that makes it possible for python modules (more specifically, library bindings) to be used in node.js? Some of the data structures can be directly mapped to V8 objects - e.g. array, dict.
More importantly - would that be a more elegant way to create bindings than manually or through FFI. In short, would it be worth it?

A: Try this node.js module, that is a bridge: Node-Python,
NOTE: The Project is 7 years old and still stuck at v0.4. A lot of functionality like converting between Python and Node arrays is still missing. It may be safe to assume that it's no longer supported by its original author(s)

A: Edge.js does a fine job at this. It allows you to write a Python script and then call the routines from Node.js, which can be used to easily create bindings with python modules.


text:
Q: JavaFX Blurry HBOX with CSS
css
   HBox:hover{
    -fx-background-color: rgba(0,0,0, .25);
    -fx-scale-x: 1.10px;
    -fx-scale-y: 1.10px;
    -fx-scale-z: 1.10px;
}

A little difficult to tell on the picture, but its pretty blurry to me when I scale it. How can I fix this? Applies to buttons as well, which I'm also trying to do it on.

A: I'm gonna go out on a limb and assume that the content is blurry and not the HBox itself since I can clearly see the crisp margin.
If you're scaling up any png, there will be a loss of detail based on how small the bitmap is.
It is a good idea to either have high res copies for small, medium and large icons and whatnot, or use a large image source which you scale down.
Also, useless scale increments such as 1.1px ... i mean... you want it to scale 1 pixel into 1.1 pixels? ... how would the monitor go about plotting that stuff? Pretty sure "px" shouldn't even be there since it's a discrete value, not a pixel reference.
Scaling stuff essentially multiplies it's dimension by a number... say you want to scale a 100x100 px box to 1.5 times it's size, it's scale would be 1.5 =----> 150x150px
Moreover, you should make sure that whatever you scale, the resulting dimensions should always be even, and failing that, never be anything else than an integer.
Say you want to plot 5.23556 pixels... the software will tell your monitor driver what the expected size shoul nd be............i.e............. ^--- that one ........ and the driver will do it's best to approximate that value somehow. It usually does this by combining colors and alpha values together in order to give off the illusion of antialising.
So to recap....

*

*scale LARGE bitmap images DOWN, not SMALL IMAGES UP. ... or use SVG.

*1.1px ??? look into that..

*1.1 scale is kind of wierd ... use 2.0, 3.0, 100.0 etc.


text:
Q: Showing that this map is a norm on $C[0,1]$ Consider $C[0,1]$, the vector space of continuous functions on the interval $[0,1]$ and consider the map $N:[0,1]\to\mathbb R$ where $$N(f)=\sup_{x\in[0,1]}x\cdot|f(x)|.$$
I was able to show the homogeneity and subadditivity of $N$, but I do not know how to prove that $f=0\iff N(f)=0$. I feel like this follows from continuity, but I do not know how to give a proper $\epsilon$-$\delta$ proof. Can someone help me out?

A: Assume that $N(f)=0$ for $f\colon [0,1]\to \Bbb R$ a continuous function. We get $xf(x)=0$ for all $x\in [0,1]$. In particular, for $x\neq 0$, this gives $f(x)=0$. Now, we have by continuity
$$f(0)=\lim_{n\to +\infty}f(n^{-1})=0$$
as $f(n^{-1})=0$ for each integer $n$.


text:
Q: Android SDK: How do you set the screen brightness I have been looking around and I could only find code that will set the brightness on that one Activity. I am trying to change the actual phone settings. The code I have tried is:
public class AutoPowerManagerActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            adjustBright();
        } catch (SettingNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void adjustBright() throws SettingNotFoundException {
        // TODO Auto-generated method stub
        int brightnessMode = Settings.System.getInt(getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE);
        if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            Settings.System.putInt(getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        }

        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.screenBrightness = 0.5F;
        getWindow().setAttributes(layoutParams);
    }
}

A: You can set the brightness back to automatic by setting by using following coding, its works for me.
layoutParams.screenBrightness=-1;
getWindow().setAttributes(layoutParams);

Here is the full coding:
public class MainActivity extends Activity {

WindowManager.LayoutParams layoutParams;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        adjustBright();
    } catch (SettingNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Button btn=(Button)findViewById(R.id.button1);

    btn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            layoutParams.screenBrightness=-1;
            getWindow().setAttributes(layoutParams);
        }
    });

}

private void adjustBright() throws SettingNotFoundException {
    // TODO Auto-generated method stub
    int brightnessMode = Settings.System.getInt(getContentResolver(),
            Settings.System.SCREEN_BRIGHTNESS_MODE);
    if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
        Settings.System.putInt(getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
    }

    layoutParams = getWindow().getAttributes();
    layoutParams.screenBrightness = 0.1F;
    getWindow().setAttributes(layoutParams);
}
}


text:
Q: Jquery pan svg image trouble I have an interactive map. I'm trying to create a script to zoom and pan. The script is working as long as there isn't any image in the SVG element. When I put an image inside it, it doesn't work anymore because it selects the image and drag it. How can I disable this?
Here is the jquery code :
$(function(){
    var mouseX;
    var mouseY;
    var originX;
    var originY;
    var dX = 0;
    var dY = 0;
    var clicking = false;

    $(document).mousemove(function(e){
       mouseX = e.pageX;
       mouseY = e.pageY;
    });

    $('#P1').on({
        mousemove: function(){
            if(clicking == true){
                dX = originX - mouseX;
                dY = originY - mouseY;
            }
        },
        mousedown: function(){
            clicking = true;
            originX = mouseX;
            originY = mouseY;
        },
        mouseup: function(){
            clicking = false;
            transX = $('#mapSVG').data('transx')+dX;
            transY = $('#mapSVG').data('transy')+dY;
            $('#mapSVG').data('transx',transX);
            $('#mapSVG').data('transy',transY);
            $('#mapSVG image').attr('transform','translate('+transX+','+transY+')');
            $('#mapSVG polygon').attr('transform','translate('+transX+','+transY+')');
        }
    }, '#mapSVG');
});

Here is the svg :
<svg id="mapSVG" height="800" width="800" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" data-transx="0" data-transy="0">';
    <image x="0" y="0" width="1600px" height="1600px" xlink:href="map.png" transform="translate(0,0"/>';
    <polygon points="703,600 704,593 711,588 722,581 739,574 753,571 769,576 771,583 774,586 785,585 790,595 791,607 781,610 780,615 782,624 769,631 751,636 739,640 737,635 721,640 712,633 706,624 704,613 " style="fill:lime; stroke:purple; stroke-width:1; opacity:0.3" transform="translate(0,0)"></polygon>
</svg>';

A: Assuming that the correct SVG would be
<svg id="mapSVG" height="800" width="800" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" data-transx="0" data-transy="0">
    <image x="0" y="0" width="1600px" height="1600px" xlink:href="http://upload.wikimedia.org/wikipedia/commons/a/a6/Provinces_of_Sicily_map.png" transform="translate(0,0)"/>
    <polygon id="P1" points="703,600 704,593 711,588 722,581 739,574 753,571 769,576 771,583 774,586 785,585 790,595 791,607 781,610 780,615 782,624 769,631 751,636 739,640 737,635 721,640 712,633 706,624 704,613 " style="fill:lime; stroke:purple; stroke-width:1; opacity:0.3" transform="translate(0,0)"></polygon>
</svg>

with corrected syntax and <polygon> with id "P1" (please edit the question accordingly if I'm right).
If #P1 isn't the polygon, my answer is no valid anymore. Eventually I'll iterate it.
I've done an apparently working pen, although the user story isn't 100% clear to me: http://codepen.io/pioneerskies/pen/qEegbV where the the only problem I can see is a wrong event delegation: you are delegating events to #P1 with target #mapSVG, but you can't delegate parent's event to one of its child nodes, because delegation will "watch" for events in descendants.
Official jQuery documentation about event delegation is at http://learn.jquery.com/events/event-delegation/


text:
Q: MEF Composition Error Because of Assembly Names? Thanks in advance for reviewing this question!
I am using MEF to load some assemblies in a project. Everything was working great until we changed the name of the file that contains the interface.
To make it clearer, I'll summarize the scenario where things worked, then the scenario where things did not work, then specifically show the exception and the code that caused the exception in the scenario that didn't work.
Here's the working scenario:
We've got an interface called IPlugin that is defined in an assembly called Common-1-0.dll.
We have some plugin assemblies that are compiled against Common-1-0.dll.
The application that loads the plugin is compiled against Common-1-0.dll.
Here's the non working scenario:
We've got this an called IPlugin that is defined in an assembly called Common-1-1.dll. The interface has not changed from Common-1-0.dll.
We have some plugin assemblies that are compiled against Common-1-0.dll.
The application that loads the plugin is compiled against Common-1-1.dll.
Now the issue:
When I go to run this code below in the second scenario, I get a CompositionException (shown under the code below). It appears to be caused because the the plugin was compiled against Common-1-0.dll while the application trying to do the composition was compiled against Common-1-1.dll. Nothing within the code has changed between the two files, just the name.
So we'd like to be able to load plugins built against whatever assembly so long as that assembly exports the right interface but I'm not sure if I can do that with MEF or not. That is what I'd like to know as a result of this question.
Code :
    private void LoadPlugins(string directory, string searchPattern = "", bool recursive = false)
    {
        Trace.Agent.Status("Loading plugin(s) from {0}{1}{2}", directory, Path.DirectorySeparatorChar, searchPattern);

        try
        {
            var directoryCatalog = string.IsNullOrEmpty(searchPattern)
                                           ? new DirectoryCatalog(directory)
                                           : new DirectoryCatalog(directory, searchPattern);
            _container = new CompositionContainer(new AggregateCatalog(directoryCatalog));

            _container.ComposeParts(this);
        }
        catch (CompositionException exc)
        {
            Trace.Agent.Exception(exc);
        }

        if (recursive)
        {
            foreach (string dir in Directory.GetDirectories(directory))
            {
                LoadPlugins(Path.Combine(directory, dir), recursive:true);
            }
        }
    }

CompositionException :
The export 'TestPlugin.TestPlugin (ContractName="Common.IPlugin")' is not assignable to type 'Common.IPlugin'.

A: I think I found a solution for your issue, it is a little bit hacked but anyways.
So if you have named your assemblies differently, e.g. assembly1.0 and assembly1.1 this causes issues because you cannot simply redirect the assembly to a new version.
Usually you would just keep the same assembly name and increase the version number. This way you can redirect without any issues (as long as the code supports it).
The solution is to hack into the assembly resolve mechanism by attaching to the AssemblyResolve event of the current AppDomain.
        AppDomain currentDomain = AppDomain.CurrentDomain;

        currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

        LoadPlugins(currentDomain.BaseDirectory);

        var x = _container.GetExport<IPlugin>().Value;

within the event handler you can simply return the "new" assembly
    private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
    {
        if (args.Name.StartsWith("PluginCore1.0"))
        {
            return typeof(IPlugin).Assembly;
        }
        return null;
    }

This works, also without signed assemblies (without public key tokens).
To trigger the resolve event you still have to define the assembly redirection within your app.config though:
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="PluginCore1.0"
                      culture="neutral" />

    <bindingRedirect oldVersion="1.0.0.0" newVersion="1.1.0.0" />
  </dependentAssembly>
</assemblyBinding>

Again, I would strongly recommend to use the same assembly name (without the version suffix) and simply use the assembly redirection mechanism which should work just fine.


text:
Q: How to use the header() function with POST? I've been trying to create a simple login script, but for some reason the header() function has not been working. For example, consider the below code:
<form method="POST">
    <input type="submit">
</form>

<?php
if($_POST)
{
    header("Location: www.example.com");
    die();
}
?>

For some reason, this does not work (when a POST type submit button is clicked).
Having googled this issue, I've come to find that you cannot use the header() function with POST - you must use GET. However, using GET causes a query string to be shown in the URL, and this is not desirable when submitting login data.
What is the solution to this issue?


text:
Q: Is there a way to import PST files into Outlook using C#? Using: Visual Studio 2017 (Language: C#)
I have a similar function written below in PowerShell script, but I need the C# version of it to execute on the click of a button within Visual Studio:
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application

$namespace = $outlook.GetNameSpace("MAPI")

dir "$env:userprofile\Documents\Outlook Files\*.pst" | % { $namespace.AddStore($_.FullName) }

Any insight or examples of code would be much appreciated.

A: You can do that the following way:
In your project, right click on "References" and add a reference to the assembly "Microsoft.Office.Interop.Outlook".
Then you can use the following code:
/// <summary>
/// Get a reference to an already running or a newly started Outlook instance
/// </summary>
Microsoft.Office.Interop.Outlook.Application GetOutlookApp()
{
    Microsoft.Office.Interop.Outlook.Application app = null;

    // Try to get running instance
    try
    {
        app = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
    }
    catch(Exception)
    {
        // Ignore exception when Outlook is not running
    }

    // When outlook was not running, try to start it
    if(app == null)
    {
        app = new Microsoft.Office.Interop.Outlook.Application();
    }

    return app;
}

private void button1_Click(object sender, EventArgs e)
{
    const string fileName = @"D:\MyDings.pst";

    var app = GetOutlookApp();
    var nameSpace = app.GetNamespace("MAPI");

    nameSpace.AddStore(fileName);

    MessageBox.Show("Done");
}

A: I'm not 100% sure if it is possible without extra packages. So I would just do a shell command executing the powershell script, since you already have that. Bit of a hack but seems the easiest option.
using System.Diagnostics;
Process.Start("powershell.exe " + scriptLocation);


text:
Q: @RenderBody() with canvas I have a canvas loaded onto the _Layout.cshtml
When I browse from the Index page, to About or Contact, the <canvas> is showing but the page content is missing.
Index page will load a div under  tag but About page is missing content.
I'm assuming @RenderBody isn't in the appropriate z-index or is not showing on top of <canvas> like my Index page does.
<canvas id="bgCanvas"></canvas>

    @RenderBody()

© @DateTime.Now

edit2:
under view source it shows
    <canvas id="bgCanvas"></canvas>

About.

Your application description page.

Use this area to provide additional information.

© 4/17/2015 11:33:17 AM - JTR

However I still can't see the content so it's underneath the canvas I believe. Which is weird since it is on top of the canvas on index.cshtml

A: Here is your answer: w3c canvas. Shortly, you must provide width and height properties for canvas element.
And remember to place the *.js file/code which is responsible for "drawing" after the canvas element.
Can you provide css code, so I'll be abe to edit this answer to be more specific?


text:
Q: Anything about $\prod_{n \ge 1} (1 + n^{-n})$? Sophomore's dream is especially the statement that the sum, let me call it $s$, of the (convergent) real series $\sum_{n \ge 1} n^{-n}$ is equal to the (improper) integral $\int_0^1 x^{-x} dx$. A few digits of the decimal representation of $s$ are recorded on the OEIS. A couple of days ago, a user of an Italian math forum asked for information about a multiplicative analogue of $s$, namely the constant $p := \prod_{n \ge 1} (1 + n^{-n}) \approx 2.60361$. After browsing through Finch's Mathematical Constants (Cambridge University Press, 2003), I couldn't find anything there about $p$, but on the other hand, I couldn't find anything about $s$ either. So I guess my question is:

Do you have any pointer to a piece of literature where $p$ pops up in connection to some (interesting) math?

A: Logarithm $\log p$ of this product is also some definite integral (not a surprise, any number is a definite integral of appropriate function), but the integrand is more sophisticated than $x^{-x}$.
Logarithm of your product equals
$$
\log p=\sum \log(1+n^{-n})=\sum_n \sum_k(-1)^{k-1} \frac{n^{-kn}}{k}=\sum_k \frac{(-1)^{k-1}}{k} c_k,
$$
where $$c_k:=\sum_{n\geq 1} n^{-kn}.$$
We have
$$
\int_0^1 x^a(-\log x)^bdx=\frac{b!}{(a+1)^{b+1}}.
$$
hence $$c_k=\int_0^1 \sum_n \frac1{(kn-1)!}x^n(-\log x)^{kn} dx=\int_0^1 x^{1/k}g_k(-x\log x) dx,$$
where $$g_k(t)=\sum \frac{t^{kn-1}}{(kn-1)!}=k^{-1}\sum_{w:w^k=1} we^{wt}.$$
Thus $$c_k=\frac1k\int_0^1x^{1/k} \sum_{w:w^k=1} w x^{-wx}.$$
Therefore $\log p=\int_0^1 g(x)dx$, where
$$
g(x)=\sum_{k,w:w^k=1} \frac{(-1)^{k-1}}{k^2}x^{1/k}wx^{-wx}.
$$
We may change order of summation, fixing $w=e^{2\pi ai/b}$ for coprime $a,b$. Then it arises for $k=b,2b,\dots$. We see that coefficient of $wx^{-wx}$ equals
$$
b^{-2}\sum_{k=1}^{\infty}(-1)^{kb-1} \frac{x^{\frac1{bk}}}{k^2}.
$$
I do not recognize this function, but maybe it may in turn be expressed via some generalized polylogarithms or whatever.


text:
Q: Composer: The checksum verification of the file failed I am hosting my own Satis repository via GitLab pages.
For some reason however, it keeps on erroring with The checksum verification of the file failed when composer tries to install one of the repositories.
Its happening on and off for a few weeks now, and I can't work out why its happening or how to debug it.
Here is my satis.json:
{
  "name": "Composer Repository",
  "homepage": "<snip>",
  "repositories": [
    {"type": "vcs", "url": "<snip>"},
    {"type": "vcs", "url": "<snip>"}
  ],
  "require-all": true,
  "require-dependencies": true,
  "archive": {
    "directory": "dist",
    "format": "zip",
    "skip-dev": true,
    "checksum": false
  }
}

I added checksum: false a week ago which seemed to fix the issue, but now it has just arrived again.
I've tried clearing caches and nothing is working. Any ideas?


text:
Q: Jquery, Onclick, and Ajax I have fiddled with this with absolutely no progress or luck. If I take out the .ajax it works fine but with the .ajax nothing fires, not even the random testing alerts. Can you see what I have done wrong with this? I have tried to follow the Jquery doc's. The PHP works.
<script type="text/javascript">
jQuery(document).ready(function ($) { // wait until the document is ready
$('div#chatroom').click(function(){
$.ajax({
    type: 'GET',
    url: 'chatget.php',
    data: { chatroomid: = '<?php echo $chatroomid; ?>'},
    datatype: 'html',
    cache: 'false',
    success: function(response) {
        $('#chatroom').append(response);
        alert('Load was performed.');
    },
    error: function(){
        alert('Fuuuuuuuuuuuuuu');
    }
}); // End Ajax

alert('Fail');

}); // End onclick
});

</script>

A: just loking at it ..  you have an extra = in data object
data: { chatroomid: = '<?php echo $chatroomid; ?>'},
              ------^^--- here

should be
 data: { chatroomid: '<?php echo $chatroomid; ?>'},

A: <script type="text/javascript">
jQuery(document).ready(function ($) { // wait until the document is ready
$('div#chatroom').click(function(){
$.ajax({
    type: 'GET',
    url: 'chatget.php',
    data: { chatroomid: '<?php echo $chatroomid; ?>'},
    datatype: 'html',
    cache: 'false',
    success: function(response) {
        $('#chatroom').append(response);
        alert('Load was performed.');
    },
    error: function(){
        alert('Fuuuuuuuuuuuuuu');
    }
}); // End Ajax

alert('Fail');

}); // End onclick
});

</script>

Can u try this code

A: Error seems here to me: an extra "="
chatroomid: = '<?php echo $chatroomid; ?>'},

I usually test code with jslint when have errors like this one


text:
Q: vue-tabs-component v-bind variable in suffix property He everyone! I have a vue js project and i installed a vue plugin called vue-tabs-component.
Link to repo: https://github.com/spatie/vue-tabs-component
It has an option to show a badge on a certain tab but my problem is that i do not know how to show the count variable into that component property.
So i have this piece of code:
<tabs><tab name="Expired" suffix="5">My tab content</tab></tabs>

How can i bind a dynamic variable in the suffix property.
suffix="5"

Instead of 5 i want to show a dynamic number.
How can i do that? Thank you in advance!

A: You could use string interpolation and pass the suffix property:
 :suffix="`<span class='suffix'>${suffix}</span>`"


text:
Q: Golang command working in terminal but not with exec package I am converting a video generation library from NodeJS to GO that primarily uses FFMPEG for all the video processing. I already have all the FFMPEG commands written out to do the generation I want. The issue is that when I try to run the command through the os/exec package, it fails. However, if I copy the exact command and run it directly in the terminal it works and I cannot figure out why that is. My code that runs the command is below:
command := "ffmpeg -y -loop 1 -i image.png -vf 'fade=in:0:15,fade=out:105:15' -c:v mpeg2video -t 5 -s 1280x720 -r 30 -q:v 1 -preset ultrafast image.mpg"

parts := strings.Fields(command)
cmd := exec.Command(parts[0], parts[1:]...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err := cmd.Run()
if err != nil {
    panic(err)
}

The ffmpeg error I get when I try to run this code is:

[AVFilterGraph @ 0x22a9bc0] No such filter: 'fade=in:0:15,fade=out:105:15'
Error opening filters!
2016/08/17 17:48:53 exit status 1

Like I previously stated, if I copy the EXACT command:
ffmpeg -y -loop 1 -i image.png -vf 'fade=in:0:15,fade=out:105:15' -c:v mpeg2video -t 5 -s 1280x720 -r 30 -q:v 1 -preset ultrafast image.mpg

and run it directly in the terminal, it works no problem.
PLEASE HELP.

A: When you are using strings.Fields(command), the fields are being split on spaces. This results in the parts slice containing a value 'fade=in:0:15,fade=out:105:15', with quotes. This complete value (with quotes) is being passed to the ffmpeg command, which the command is unable to recognize.
A shell would strip off these quotes and pass the string fade=in:0:15,fade=out:105:15 only which Go isn't doing. To fix, try:
// remove the quotes around fade=in:0:15,fade=out:105:15
command := "ffmpeg -y -loop 1 -i image.png -vf fade=in:0:15,fade=out:105:15 -c:v mpeg2video -t 5 -s 1280x720 -r 30 -q:v 1 -preset ultrafast image.mpg"

parts := strings.Fields(command)


text:
Q: RavenDB up multiple updates Is it possible to update multiple records in RavenDB - and do it in the database? I am trying to replace a particular property value in every document that's stored.

A: It is possible using the patch API. You'll find sample bulk-update operations in the docs.


text:
Q: Trying to create a generic mapper in mapstruct for all the fields with target and source as String I have this requirement in which for all the String -> String mappings, I need to check if the source string is empty and if it is I want to return null. I thought this would work but unfortunately doesn't
@Mapping(source = "in", target = ".", qualifiedByName = "stringConverter")
abstract String mapString(String in);

I thought this would generate a function like
String mapString(String in) {
    if ( in == null ) {
        return null;
    }

    String string = stringConverter(in);

    return string;
}

Or something similar. Here stringConverter just basically checks if the string is empty and returns null if so, else the original string. But in turn what I actually get is
String mapString(String in) {
    if ( in == null ) {
        return null;
    }

    String string = new String();

    return string;
}

Is it possible to create a generic function that handles mappings for all the string fields when using mapstruct?

A: MapStruct is meant for mapping beans and not for mapping between Strings.
You need to write a custom method for mapping between String and MapStruct will use that method.
public class StringConverter {

    public static String map(String value) {
        return (value == null || value.isEmpty()) ? null : value;
    }

}


text:
Q: Why this is an invalid regular expression? I am trying to match all UK phone numbers in a string.
The pattern for this is:
^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$
But when I try to initiate a new RegExp like:

const myRegex = RegExp('^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$','g');

I get this error:

Uncaught SyntaxError: Invalid regular expression: /^(?(?:(?:0(?:0|11))?[s-]?(?|+)44)?[s-]?(?(?:0)?[s-]?(?)?|0)(?:d{2})?[s-]?d{4}[s-]?d{4}|d{3})?[s-]?d{3}[s-]?d{3,4}|d{4})?[s-]?(?:d{5}|d{3}[s-]?d{3})|d{5})?[s-]?d{4,5}|8(?:00[s-]?11[s-]?11|45[s-]?46[s-]?4d))(?:(?:[s-]?(?:x|ext.?s?|#)d+)?)$/: Invalid group

A: The error already shows you what the problem is. \ inside a string literal is the escape character. But escaping a character that doesn't need to be escaped simply "drops" the \:

console.log('\(');

So the value you are passing to the regular expression engine (and what the error shows you) is:
^(?(?...

(note: no backslash)
and (?( is not a valid character sequence in a regular expression.
You either have to

*

*escape the escape characters ("\\(")

*Use a regular expression literal instead of RegExp("string") (/^.../).


text:
Q: Не получается настроить FTP Сервер FileZilla Пытаюсь настроить FTP Сервер через FileZilla 0.9.31
Открыл в роутере порты 21,990,3000-4000
Настроил DDNS(No-Ip)
SSL Сертификаты в FileZilla отключил(может это важно)
При попытке подключение через локальную сеть на сервере отображается следующее:
Connected, sending welcome message...
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> 220 Hello
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> AUTH TLS
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> 502 SSL/TLS authentication not allowed
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> AUTH SSL
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> 502 SSL/TLS authentication not allowed
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> USER Maxim
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> 331 Password required for maxim
(000005) 17.01.2022 14:45:18 - (not logged in) (192.168.1.160)> PASS ****
(000005) 17.01.2022 14:45:18 - maxim (192.168.1.160)> 230 Logged on
(000005) 17.01.2022 14:45:19 - maxim (192.168.1.160)> PWD
(000005) 17.01.2022 14:45:19 - maxim (192.168.1.160)> 257 "/" is current directory.
(000005) 17.01.2022 14:45:19 - maxim (192.168.1.160)> TYPE I
(000005) 17.01.2022 14:45:19 - maxim (192.168.1.160)> 200 Type set to I
(000005) 17.01.2022 14:45:19 - maxim (192.168.1.160)> PASV
(000005) 17.01.2022 14:45:19 - maxim (192.168.1.160)> 227 Entering Passive Mode (37,78,234,146,11,187)
(000005) 17.01.2022 14:45:19 - maxim (192.168.1.160)> MLSD
(000005) 17.01.2022 14:45:29 - maxim (192.168.1.160)> 425 Can't open data connection.

В клиенте отображается следующее:
Соединяюсь с 192.168.1.160:21...
Статус: Соединение установлено, ожидание приглашения...
Статус: Небезопасный сервер, не поддерживает FTP через TLS.
Статус: Авторизовались
Статус: Получение списка каталогов...
Команда:    PWD
Ответ:  257 "/" is current directory.
Команда:    TYPE I
Ответ:  200 Type set to I
Команда:    PASV
Ответ:  227 Entering Passive Mode (**,**,***,***,11,188) (Вместо звездочек здесь мой внешний IP)
Команда:    MLSD
Ошибка: Соединение передачи данных не может быть установлено: ECONNREFUSED - Соединение отклонено сервером
Ответ:  425 Can't open data connection.
Ошибка: Не удалось получить список каталогов

При попытке подключения не находясь в локальной сети(по внешнему ip или домену) сервер не видит попыток соеденения с ним, а в клиенте отображается слежующее:
Соединяюсь с **.**.***.***:21...
Статус: Не удалось установить соединение с "ECONNREFUSED - Соединение отклонено сервером".
Ошибка: Невозможно подключиться к серверу

Пробовал в консоли telnet 192.168.1.160 21 - подключение происходило и отображалось сообщение с сервера
Та же команда на внешний ip сбрасывала ошибку
Настройки в самом сервере следующие(3 скриншота ниже):
С чем это может быть связано и как пофиксить? Заранее огромное спасибо!


text:
Q: Synced Realm Separate vs Shared I am creating an IOS app where each user will have their own data that will not be shared with other users.  Should I create a separate realm for each user?  If I don't, and they only have permissions for their data will they still synch the entire shared realm even though they don't have access permissions for others data?  Or will it just synch what they are permissioned for?  If I create separate realms for each user is their any easy way to manage and look at size of individual realms.  Realm studio has very minimal capabilities.  Thanks.

A: Since the Realm Object Server only (currently) supports permissions on a per-Realm basis, you will need to create a separate Realm for each user if you don't want users to see each others' data.
If and when Realm Object Server does support object-level notifications, you could store multiple users' data in a single Realm and use partial synchronization to only sync down data pertinent to that specific user.
We are definitely interested in ways to improve Realm Studio; it will certainly be improved as we receive user feedback. If there are particular features you'd like to see please file an issue at our GitHub issue tracker.


text:
Q: How to query list of all directories with images in it, efficiently? I need to query MediaStore and get all the bucket names as a list. It is easy to do it and there is tons of questions with answer on stackoverflow however all of the answers are having one big efficiency problem. They all query all of the images to get a list of gallery. So if there is thousands of images in 10 directories, it takes too much time to query those only 10 directory names. I want to know if there is any better way to query those list of directories without querying all of the images.

A: Battle-tested code:
public void collectPhotosInFolder(File directory, boolean recurse, List<File> list) {
    Log.i(Constants.LOG_TAG, "Reading photos in file system folder " + directory.getAbsolutePath());

    File[] files = directory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            String name = file.getName();
            if (name.contains(".")) {
                String ext = name.substring(name.lastIndexOf('.') + 1);
                return ((ext.compareToIgnoreCase("jpg") == 0) || (ext.compareToIgnoreCase("jpeg") == 0) || (ext.compareToIgnoreCase("png") == 0));
            }
            return false;
        }
    });

    if (files == null)
        files = new File[0];

    for (File file : files)
        list.add(file);

    if (recurse) {
        File[] dirs = directory.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isDirectory();
            }
        });

        for (File dir : dirs)
            collectPhotosInFolder(dir, recurse, list);
    }
}


text:
Q: MySQL performance using where A simple query like the one below, properly indexed on a table populated with roughly 2M rows is taking 95 rows in set (2.06 sec) a lot longer to complete than I was hoping for.
As this is my first experience with tables this size, am I looking into normal behavior?
Query:
  SELECT t.id, t.symbol, t.feed, t.time,
         FLOOR(UNIX_TIMESTAMP(t.time)/(60*15)) as diff
    FROM data as t
   WHERE t.symbol = 'XYZ'
     AND DATE(t.time) = '2011-06-02'
     AND t.feed = '1M'
GROUP BY diff
ORDER BY t.time ASC;

...and Explain:
+----+-------------+-------+------+--------------------+--------+---------+-------+--------+----------------------------------------------+
| id | select_type | table | type | possible_keys      | key    | key_len | ref   | rows   | Extra                                        |
+----+-------------+-------+------+--------------------+--------+---------+-------+--------+----------------------------------------------+
|  1 | SIMPLE      | t     | ref  | unique,feed,symbol | symbol | 1       | const | 346392 | Using where; Using temporary; Using filesort |
+----+-------------+-------+------+--------------------+--------+---------+-------+--------+----------------------------------------------+

A: Try this:
...
AND t.time >= '2011-06-02' AND t.time < '2011-06-03'
...

Otherwise, your index(es) are wrong for this query. I'd expect one on (symbol, feed, time, id) or  (feed, symbol, time, id) to cover it.
Edit, after comment:
If you put a function or processing on a column, any index is liable to be ignored. The index is on x not f(x) basically.
This change allows the index to be used because we now do a <= x < y to ignore the time part, not takeofftime(x)