答:
You can join the table twice to get your desired data:</p>

```<code>SELECT T1.ID,
       T2.ZipCode AS FromZipCode,
       TT2.ZipCode AS ToZipCode --From the second Table2 (TT2)
From Table1 T1 JOIN Table2 T2 ON T1.FromAddress = T1.ID
     JOIN Table2 TT2 ON T1.ToAddress = TT2.ID --Join Table2 for the second time with another alias
</code>```

Title: Getting data from second table

Body:
You can join the table twice to get your desired data:

SELECT T1.ID,
       T2.ZipCode AS FromZipCode,
       TT2.ZipCode AS ToZipCode --From the second Table2 (TT2)
From Table1 T1 JOIN Table2 T2 ON T1.FromAddress = T1.ID
     JOIN Table2 TT2 ON T1.ToAddress = TT2.ID --Join Table2 for the second time with another alias


来源: stackexchange

问:
AirPlay service registered by `DNSServiceRegister` cannot be discovered by iOS 11
Multicast is disabled in our ethernet, so I registered proxy services (_airplay._tcp & _raop._tcp) pointed to Apple TV's IP with DNSServiceRegister in my app, register and detect the service on the same phone. It works fine in iOS 10, but my service can't be detected in Control Center in iOS 11.

答: When Apple changed around everything in iOS 11 (meaning AirPlay 2), they made it a tad more difficult for a device to Airplay to itself. You must use a much lower level API for this to work, by that I mean C instead of Objective-C. </p>

ContentLicense: CC BY-SA 3.0


问:
Models need to be changed when migration files are changed?
I'm very new to Rails, and currently for our class, we have to create an application with databases.

I have a bunch of tables that have foreign keys to other tables, and I've defined these associations in the migration files (using execute("ALTER TABLE...")), but not in my models (I only have self.primary_key defined in my models).

My question is, since I've set these associations in my migrations, do I also have to set the associations in my models (i.e. has_may, belongs_to, validates_uniqueness_of, etc)?

I'll be creating an app that would allow user input, and these input would be inserted to the database.

Hoping that my confusion can be cleared up. Thank you!

Example

Migration file:

```<code>class CreateSchools < ActiveRecord::Migration[5.0]
  def up
    create_table :schools, {:id => false} do |t|
      t.integer :school_id
      t.string :school_name
      t.string :contact_number
      t.integer :a_id

      t.timestamps
    end
    execute "ALTER TABLE schools ADD PRIMARY KEY(school_id);"
    execute "ALTER TABLE schools ADD CONSTRAINT a_id UNIQUE(a_id);"
    execute "ALTER TABLE schools ADD CONSTRAINT school_references_location FOREIGN KEY (a_id) REFERENCES locations(a_id) ON DELETE CASCADE ON UPDATE CASCADE;"
    change_column_null :schools, :school_name, false
    change_column_null :schools, :a_id, false
  end

  def down
    execute "ALTER TABLE schools DROP PRIMARY KEY;"
    execute "ALTER TABLE schools DROP FOREIGN KEY school_references_location;"
    execute "ALTER TABLE schools DROP INDEX a_id;"
    drop_table :schools
  end
end
</code>```

Model:

```<code>class School < ApplicationRecord
  self.primary_key = :school_id
end
</code>```

答:
Yes you'll need to define the associations in Model as well.

For all the rails applications,

Migrating and changing db according to associations is the first step.

Then add association statements in the models so that the associations from db can be accessed using simple methods. Like user.posts etc.

Adding association statements in Models provide you methods that generates queries according to the method called to retrieve data from db easily. You can also query db using join and select statements if you don't want to include association statements in Models.

So, in short, designing schema to manage associations is necessary where as mentioning them in Model is not. But we do it to make our life and code simpler.

Body:
I'm very new to Rails, and currently for our class, we have to create an application with databases.

I have a bunch of tables that have foreign keys to other tables, and I've defined these associations in the migration files (using execute("ALTER TABLE...")), but not in my models (I only have self.primary_key defined in my models).

My question is, since I've set these associations in my migrations, do I also have to set the associations in my models (i.e. has_may, belongs_to, validates_uniqueness_of, etc)?

I'll be creating an app that would allow user input, and these input would be inserted to the database.

Hoping that my confusion can be cleared up. Thank you!

Example

Migration file:

class CreateSchools < ActiveRecord::Migration[5.0]
  def up
    create_table :schools, {:id => false} do |t|
      t.integer :school_id
      t.string :school_name
      t.string :contact_number
      t.integer :a_id

      t.timestamps
    end
    execute "ALTER TABLE schools ADD PRIMARY KEY(school_id);"
    execute "ALTER TABLE schools ADD CONSTRAINT a_id UNIQUE(a_id);"
    execute "ALTER TABLE schools ADD CONSTRAINT school_references_location FOREIGN KEY (a_id) REFERENCES locations(a_id) ON DELETE CASCADE ON UPDATE CASCADE;"
    change_column_null :schools, :school_name, false
    change_column_null :schools, :a_id, false
  end

  def down
    execute "ALTER TABLE schools DROP PRIMARY KEY;"
    execute "ALTER TABLE schools DROP FOREIGN KEY school_references_location;"
    execute "ALTER TABLE schools DROP INDEX a_id;"
    drop_table :schools
  end
end

Model:

class School < ApplicationRecord
  self.primary_key = :school_id
end


问:
Will bokeh or plotly libraries work offline in a executable desktop application?
I'm trying to create an executable in python using either pyqt4 or tkinter and I want my GUI to be able to be interactive. I found bokeh and it seems like it can do everything I want.

However I was reading into bokeh and it seems that its main purpose is to make figures for embedding online using html. I'm not really familiar with html and I want my GUI to be able to pull up all the graphical data within my UI window rather than open an external link.

Is there a way to freeze my python scripts that utilize bokeh or plotly for a desktop application without embedding them online or using html?

答:
you can use for sure plotly offline:
e.g.:

```<code>import plotly
from plotly.graph_objs import Scatter, Layout

print(help(plotly.offline.plot))

plotly.offline.plot([Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-
graph.html')
</code>```

then save the plot in a html file and use this file in PyQt:
How do I rerender HTML PyQt4

Body:
you can use for sure plotly offline:
e.g.:

import plotly
from plotly.graph_objs import Scatter, Layout

print(help(plotly.offline.plot))

plotly.offline.plot([Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-
graph.html')

then save the plot in a html file and use this file in PyQt:
How do I rerender HTML PyQt4


问:
How can I store and query 50 million simple Python dicts?

Question

Each dict has a unique numeric id field but the rest are variable (all text or numeric values though). Some simple query functionality would be nice e.g. get where name contains 'abc' or where a < 123.

What are my options?

Setup

Python 2.6

32-bit Ubuntu-server 256MB

single machine

no swap

example dict:

```<code>{'id': 3823942, 'name': u'example', 'unknown_variable_key': u'foo'}
</code>```

Notes

can't use MongoDB: 32-bit MongoDB processes are limited to about 2.5 gb of data

can't use Redis because it needs the whole dataset in RAM

答:
Try using littletable.  It works with a list of objects, infers column names from object attributes, and supports simple query, join, and pivot table operations.  One of the nice things is that the results of query and join operations are new, full-fledged, queryable littletables.

littletable hasn't gotten a lot of attention or use yet, so I'd be very curious to hear your feedback/experience with it.

Body:
Question

Each dict has a unique numeric id field but the rest are variable (all text or numeric values though). Some simple query functionality would be nice e.g. get where name contains 'abc' or where a < 123.

What are my options?

Setup

Python 2.6

32-bit Ubuntu-server 256MB

single machine

no swap

example dict:

{'id': 3823942, 'name': u'example', 'unknown_variable_key': u'foo'}

Notes

can't use MongoDB: 32-bit MongoDB processes are limited to about 2.5 gb of data

can't use Redis because it needs the whole dataset in RAM

ContentLicense: CC BY-SA 2.5


问:
Clause group by if two lines return the maximum
My query is:

```<code>SELECT ID,B,C,D, SUM(X), SUM(Y)
FROM TABLE
GROUP BY A,B,C,D
</code>```

But if the query returns 2 lines with the same id, I want take only one line which have the max of column D.

For example if the query returns:

```<code>+----+---+---+---+--------+--------+
| ID | B | C | D | SUM(X) | SUM(Y) |
+----+---+---+---+--------+--------+
| 2  | 1 | 1 | 1 | 70     | 100    |
| 2  | 1 | 1 | 3 | 100    | 150    |
+----+---+---+---+--------+--------+
</code>```

Then drop the line with D=1, and keep only the line with D=3

答:
If you want one row per id, then that should be the only column in the group by:

```<code>SELECT ID, SUM(X), SUM(Y)
FROM TABLE
GROUP BY ID;
</code>```

Body:
My query is:

SELECT ID,B,C,D, SUM(X), SUM(Y)
FROM TABLE
GROUP BY A,B,C,D

But if the query returns 2 lines with the same id, I want take only one line which have the max of column D.

For example if the query returns:

+----+---+---+---+--------+--------+
| ID | B | C | D | SUM(X) | SUM(Y) |
+----+---+---+---+--------+--------+
| 2  | 1 | 1 | 1 | 70     | 100    |
| 2  | 1 | 1 | 3 | 100    | 150    |
+----+---+---+---+--------+--------+

Then drop the line with D=1, and keep only the line with D=3

Body:
If you want one row per id, then that should be the only column in the group by:

SELECT ID, SUM(X), SUM(Y)
FROM TABLE
GROUP BY ID;


问:
Node Property key relations Neo4j
I have somewhat of a noob question. Im trying to create relations between node property keys, but can't seem to to get my query right.

The node contains two keys: source and destination.

```<code>{
  "dst": "192.168.XX.XX",
  "src": "192.168.XX.XX"
}
</code>```

I need to create a graph where the scr -> dst.

```<code>MATCH (n:IOC)
RETURN (n)-[*]->(n);
</code>```

But is not working, any pointers tips or tricks appreciated.

答:
I don't know if I understood your question completely, but I think you are trying to create a relationship between n1 and n2 when n1.src = n2.dst. You can do it using:

```<code>MATCH (n1:IOC), (n2:IOC)
WHERE n1.src = n2.dst
CREATE (n1)-[:RELATIONSHIP_TYPE]->(n2)
</code>```

Title: Node Property key relations Neo4j

Body:
I have somewhat of a noob question. Im trying to create relations between node property keys, but can't seem to to get my query right.

The node contains two keys: source and destination.

{
  "dst": "192.168.XX.XX",
  "src": "192.168.XX.XX"
}

I need to create a graph where the scr -> dst.

MATCH (n:IOC)
RETURN (n)-[*]->(n);

But is not working, any pointers tips or tricks appreciated.

Body:
I don't know if I understood your question completely, but I think you are trying to create a relationship between n1 and n2 when n1.src = n2.dst. You can do it using:

MATCH (n1:IOC), (n2:IOC)
WHERE n1.src = n2.dst
CREATE (n1)-[:RELATIONSHIP_TYPE]->(n2)


问:
create file with FileStream and apply FileAttributes
Is it possible while creating the file with FileStream also apply FileAttributes at the same time? I would like to create file for stream writing with FileAttributes.Temporary file attribute.</p>

答:
You can do this if you use the Win32 CreateFile method

```<code>uint readAccess = 0x00000001;
uint writeAccess = 0x00000002;

uint readShare = 0x00000001;

uint createAlways = 2;

uint tempAttribute = 0x100;
uint deleteOnClose = 0x04000000;

new FileStream(new SafeFileHandle(NativeMethods.CreateFile("filename",
                                                           readAccess | writeAccess,
                                                           readShare,
                                                           IntPtr.Zero,
                                                           createAlways,
                                                           tempAttribute | deleteOnClose,
                                                           IntPtr.Zero),
                                  true),
               FileAccess.ReadWrite, 4096, true);

private static class NativeMethods
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern IntPtr CreateFile(string name, uint accessMode, uint shareMode, IntPtr security, uint createMode, uint flags, IntPtr template);
}
</code>```

For more information, see the MSDN documentation of CreateFile

Body:
You can do this if you use the Win32 CreateFile method

uint readAccess = 0x00000001;
uint writeAccess = 0x00000002;

uint readShare = 0x00000001;

uint createAlways = 2;

uint tempAttribute = 0x100;
uint deleteOnClose = 0x04000000;

new FileStream(new SafeFileHandle(NativeMethods.CreateFile("filename",
                                                           readAccess | writeAccess,
                                                           readShare,
                                                           IntPtr.Zero,
                                                           createAlways,
                                                           tempAttribute | deleteOnClose,
                                                           IntPtr.Zero),
                                  true),
               FileAccess.ReadWrite, 4096, true);

private static class NativeMethods
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern IntPtr CreateFile(string name, uint accessMode, uint shareMode, IntPtr security, uint createMode, uint flags, IntPtr template);
}

For more information, see the MSDN documentation of CreateFile


问:
I am trying to do some simple hibernate program but i am getting error. Could you help some one?
Error:

EmployeePOJO.hbm.xml :

hibernate.cfg.xml :

ManageEmployee :

答:
If EmployeePOJO.hbm.xml file is in hibernate.project.test package, then in hibernate.cfg.xml you should provide the mapping as:

```<code><mapping resource="hibernate/project/test/EmployeePOJO.hbm.xml" />
</code>```

Body:
If EmployeePOJO.hbm.xml file is in hibernate.project.test package, then in hibernate.cfg.xml you should provide the mapping as:

<mapping resource="hibernate/project/test/EmployeePOJO.hbm.xml" />


问:
Is it possible to use Spring to create a console application?
Currently researching this topic. Is it possible to use the benefits of Spring to form a Console application? I mean, with scopes, autowiring and etc(found a bunch of examples of a basic "Set the context, init and go", but nothing more)?

Can't find any tutorials or helpful information on this topic.

答:
Spring is a framework which offers the dependency injection mechanism. It also supports segregation of service layer, web layer, and business layer but I believe that this is not what you want.

So the answer is yes. You can utilize the dependency injection service that provides in order to create a console application without facing any problems. Of course, the MVC model that offers is actually useless for you.


问:
Website loses css content when hosted on linux server
I have a website that is primarily html5 and css3, and the pages look good when I run them locally from my pc on chrome and internet explorer 11.0.47, but when I put it on the Linux server and run the page from there on my own pc, the page loses the css in IE but is fine in chrome.

I don't have a lot of experience with html5/css3.  What's going on here?  I tried googling it, but don't see any online help.

The web page is start of web site.  As you can see, in IE, Map Home isn't shown as a button in nav to the left, and nav lost it's brown background.  It also lost the header background.  If you look at the link in chrome, it has those.

Any ideas? Could there be a directional issue with use of the media folder when IE pulls it from Linux but not chrome?

**Added:
I see this on the server log, but when I list the location on the server, the file exists there. The css file (catvStyles.css) referring to the globe file is in the same dir as index.html, and the media dir is in the dir of index.html.

File does not exist:
  /opt/apps/html/catv/media/globe_transp_gradation.png), url(..,
  referer: http://ltrkarkvm391.mgmt.windstream.net/catv/index.html

**
This looks similar to other web page if you can't reach the link. The problem is my linux hosted site isn't showing the brown nav to the left, it's not showing the metal header globe, and windmill pictures, and it's not showing Map Home in a button (it's as a link without the button), and it's not showing the picture in the right side to the right (it's in the body now).

This is the index.html page:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<link type="text/css" rel="stylesheet" href="FunStuff/catvStyles.css">
<title>CATV Monitoring</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Wi">
<meta name="keywords" content="catv, cmts, snmp, modem, dhcp, rf, status, map">
<meta name="author" content="Wi, Michele, Adam">

<style type="text/css">

</style>
<!--[if lt IE 9]>
   <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"> </script>
<![endif]-->
</head>
<body>
<div id="wrapper">
  <header role="banner" class="bgFun">
    <h1>Wi</h1>
    <h2 id="headerH2Pos">CATV Monitoring System</h2>
  </header>
  <div id="page">
  <nav role="navigation" id="navBakImg">
    <ul>
     <li><a href="FunStuff/ClusterMap.html">Map Home</a></li> <!--MapHome.html-->

    </ul>
   </nav>

   <main role="main" id="middle">
    <h2>Purpose</h2>
    <p>To provide CATV Monitoring to our internal customers</p>
     </p>
    <h2>Mapping </h2>
    <p>Click the "Map Home" link on the left to see how the network is doing </p>
    <img class="imgFix" src="media/WIN_Vert_Green_Logo.png"  height:"18" width:"15" alt="Logo" title="Wi" >
     </p>
    </main>
    <aside role="complementary">
      <img class="imgFix" src="media/WIN_Vert_Green_Logo.png"  height:"18" width:"15" alt="Logo" title="Wi" >
     <h2>How To Start</h2>
     <p>See directions</p>
   </aside>
   </div> <!-- end of flex container -->
   <footer role="contentinfo">
      <a href="https://www.linkedin.com/in/michele" target="_blank"><img class="tree" src="media/Tree_Branches_And_Roots_clip_art_small.png"  height="50" width="50" alt="Tree" title="Created by Michele " ></a>
      <br>Copyright © 2017
      <script>
        document.write('Last Modified: ' + document.lastModified);
      </script>
  <br>

   </footer>
</div>
</body>
</html>
</code>```

This is the css catvStyles.css:

```<code>body {font-family: Verdana, Arial, sans-serif;
      background-color: #330000;
      background-image: url(../media/green.gif);

}
#middle{}
header, h1, wrapper { margin-top: 0; }
#wrapper {  background-color: #F4E8BC;
            /*background-color: #00ffff;*/
            width: 90%;
            margin: auto;
            color: #003300;/*color: #330000;*/

}
h1, h2 { color: #003300; }
header {
         background-repeat: no-repeat;
        background-color:transparent;
}
.bgFun{background-image: url(../media/globe_transp_gradation.png),
         url(../media/windmill_transp_gradation.png),url(../media/MetalGalvanized0014_M.jpg);
         background-position: left, right;
         /*width: 80%;
         height:80%;*/
         background-size:45%,30%,cover;
         background-repeat:no-repeat;
         background-color:transparent;}
h1 { text-align: center;
      font-size: 300%;
     padding: 5% 0;
     text-shadow: 3px 3px 3px #F4E8BC;
}
nav, main, aside {  padding: 0 1em;
}
.imgFix { width: 25%;
      height: auto;
}
nav ul { list-style-type: none;
         font-size: 1.2em;
         padding-left: 0;
}
/*nav a { text-decoration: none;}*/
nav a {
   text-decoration: none;
   background-color: #666666;
   display:block;
   text-align:center;
   width:100%;
   margin:1em auto;
   border:solid .08em #339900
}
nav a:link { color: #330000; }
nav a:visited { color: #003300; }
nav a:hover { color: #996600;
              background-color:#000000;}
footer { text-align: center;
         font-size: 80%;
         font-style: italic;
         color: #003300;
         padding: 2.5%;
}
#page{display: -webkit-flex;
      display: flex;
      -webkit-flex-direction: row;
      flex-direction: row;
}
#navBakImg{border: .1em solid #000000;
    padding-right:1em;
    background-image: url(../media/CardboardPlain0016_2_M.jpg);
    font-size:90%;}
nav{-webkit-flex: 1;
    flex: 1;
}
main{-webkit-flex: 7;
     flex:7;
}
aside{-webkit-flex: 2;
      flex: 2;
}
.tree { width:3em;
        height: auto;
        float:right;}

@media only screen and (max-width: 1024px) {
            body { margin: 0; padding: 0; }
            #wrapper { width: auto; margin: 0; }
            h1 { font-size: 200%; }
            nav li { padding: 0 0.5em;
                     font-size: 1.2em;
                    }
        #page{-webkit-flex-direction: column;
                  flex-direction: column;
            }
            nav ul{display: -webkit-flex;
                   display: flex;
                   -webkit-flex-direction: row;
                   flex-direction: row;
                   webkit-justify-content: center;
                   justify-content: center;
            }
            .imgFix { width: 30%;
            height: auto;}

}
@media only screen and (max-width: 768px) {
            nav{-webkit-order: 1;
                order: 1;
            }
            nav ul{-webkit-flex-wrap: wrap;
                   flex-wrap: wrap;
            }
            section{display:none;}
            .imgFix { width: 35%;
            height: auto;}
}
header, main, nav, footer, figure, figcaption { display: block; }
#headerH2Pos{position:relative;
             left:26%;
             }
</code>```

答:
I had to add this line and it was fixed:</p>

```<code><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</code>```

Body:
I have a website that is primarily html5 and css3, and the pages look good when I run them locally from my pc on chrome and internet explorer 11.0.47, but when I put it on the Linux server and run the page from there on my own pc, the page loses the css in IE but is fine in chrome.

I don't have a lot of experience with html5/css3.  What's going on here?  I tried googling it, but don't see any online help.

The web page is start of web site.  As you can see, in IE, Map Home isn't shown as a button in nav to the left, and nav lost it's brown background.  It also lost the header background.  If you look at the link in chrome, it has those.

Any ideas? Could there be a directional issue with use of the media folder when IE pulls it from Linux but not chrome?

**Added:
I see this on the server log, but when I list the location on the server, the file exists there. The css file (catvStyles.css) referring to the globe file is in the same dir as index.html, and the media dir is in the dir of index.html.

File does not exist:
  /opt/apps/html/catv/media/globe_transp_gradation.png), url(..,
  referer: http://ltrkarkvm391.mgmt.windstream.net/catv/index.html

**
This looks similar to other web page if you can't reach the link. The problem is my linux hosted site isn't showing the brown nav to the left, it's not showing the metal header globe, and windmill pictures, and it's not showing Map Home in a button (it's as a link without the button), and it's not showing the picture in the right side to the right (it's in the body now).

This is the index.html page:

<!DOCTYPE html>

<link type="text/css" rel="stylesheet" href="FunStuff/catvStyles.css">
<title>CATV Monitoring</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Wi">
<meta name="keywords" content="catv, cmts, snmp, modem, dhcp, rf, status, map">
<meta name="author" content="Wi, Michele, Adam">

Wi

CATV Monitoring System

Map Home

Purpose

To provide CATV Monitoring to our internal customers

Mapping

Click the "Map Home" link on the left to see how the network is doing

How To Start

See directions

Copyright © 2017

This is the css catvStyles.css:

body {font-family: Verdana, Arial, sans-serif;
      background-color: #330000;
      background-image: url(../media/green.gif);

}
#middle{}
header, h1, wrapper { margin-top: 0; }
#wrapper {  background-color: #F4E8BC;
            /*background-color: #00ffff;*/
            width: 90%;
            margin: auto;
            color: #003300;/*color: #330000;*/

}
h1, h2 { color: #003300; }
header {
         background-repeat: no-repeat;
        background-color:transparent;
}
.bgFun{background-image: url(../media/globe_transp_gradation.png),
         url(../media/windmill_transp_gradation.png),url(../media/MetalGalvanized0014_M.jpg);
         background-position: left, right;
         /*width: 80%;
         height:80%;*/
         background-size:45%,30%,cover;
         background-repeat:no-repeat;
         background-color:transparent;}
h1 { text-align: center;
      font-size: 300%;
     padding: 5% 0;
     text-shadow: 3px 3px 3px #F4E8BC;
}
nav, main, aside {  padding: 0 1em;
}
.imgFix { width: 25%;
      height: auto;
}
nav ul { list-style-type: none;
         font-size: 1.2em;
         padding-left: 0;
}
/*nav a { text-decoration: none;}*/
nav a {
   text-decoration: none;
   background-color: #666666;
   display:block;
   text-align:center;
   width:100%;
   margin:1em auto;
   border:solid .08em #339900
}
nav a:link { color: #330000; }
nav a:visited { color: #003300; }
nav a:hover { color: #996600;
              background-color:#000000;}
footer { text-align: center;
         font-size: 80%;
         font-style: italic;
         color: #003300;
         padding: 2.5%;
}
#page{display: -webkit-flex;
      display: flex;
      -webkit-flex-direction: row;
      flex-direction: row;
}
#navBakImg{border: .1em solid #000000;
    padding-right:1em;
    background-image: url(../media/CardboardPlain0016_2_M.jpg);
    font-size:90%;}
nav{-webkit-flex: 1;
    flex: 1;
}
main{-webkit-flex: 7;
     flex:7;
}
aside{-webkit-flex: 2;
      flex: 2;
}
.tree { width:3em;
        height: auto;
        float:right;}

@media only screen and (max-width: 1024px) {
            body { margin: 0; padding: 0; }
            #wrapper { width: auto; margin: 0; }
            h1 { font-size: 200%; }
            nav li { padding: 0 0.5em;
                     font-size: 1.2em;
                    }
        #page{-webkit-flex-direction: column;
                  flex-direction: column;
            }
            nav ul{display: -webkit-flex;
                   display: flex;
                   -webkit-flex-direction: row;
                   flex-direction: row;
                   webkit-justify-content: center;
                   justify-content: center;
            }
            .imgFix { width: 30%;
            height: auto;}

}
@media only screen and (max-width: 768px) {
            nav{-webkit-order: 1;
                order: 1;
            }
            nav ul{-webkit-flex-wrap: wrap;
                   flex-wrap: wrap;
            }
            section{display:none;}
            .imgFix { width: 35%;
            height: auto;}
}
header, main, nav, footer, figure, figcaption { display: block; }
#headerH2Pos{position:relative;
             left:26%;
             }

Body:
I had to add this line and it was fixed:

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">


问:
How to prevent "0" as the first character and limit number of characters allowed in UITextField using Swift?
I want to achieve following:

Have a decimal keypad. Which means user will be able to enter Double
values. (Needless to say "." will be limited one)

Prevent "0" characters as the first characters. (i.e.: There should
not be values like "003" "01" "000012" etc.)

Limit the character count to 10.

Only allow numbers. No Copy-Paste text values.

I am using decimal keypad. Below code handles first and third item above:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return newString.count <= 10
}
</code>```

Thank you for your time.

答:
Bellow code will check all conditions you have specified</p>
```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    //Prevent "0" characters as the first characters. (i.e.: There should not be values like "003" "01" "000012" etc.)
    if textField.text?.count == 0 && string == "0" {

        return false
    }

    //Limit the character count to 10.
    if ((textField.text!) + string).count > 10 {

        return false
    }

    //Have a decimal keypad. Which means user will be able to enter Double values. (Needless to say "." will be limited one)
    if (textField.text?.contains("."))! && string == "." {

        return false
    }

    //Only allow numbers. No Copy-Paste text values.
    let allowedCharacterSet = CharacterSet.init(charactersIn: "0123456789.")
    let textCharacterSet = CharacterSet.init(charactersIn: textField.text! + string)
    if !allowedCharacterSet.isSuperset(of: textCharacterSet) {
        return false
    }
    return true
}
</code>```

Body:
I want to achieve following:

Have a decimal keypad. Which means user will be able to enter Double
values. (Needless to say "." will be limited one)

Prevent "0" characters as the first characters. (i.e.: There should
not be values like "003" "01" "000012" etc.)

Limit the character count to 10.

Only allow numbers. No Copy-Paste text values.

I am using decimal keypad. Below code handles first and third item above:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return newString.count <= 10
}

Thank you for your time.

Body:
Bellow code will check all conditions you have specified

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    //Prevent "0" characters as the first characters. (i.e.: There should not be values like "003" "01" "000012" etc.)
    if textField.text?.count == 0 && string == "0" {

        return false
    }

    //Limit the character count to 10.
    if ((textField.text!) + string).count > 10 {

        return false
    }

    //Have a decimal keypad. Which means user will be able to enter Double values. (Needless to say "." will be limited one)
    if (textField.text?.contains("."))! && string == "." {

        return false
    }

    //Only allow numbers. No Copy-Paste text values.
    let allowedCharacterSet = CharacterSet.init(charactersIn: "0123456789.")
    let textCharacterSet = CharacterSet.init(charactersIn: textField.text! + string)
    if !allowedCharacterSet.isSuperset(of: textCharacterSet) {
        return false
    }
    return true
}

ContentLicense: CC BY-SA 4.0


问:
How to automatically populate a 5x3x2 array with natural numbers from zero to the array's full size?
I need to populate a 3D array automatically, using natural positive numbers (0,1,2,3,4...), up to the array's full dimension. In this case, a 5x3x2 array stores 30 elements. Is there any algorithm, where for-loops could be employed to dynamically populate such array? For example: if I had a 5x3 2D array, I certainly could use the following code, to automatically generate its elements:

```<code>var ray = new Array(5);
for (var make2D = 0; make2D < ray.length; make2D++) {
    ray[make2D] = new Array(3);
}
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        array[i][j] = i * array[i].length + j;
    }
}
</code>```

The above code would first create a 5 x 3 array and populate this 2D array with elements from 0 to 14.
But, I have struggled to find a 'formula' to populate a 3D array likewise

Like explicit: array[ i ] [ j ] [ z ]= '.....code.....'  using length property values and for-loops?

答:
To populate your array you can use the folowing:</p>

```<code>let x = 1

for (let i = 0; i < myArray.length; i++){
  for (let j = 0; j < myArray[i].length; j++){
    for (let k = 0; k < myArray[i][j].length; k++){
      array[i][j][k] = x++ ;
    }
  }
}
</code>```

Body:
I need to populate a 3D array automatically, using natural positive numbers (0,1,2,3,4...), up to the array's full dimension. In this case, a 5x3x2 array stores 30 elements. Is there any algorithm, where for-loops could be employed to dynamically populate such array? For example: if I had a 5x3 2D array, I certainly could use the following code, to automatically generate its elements:

var ray = new Array(5);
for (var make2D = 0; make2D < ray.length; make2D++) {
    ray[make2D] = new Array(3);
}
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        array[i][j] = i * array[i].length + j;
    }
}

The above code would first create a 5 x 3 array and populate this 2D array with elements from 0 to 14.
But, I have struggled to find a 'formula' to populate a 3D array likewise

Like explicit: array[ i ] [ j ] [ z ]= '.....code.....'  using length property values and for-loops?

Body:
To populate your array you can use the folowing:

let x = 1

for (let i = 0; i < myArray.length; i++){
  for (let j = 0; j < myArray[i].length; j++){
    for (let k = 0; k < myArray[i][j].length; k++){
      array[i][j][k] = x++ ;
    }
  }
}


问:
Function with input type double in classdef
I am starting with oop in Matlab and seem to miss something.

```<code>classdef car < handle

properties (Access = public)
    a
    b
end

methods
    function obj = update(obj)
        obj.b = updateB(obj.a, obj.b);
    end

    function B = updateB(a, b)
        B = a + b;
    end
end

end
</code>```

I get the famous Undefined function 'updateB' for input arguments of type 'double'. error every time, I try to call the function update. Oddly, it works if I change updateB to:

```<code>function B = updateB(obj)
    B = obj.a + obj.b;
end
</code>```

What am I missing? I do not always want to call updateB with obj, because I want to use the function without using the actual object's properties.

答:
When, if you don't want the method to rely on a specific instance, use this approach:</p>

```<code>methods
    function obj = update(obj)
        obj.b = car.updateB(obj.a, obj.b);
    end
end

methods (Static)
    function B = updateB(a, b)
        B = a + b;
    end
end
</code>```

Body:
I am starting with oop in Matlab and seem to miss something.

classdef car < handle

properties (Access = public)
    a
    b
end

methods
    function obj = update(obj)
        obj.b = updateB(obj.a, obj.b);
    end

    function B = updateB(a, b)
        B = a + b;
    end
end

end

I get the famous Undefined function 'updateB' for input arguments of type 'double'. error every time, I try to call the function update. Oddly, it works if I change updateB to:

function B = updateB(obj)
    B = obj.a + obj.b;
end

What am I missing? I do not always want to call updateB with obj, because I want to use the function without using the actual object's properties.

Body:
When, if you don't want the method to rely on a specific instance, use this approach:

methods
    function obj = update(obj)
        obj.b = car.updateB(obj.a, obj.b);
    end
end

methods (Static)
    function B = updateB(a, b)
        B = a + b;
    end
end


问:
How to get the environment variable from local using @Value in spring?
I set a key inside my environment (in bash_profile file) called 'FLAG'(the value is 'true'). I'm trying to get his value by using annotation Value.
so far i tried to do this:

```<code>@Value("\${FLAG}")
 private lateinit var process_flag: String
</code>```

but no success, I'm getting an error:

```<code>java.lang.IllegalArgumentException: Could not resolve placeholder 'FLAG' in string value "${FLAG}"
</code>```

*should I add any import\annotation to the class?

答: Solution: maybe it will sound funny but the solution for me was to turn off and on the intellij, of course after declare the environment variable.

Body:
I set a key inside my environment (in bash_profile file) called 'FLAG'(the value is 'true'). I'm trying to get his value by using annotation Value.
so far i tried to do this:

@Value("\${FLAG}")
 private lateinit var process_flag: String

but no success, I'm getting an error:

java.lang.IllegalArgumentException: Could not resolve placeholder 'FLAG' in string value "${FLAG}"

*should I add any import\annotation to the class?


问:
Can I make a constructor that deserializes a string version of my object?
I'm serializing and deserializing an object (TComponent descendant) using the example in the ComponentToString section in the Delphi help file.  This is so I can store the object in a VARCHAR field in the database.

When I need to instantiate a new instance of my class from a string stored in the database, can I do that using a constructor of the form CreateFromString(AOwner: TComponent; AData: String)?  Or do I have to use a non-class method that returns an instance of my component class?

If I can use the constructor version, how to I "map" the return value of ReadComponent to the "self" that is being created by the constructor?

Here's the deserialization example from the help file:

```<code>function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;
</code>```

答:
Use a static class function instead of a constructor:

```<code>type
  TYourClass = class(TComponent)
  public
    class function CreateFromString(AOwner: TComponent; AData: String): TYourClass; static;
  end;

implementation

class function TYourClass.CreateFromString(AOwner: TComponent; AData: String): TYourClass;
begin
   Result := (StringToComponentProc(AData) as TYourClass);
   if AOwner <> nil then
     AOwner.InsertComponent(Result);
end;
</code>```

The AOwner part could be a problem though, since TStream.ReadComponent has no parameter for the owner.

There is another so question about that problem:

How can I specify the Owner of component read from a Delphi TStream?

Edit: I've updated the code sample to include the owner, too.

Note that inserting into the component list of the owner requires a unique or empty Name for the component that is being inserted.

Body:
I'm serializing and deserializing an object (TComponent descendant) using the example in the ComponentToString section in the Delphi help file.  This is so I can store the object in a VARCHAR field in the database.

When I need to instantiate a new instance of my class from a string stored in the database, can I do that using a constructor of the form CreateFromString(AOwner: TComponent; AData: String)?  Or do I have to use a non-class method that returns an instance of my component class?

If I can use the constructor version, how to I "map" the return value of ReadComponent to the "self" that is being created by the constructor?

Here's the deserialization example from the help file:

function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;

Body:
Use a static class function instead of a constructor:

type
  TYourClass = class(TComponent)
  public
    class function CreateFromString(AOwner: TComponent; AData: String): TYourClass; static;
  end;

implementation

class function TYourClass.CreateFromString(AOwner: TComponent; AData: String): TYourClass;
begin
   Result := (StringToComponentProc(AData) as TYourClass);
   if AOwner <> nil then
     AOwner.InsertComponent(Result);
end;

The AOwner part could be a problem though, since TStream.ReadComponent has no parameter for the owner.

There is another so question about that problem:

How can I specify the Owner of component read from a Delphi TStream?

Edit: I've updated the code sample to include the owner, too.

Note that inserting into the component list of the owner requires a unique or empty Name for the component that is being inserted.


问:
java subclass or field, good semantics
Please help me to decide which approach is reasonable in the following case. Object:

```<code>public class FunctionCall {
  private String functionName;
  private List<Exp> args;
  ...
}
</code>```

In one very particular case/check the object need to be identified somehow.
Possible approaches:

FunctionCall class becomes an attribute, but there is a doubt that this would pollute overall semantics, as the attribute should not be visible "globally".

SpecialFunctionCall inherits the FunctionCall and with instanceof can be identified in the very special case. This would be ideal, the only doubt that it would misuse purpose of inheritance?

Any other suggestions are very welcome.

Thanks in advance.

答:
From what you wrote, it seems that the FunctionCall object is just a value object with data, not some object that evaluates itself and returns value. With multiple types of such objects, you need to have a way to disambiguate what type of object you are using.

For that part, I can advise you using enums to disambiguate rather than using instanceof operator or class reflections. You can create nice switch-case commands with it, too.

```<code>public class FunctionCall {
    // ...
    public MyType getType() {
        return MyType.BASIC_FUNCTION_CALL;
    }
}
</code>```

Another nice thing about enums is, it is a class that can have its own fields.  Have some final fields for the enum constants, put in values that describe some trait of it, and you can use this information in the logic that handles it, to your advantage.

As for the actual answer to your question though, it's not quite possible from knowing so little about your problem. In some cases, inheritance is better, in some other cases, composition is better. In both cases, some kind of interface is nice, and it could declare the getType method.

Title: java subclass or field, good semantics

Body:
Please help me to decide which approach is reasonable in the following case. Object:

public class FunctionCall {
  private String functionName;
  private List<Exp> args;
  ...
}

In one very particular case/check the object need to be identified somehow.
Possible approaches:

FunctionCall class becomes an attribute, but there is a doubt that this would pollute overall semantics, as the attribute should not be visible "globally".

SpecialFunctionCall inherits the FunctionCall and with instanceof can be identified in the very special case. This would be ideal, the only doubt that it would misuse purpose of inheritance?

Any other suggestions are very welcome.

Thanks in advance.

Body:
From what you wrote, it seems that the FunctionCall object is just a value object with data, not some object that evaluates itself and returns value. With multiple types of such objects, you need to have a way to disambiguate what type of object you are using.

For that part, I can advise you using enums to disambiguate rather than using instanceof operator or class reflections. You can create nice switch-case commands with it, too.

public class FunctionCall {
    // ...
    public MyType getType() {
        return MyType.BASIC_FUNCTION_CALL;
    }
}

Another nice thing about enums is, it is a class that can have its own fields.  Have some final fields for the enum constants, put in values that describe some trait of it, and you can use this information in the logic that handles it, to your advantage.

As for the actual answer to your question though, it's not quite possible from knowing so little about your problem. In some cases, inheritance is better, in some other cases, composition is better. In both cases, some kind of interface is nice, and it could declare the getType method.


问:
Redirect to signin page and display the message in that page only
I have this JavaScript code, in this scenario if data.rval == 2 then it should redirect to signin page and display the message in that page only

```<code>if(data.rval == 1) {
            window.location = "/offerletter/index";
            Application.PageAlertBox.Show('Sucess', ['Successfully Loggedin.']);
        } else if(data.rval == 2) {
            window.location = "/signin";
            Application.PageAlertBox.Show('info', ['OTP is Expired, New OTP has been sent on official email id, Please try again.']);
        } else if(data.rval == -4) {
            Application.PageAlertBox.Show('error', ['OTP is Invalid. Please Enter correct OTP.']);
        } else {
            Application.PageAlertBox.Show('error', [data.Message]);
        }
</code>```

答:
```<code>if(data.rval == 1) {
        window.location = "/offerletter/index";
        Application.PageAlertBox.Show('Sucess', ['Successfully Loggedin.']);
    } else if(data.rval == 2) {
        window.location = "/signin?info=OTP is Expired, New OTP has been sent on official email id, Please try again.";
    } else if(data.rval == -4) {
        Application.PageAlertBox.Show('error', ['OTP is Invalid. Please Enter correct OTP.']);
    } else {
        Application.PageAlertBox.Show('error', [data.Message]);
    }
</code>```

and in the signin page:

```<code>Application.PageAlertBox.Show('info', ['<?php echo $_GET['info']?>']);
</code>```

Body:
I have this JavaScript code, in this scenario if data.rval == 2 then it should redirect to signin page and display the message in that page only

if(data.rval == 1) {
            window.location = "/offerletter/index";
            Application.PageAlertBox.Show('Sucess', ['Successfully Loggedin.']);
        } else if(data.rval == 2) {
            window.location = "/signin";
            Application.PageAlertBox.Show('info', ['OTP is Expired, New OTP has been sent on official email id, Please try again.']);
        } else if(data.rval == -4) {
            Application.PageAlertBox.Show('error', ['OTP is Invalid. Please Enter correct OTP.']);
        } else {
            Application.PageAlertBox.Show('error', [data.Message]);
        }

Body:
if(data.rval == 1) {
        window.location = "/offerletter/index";
        Application.PageAlertBox.Show('Sucess', ['Successfully Loggedin.']);
    } else if(data.rval == 2) {
        window.location = "/signin?info=OTP is Expired, New OTP has been sent on official email id, Please try again.";
    } else if(data.rval == -4) {
        Application.PageAlertBox.Show('error', ['OTP is Invalid. Please Enter correct OTP.']);
    } else {
        Application.PageAlertBox.Show('error', [data.Message]);
    }

and in the signin page:

Application.PageAlertBox.Show('info', ['<?php echo $_GET['info']?>']);


问:
deep link not opening application activity
I am using below code to open my activity

```<code><activity
        android:name=".home.AddConferenceActivity"
        android:label="@string/add_conference"
        android:parentActivityName=".home.ConferenceActivity"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="cokeconference.com"
                android:pathPrefix="/info"
                android:scheme="cokeconference" />
        </intent-filter>
    </activity>
</code>```

and the URL is : cokeconference://cokeconference.com/info/Akshat/1234567891

I tried with both type of HTML files (with Java script as well) as below :

```<code><!DOCTYPE html>
<html>
<body>
    <script language="javascript">
        window.location =      'cokeconference://cokeconference.com/info/Akshat/1234567891';
    </script>
</body>
</html>
</code>```

and

```<code> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"      "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
  <TITLE>Base element example</TITLE>
   <a href="cokeconference://cokeconference.com/info/Akshat/1234567891"> Test     Conference Info </a>

</HEAD>
</code>```

Where I am going wrong ?
Thanks in Advance

答:
Replace :

```<code><data
    android:host="cokeconference.com"
    android:pathPrefix="/info"
    android:scheme="cokeconference" />
</code>```

With this:

```<code><data android:scheme="cokeconference" />
<data android:host="cokeconference.com" />
<data android:pathPattern="/info/.*/.*" />
</code>```

Body:
I am using below code to open my activity

<activity
        android:name=".home.AddConferenceActivity"
        android:label="@string/add_conference"
        android:parentActivityName=".home.ConferenceActivity"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="cokeconference.com"
                android:pathPrefix="/info"
                android:scheme="cokeconference" />
        </intent-filter>
    </activity>

and the URL is : cokeconference://cokeconference.com/info/Akshat/1234567891

I tried with both type of HTML files (with Java script as well) as below :

<!DOCTYPE html>

and

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"      "http://www.w3.org/TR/html4/strict.dtd">

  <TITLE>Base element example</TITLE>
    Test     Conference Info

Where I am going wrong ?
Thanks in Advance

Body:
Replace :

<data
    android:host="cokeconference.com"
    android:pathPrefix="/info"
    android:scheme="cokeconference" />

With this:

<data android:scheme="cokeconference" />
<data android:host="cokeconference.com" />
<data android:pathPattern="/info/.*/.*" />


问:
create new user in quickblox (javascript)
I was trying to use quickbox javascript api for chat application in my website. I used quickblox  example and  it's working good.But i didn't understand how to create new user. Any one have any code or tuorials or links on this share it.</p>

答:
```<code>    var QB = require('quickblox');

    // our parameters to connect to QuickBlox Chat service
    var CHAT = {
      server: 'chat.quickblox.com'
    };

    var CREDENTIALS = {
      appId: 55,
      authKey: 'ABCDE45415212',
      authSecret: 'ddf5456ffgf'
    };

    QB.init(CREDENTIALS.appId, CREDENTIALS.authKey, CREDENTIALS.authSecret);

    var params = { 'login': QuickBloxlogin(via email or username), 'pass': QuickBloxlogin Password};

    var user1 = { 'login': "new_user, 'password': "new_user_password"};

    QB.createSession(params, function(err, res) {
      if (err) {
        console.log(err.detail);
      } else {
        console.log(res);

        QB.users.create(user1, function(err, user) {
           // callback function
          if (err) {
              console.log(err.detail);
          }else {
              // user - JS obejct with QB user
                console.log('Users created');
          }
        });

// Link for more functions of users https://quickblox.com/developers/Sample-users-javascript#Update_your_own_profile

//This function will update the user based on his id

QB.users.update(user_id, {full_name: "My Name", email: "My emailid"}, function(err, user){
  if (user) {
     // success
  } else  {
     // error
  }
});

//This function will list out all the users with total records 100 in a single page
    var user_params = { page: '1', per_page: '100'};

    QB.users.listUsers(user_params, function(err, users_list){
      if (err) {
        // error
      } else {
        // success
        console.log(users_list);
      }
    });

 //This function will delete the user based on his id
       QB.users.delete(user_id, function(err, user){
       if (user) {
        // success
      } else  {
        // error
      }
    });
   }
  });
</code>```

Firstly import the quickblox package

Then get your credentials like appID, authKey, authSecret by registering your account in quickblox https://admin.quickblox.com

After this, enter your quickblox credentials for creating the session.

Now you can create the new user when you follow al the above steps

QuickBlox Docs for JavaScript:- https://quickblox.com/developers/Javascript

For more functions relating to user you can fing the same by visition quickblox site
https://quickblox.com/developers/Sample-users-javascript#Update_your_own_profile

Sometimes you need to retrieve all your QuickBlox users. But there is one restriction: you can retrieve a maximum of 100 users per query.

Here is an example how to retrieve all users:

```<code>var usersCount = 0;

function retrieveAllUsersFromPage(page_number) {
  var params = { page: page_number, per_page: '100'};
  QB.users.listUsers(params, function(err, result){
    if (result) {
      usersCount += result.items.length;
      if(result.total_entries > usersCount){
        retrieveAllUsersFromPage(result.per_page+1);
      }
    } else {
      // error
    }
  });
}

// Start
retrieveAllUsersFromPage(1);
</code>```

It's possible to use some filters and sort parameters:

```<code>var params = {filter: { field: 'email', param: 'eq', value: 'nobody@nowhere.org' }};

QB.users.listUsers(params, function(err, result){
  if (result) {
    // success
  } else {
    // error
  }
});
</code>```

// Retrieve Users with IDs

```<code>var params = {filter: { field: 'id', param: 'in', value: [2,3] }};

QB.users.listUsers(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});
</code>```

// Retrieve Users with tags

```<code>var params = {tags: ["man", "golf"]};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});
</code>```

// Retrieve Users with full names

```<code>var params = {full_name: ["Graay Sabs", "Samuel Camy"]};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});
</code>```

// Retrieve User by id

```<code>QB.users.get(72, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});
</code>```

// Retrieve User with Facebook ID

```<code>var params = {facebook_id: "11227884521232"};

    QB.users.get(params, function(err, result){
      if (result) {
        // success
      } else  {
        // error
      }
    });
</code>```

// Retrieve User with Twitter ID

```<code>var params = {twitter_id: "27884521232"};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});
</code>```

//Retrieve User with an external ID

```<code>var params = {external: "884521232"};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});
</code>```

Happy Coding :)

Body:
    var QB = require('quickblox');

    // our parameters to connect to QuickBlox Chat service
    var CHAT = {
      server: 'chat.quickblox.com'
    };

    var CREDENTIALS = {
      appId: 55,
      authKey: 'ABCDE45415212',
      authSecret: 'ddf5456ffgf'
    };

    QB.init(CREDENTIALS.appId, CREDENTIALS.authKey, CREDENTIALS.authSecret);

    var params = { 'login': QuickBloxlogin(via email or username), 'pass': QuickBloxlogin Password};

    var user1 = { 'login': "new_user, 'password': "new_user_password"};

    QB.createSession(params, function(err, res) {
      if (err) {
        console.log(err.detail);
      } else {
        console.log(res);

        QB.users.create(user1, function(err, user) {
           // callback function
          if (err) {
              console.log(err.detail);
          }else {
              // user - JS obejct with QB user
                console.log('Users created');
          }
        });

// Link for more functions of users https://quickblox.com/developers/Sample-users-javascript#Update_your_own_profile

//This function will update the user based on his id

QB.users.update(user_id, {full_name: "My Name", email: "My emailid"}, function(err, user){
  if (user) {
     // success
  } else  {
     // error
  }
});

//This function will list out all the users with total records 100 in a single page
    var user_params = { page: '1', per_page: '100'};

    QB.users.listUsers(user_params, function(err, users_list){
      if (err) {
        // error
      } else {
        // success
        console.log(users_list);
      }
    });

 //This function will delete the user based on his id
       QB.users.delete(user_id, function(err, user){
       if (user) {
        // success
      } else  {
        // error
      }
    });
   }
  });

Firstly import the quickblox package

Then get your credentials like appID, authKey, authSecret by registering your account in quickblox https://admin.quickblox.com

After this, enter your quickblox credentials for creating the session.

Now you can create the new user when you follow al the above steps

QuickBlox Docs for JavaScript:- https://quickblox.com/developers/Javascript

For more functions relating to user you can fing the same by visition quickblox site
https://quickblox.com/developers/Sample-users-javascript#Update_your_own_profile

Sometimes you need to retrieve all your QuickBlox users. But there is one restriction: you can retrieve a maximum of 100 users per query.

Here is an example how to retrieve all users:

var usersCount = 0;

function retrieveAllUsersFromPage(page_number) {
  var params = { page: page_number, per_page: '100'};
  QB.users.listUsers(params, function(err, result){
    if (result) {
      usersCount += result.items.length;
      if(result.total_entries > usersCount){
        retrieveAllUsersFromPage(result.per_page+1);
      }
    } else {
      // error
    }
  });
}

// Start
retrieveAllUsersFromPage(1);

It's possible to use some filters and sort parameters:

var params = {filter: { field: 'email', param: 'eq', value: 'nobody@nowhere.org' }};

QB.users.listUsers(params, function(err, result){
  if (result) {
    // success
  } else {
    // error
  }
});

// Retrieve Users with IDs

var params = {filter: { field: 'id', param: 'in', value: [2,3] }};

QB.users.listUsers(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});

// Retrieve Users with tags

var params = {tags: ["man", "golf"]};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});

// Retrieve Users with full names

var params = {full_name: ["Graay Sabs", "Samuel Camy"]};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});

// Retrieve User by id

QB.users.get(72, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});

// Retrieve User with Facebook ID

var params = {facebook_id: "11227884521232"};

    QB.users.get(params, function(err, result){
      if (result) {
        // success
      } else  {
        // error
      }
    });

// Retrieve User with Twitter ID

var params = {twitter_id: "27884521232"};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});

//Retrieve User with an external ID

var params = {external: "884521232"};

QB.users.get(params, function(err, result){
  if (result) {
    // success
  } else  {
    // error
  }
});

Happy Coding :)


问:
How can I show the "Open with" file dialog?
Is there any simple way to open the "Open with" file dialog?</p>

答:
This ought to do the trick...

```<code>var processInfo = new ProcessStartInfo(fileName);
processInfo.Verb = "openas";
Process.Start(processInfo);
</code>```

Although, Oded makes a great point - not knowing exactly how/where you intend to use such functionality means this might not be the answer for your situation.

Recent comments on this answer go to show I wasn't very detailed in the first place. A problem will arise if you try to openas a file that already has the open verb defined against that type of file. Similarly, if you try to open a file that doesn't have that verb defined there'll be trouble. The issue would be:

Win32Exception: No application is associated with the specified file for this operation

Off the top of my head I suggested to Thomas that in order to use this kind of code in a production application you would need to be thorough and perhaps check the registry, or otherwise find out whether or not a file can and should be opened with any given verb. It could be simpler than that when you consider ProcessStartInfo.Verbs: this will, once the fileName is set, provide you with a collection of possible verbs associated with the file type. This should make it easier to determine what to do with which file.

To wrap up, as I mentioned to Thomas, you will need to take care and add some complexity/intelligence to your application - this answer certainly isn't a catch-all solution.

Body:
This ought to do the trick...

var processInfo = new ProcessStartInfo(fileName);
processInfo.Verb = "openas";
Process.Start(processInfo);

Although, Oded makes a great point - not knowing exactly how/where you intend to use such functionality means this might not be the answer for your situation.

Recent comments on this answer go to show I wasn't very detailed in the first place. A problem will arise if you try to openas a file that already has the open verb defined against that type of file. Similarly, if you try to open a file that doesn't have that verb defined there'll be trouble. The issue would be:

Win32Exception: No application is associated with the specified file for this operation

Off the top of my head I suggested to Thomas that in order to use this kind of code in a production application you would need to be thorough and perhaps check the registry, or otherwise find out whether or not a file can and should be opened with any given verb. It could be simpler than that when you consider ProcessStartInfo.Verbs: this will, once the fileName is set, provide you with a collection of possible verbs associated with the file type. This should make it easier to determine what to do with which file.

To wrap up, as I mentioned to Thomas, you will need to take care and add some complexity/intelligence to your application - this answer certainly isn't a catch-all solution.


问:
How to check the status of URL?
I created a macro, in which I can fetch each URL from any webpage.

Now, I have each URL in column.

How can I check if a URL is working.

If any one of these URL is not working then it should show me error not working next to URL in next column.

Below is the code I wrote:

```<code>Sub CommandButton1_Click()
Dim ie As Object
Dim html As Object
Dim j As Integer
j = 1
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
url = "www.mini.co.uk"
ie.navigate url

Do While ie.READYSTATE <> READYSTATE_COMPLETE
    Application.StatusBar = "Trying to go to website ..."
Loop

Application.StatusBar = " "
Set html = ie.document
'Dim htmltext As Collection
Dim htmlElements As Object
Dim htmlElement As Object
Set htmlElements = html.getElementsByTagName("*")

For Each htmlElement In htmlElements
    'If htmlElement.getAttribute("href") <> "" Then Debug.Print htmlElement.getAttribute("href")
    If htmlElement.getAttribute("href") <> "" Then Cells(j, 1).Value = htmlElement.getAttribute("href")
    j = j + 1
Next

ActiveSheet.Range("$A$1:$A$2752").removeDuplicates Columns:=1, Header:=xlNo

End Sub
</code>```

This code is to fetch the URL from web-page.

Below is the code to check the status of URL, if it is working or not.

```<code>Sub CommandButton2_Click()
Dim k As Integer
Dim j As Integer
k = 1
j = 1
'Dim Value As Object
'Dim urls As Object
'urls.Value = Cells(j, 1)

For Each url In Cells(j, 1)
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = False
    url = Cells(j, 1)
    ie.navigate url

    Do While ie.READYSTATE <> READYSTATE_COMPLETE
        Application.StatusBar = "checking the Data. Please wait..."
    Loop

    Cells(k, 2).Value = "OK"
    'Set html = ie.document
    ie.Quit
    j = j + 1
    k = k + 1
Next

End Sub
</code>```

答:
```<code>Public Function IsURLGood(url As String) As Boolean
    Dim request As New WinHttpRequest

    On Error GoTo IsURLGoodError
    request.Open "HEAD", url
    request.Send
    If request.Status = 200 Then
        IsURLGood = True
    Else
        IsURLGood = False
    End If
    Exit Function

IsURLGoodError:
    IsURLGood = False
End Function

Sub testLink()

Dim source As Range, req As Object, url$

  Set source = Range("A2:B2")

  source.Columns(2).Clear

  For i = 1 To source.Rows.Count

  url = source.Cells(i, 1)
    If IsURLGood(url) Then
    source.Cells(i, 2) = "OK"
    Else
    source.Cells(i, 2) = "Down"
    End If

Next

  MsgBox "Done"

End Sub
</code>```

Title: How to check the status of URL?

Body:
I created a macro, in which I can fetch each URL from any webpage.

Now, I have each URL in column.

How can I check if a URL is working.

If any one of these URL is not working then it should show me error not working next to URL in next column.

Below is the code I wrote:

Sub CommandButton1_Click()
Dim ie As Object
Dim html As Object
Dim j As Integer
j = 1
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
url = "www.mini.co.uk"
ie.navigate url

Do While ie.READYSTATE <> READYSTATE_COMPLETE
    Application.StatusBar = "Trying to go to website ..."
Loop

Application.StatusBar = " "
Set html = ie.document
'Dim htmltext As Collection
Dim htmlElements As Object
Dim htmlElement As Object
Set htmlElements = html.getElementsByTagName("*")

For Each htmlElement In htmlElements
    'If htmlElement.getAttribute("href") <> "" Then Debug.Print htmlElement.getAttribute("href")
    If htmlElement.getAttribute("href") <> "" Then Cells(j, 1).Value = htmlElement.getAttribute("href")
    j = j + 1
Next

ActiveSheet.Range("$A$1:$A$2752").removeDuplicates Columns:=1, Header:=xlNo

End Sub

This code is to fetch the URL from web-page.

Below is the code to check the status of URL, if it is working or not.

Sub CommandButton2_Click()
Dim k As Integer
Dim j As Integer
k = 1
j = 1
'Dim Value As Object
'Dim urls As Object
'urls.Value = Cells(j, 1)

For Each url In Cells(j, 1)
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = False
    url = Cells(j, 1)
    ie.navigate url

    Do While ie.READYSTATE <> READYSTATE_COMPLETE
        Application.StatusBar = "checking the Data. Please wait..."
    Loop

    Cells(k, 2).Value = "OK"
    'Set html = ie.document
    ie.Quit
    j = j + 1
    k = k + 1
Next

End Sub


问:
How to permit only input br html tag
Hello (i'm not good at English, Sorry.)

I'm implementing any comment and reply system Using by HTML5/CSS3, Javascript, JSP.

I implemented any system if any user wrote texts,it was registered in DB,but the HTML tag's signs such as ('<','>') is replaced '<', '>'.

this is for security that protect any script attack, SQL query injection.

but I have a problem. I want to make permission for only br tag for new line in board's view page.

How can I implement this? please.

this is registering page I've so far :

```<code><%@ page contentType="text/html; charset=UTF-8" language="java" import="java.sql.*, java.net.InetAddress"%>
<!doctype html>
<html>
<head>
<%@ include file="../dbinfo.jsp" %>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<% request.setCharacterEncoding("UTF-8"); %>

<%
String nums = request.getParameter("num");
%>

<%
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Calendar cal = Calendar.getInstance();
    String date = Integer.toString(cal.get(Calendar.YEAR)) + "-";
    date += Integer.toString(cal.get(Calendar.MONTH)+1) + "-";
    date += Integer.toString(cal.get(Calendar.DATE)) + " ";
    date += Integer.toString(cal.get(Calendar.HOUR_OF_DAY)) + ":";
    date += Integer.toString(cal.get(Calendar.MINUTE)) + ":";
    date += Integer.toString(cal.get(Calendar.SECOND));
    String reply_num = null;
    String result ="n";
    String SQL  = "select (reply_num+1) as reply_num from  board_reply order by reply_num desc";
    pstmt = con.prepareStatement(SQL);
    rs = pstmt.executeQuery();
    if(rs.next()){
        reply_num = rs.getString("reply_num");
    }else{
        reply_num = "1";
    }
        SQL = "insert into board_reply(reply_num, text, userid, board_num, date, ip) values(?, ?, ?, ?, ?, ?)";
        pstmt = con.prepareStatement(SQL);
        pstmt.setString(1, reply_num);
        String text = (String) request.getParameter("ttext");
        String ip = request.getRemoteAddr();
        text = text.replaceAll("\r\n", "<br>");
        text = text.replaceAll("<", "<");
        text = text.replaceAll(">", ">");
        pstmt.setString(2, text);
        pstmt.setString(3, (String) request.getParameter("userid"));
        pstmt.setString(4, nums);
        pstmt.setString(5, date);
        pstmt.setString(6, ip);
        pstmt.executeUpdate();

    pstmt.close();
    rs.close();

 %>

</html>

<script>
alert("your texts are registered successfully!");
location.href ="board_list.jsp"
</script>
</code>```

答:
A very simple way, just change the orders of your replaceAll

```<code>text = text.replaceAll("<", "<");
text = text.replaceAll(">", ">");
text = text.replaceAll("\r\n", "<br>");
</code>```

this should work for what you asked

Title: How to permit only input br html tag

Body:
Hello (i'm not good at English, Sorry.)

I'm implementing any comment and reply system Using by HTML5/CSS3, Javascript, JSP.

I implemented any system if any user wrote texts,it was registered in DB,but the HTML tag's signs such as ('<','>') is replaced '<', '>'.

this is for security that protect any script attack, SQL query injection.

but I have a problem. I want to make permission for only br tag for new line in board's view page.

How can I implement this? please.

this is registering page I've so far :

<%@ page contentType="text/html; charset=UTF-8" language="java" import="java.sql.*, java.net.InetAddress"%>
<!doctype html>

<%@ include file="../dbinfo.jsp" %>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<% request.setCharacterEncoding("UTF-8"); %>

<%
String nums = request.getParameter("num");
%>

<%
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Calendar cal = Calendar.getInstance();
    String date = Integer.toString(cal.get(Calendar.YEAR)) + "-";
    date += Integer.toString(cal.get(Calendar.MONTH)+1) + "-";
    date += Integer.toString(cal.get(Calendar.DATE)) + " ";
    date += Integer.toString(cal.get(Calendar.HOUR_OF_DAY)) + ":";
    date += Integer.toString(cal.get(Calendar.MINUTE)) + ":";
    date += Integer.toString(cal.get(Calendar.SECOND));
    String reply_num = null;
    String result ="n";
    String SQL  = "select (reply_num+1) as reply_num from  board_reply order by reply_num desc";
    pstmt = con.prepareStatement(SQL);
    rs = pstmt.executeQuery();
    if(rs.next()){
        reply_num = rs.getString("reply_num");
    }else{
        reply_num = "1";
    }
        SQL = "insert into board_reply(reply_num, text, userid, board_num, date, ip) values(?, ?, ?, ?, ?, ?)";
        pstmt = con.prepareStatement(SQL);
        pstmt.setString(1, reply_num);
        String text = (String) request.getParameter("ttext");
        String ip = request.getRemoteAddr();
        text = text.replaceAll("\r\n", "
");
        text = text.replaceAll("<", "<");
        text = text.replaceAll(">", ">");
        pstmt.setString(2, text);
        pstmt.setString(3, (String) request.getParameter("userid"));
        pstmt.setString(4, nums);
        pstmt.setString(5, date);
        pstmt.setString(6, ip);
        pstmt.executeUpdate();

    pstmt.close();
    rs.close();

 %>

Body:
A very simple way, just change the orders of your replaceAll

text = text.replaceAll("<", "&lt;");
text = text.replaceAll(">", "&gt;");
text = text.replaceAll("\r\n", "<br>");

this should work for what you asked


问:
How to set two RabbitMQ connections for the same Camel RouteBuilder configure method
I want listen FROM rabbit queue, process, and post message TO another rabbit queue. I'm not working with spring. The messages are duplicated in this configuration.

This is a short code:

```<code>context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("rabbitmq://localhost/B?autoDelete=false&queue=worker&threadPoolSize=1&autoAck=false").
                    log(LoggingLevel.INFO, "Message ${id}").
                    to("rabbitmq://localhost/B?autoDelete=false&queue=processed");
        }
    });
</code>```

I have tried this too:

```<code>public static void main(String[] args) throws Exception {
    org.apache.camel.impl.DefaultCamelContext context = new DefaultCamelContext();

    com.rabbitmq.client.ConnectionFactory connectionFactoryWorker = new ConnectionFactory();
    com.rabbitmq.client.ConnectionFactory connectionFactoryProcessed = new ConnectionFactory();
    org.apache.camel.impl.SimpleRegistry registry = new SimpleRegistry();
    String camelBeanNameWorker = "connectionFactoryWorker";
    String camelBeanNameProcessed = "connectionFactoryProcessed";
    registry.put(camelBeanNameWorker, connectionFactoryWorker);
    registry.put(camelBeanNameProcessed, connectionFactoryProcessed);
    context.setRegistry(registry);

    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("rabbitmq://localhost/B?connectionFactory=connectionFactoryWorker&autoDelete=false&queue=worker&threadPoolSize=1&autoAck=false").
                    log(LoggingLevel.INFO, "Message ${id}").
                    to("rabbitmq://localhost/B?connectionFactory=connectionFactoryProcessed&autoDelete=false&queue=processed");
        }
    });

    context.start();
    Thread.sleep(10000l);
    context.stop();
}
</code>```

Worker queue start in four messages, but Messages are re-queued:

561 Message ID-host-1510600494291-0-2

  566 Message ID-host-1510600494291-0-4

  566 Message ID-host-1510600494291-0-6

  567 Message ID-host-1510600494291-0-8

  568 Message ID-host-1510600494291-0-10

  571 Message ID-host-1510600494291-0-12

  572 Message ID-host-1510600494291-0-14

  572 Message ID-host-1510600494291-0-16

  573 Message ID-host-1510600494291-0-18

  574 Message ID-host-1510600494291-0-20

  574 Message ID-host-1510600494291-0-22

  575 Message ID-host-1510600494291-0-24

  576 Message ID-host-1510600494291-0-26

  576 Message ID-host-1510600494291-0-28

  577 Message ID-host-1510600494291-0-30

  578 Message ID-host-1510600494291-0-32

  578 Message ID-host-1510600494291-0-34

  ...

      64k after

  ...

  10561 Message ID-host-1510600494291-0-128690

  10561 Message ID-host-1510600494291-0-128692

  10561 Message ID-host-1510600494291-0-128694

  10561 Message ID-host-1510600494291-0-128696

答:
Looking at your code, without knowing the outcome, I noticed that you are missing that you are missing the "#" when you are trying to use a bean from the registry.

What you need to do when using something from registry is

```<code>public static void main(String[] args) throws Exception {
DefaultCamelContext context = new DefaultCamelContext();

ConnectionFactory connectionFactory = new ConnectionFactory();
SimpleRegistry registry = new SimpleRegistry();
String beanNameWorker = "connectionFactoryWorker";
String beanNameProcessed = "connectionFactoryProcessed";
registry.put(beanNameWorker, connectionFactory);
registry.put(beanNameProcessed, connectionFactory);
context.setRegistry(registry);

context.addRoutes(new RouteBuilder() {
    @Override
    public void configure() throws Exception {
        from("rabbitmq://localhost/B?connectionFactory=#connectionFactoryWorker&autoDelete=false&queue=worker&threadPoolSize=1&autoAck=false").
                log(LoggingLevel.INFO, "Message ${id}").
                to("rabbitmq://localhost/B?connectionFactory=#connectionFactoryProcessed&autoDelete=false&queue=processed");
    }
});
</code>```

}

By the way what is the actual outcome? what errors do you have?

Body:
I want listen FROM rabbit queue, process, and post message TO another rabbit queue. I'm not working with spring. The messages are duplicated in this configuration.

This is a short code:

context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("rabbitmq://localhost/B?autoDelete=false&queue=worker&threadPoolSize=1&autoAck=false").
                    log(LoggingLevel.INFO, "Message ${id}").
                    to("rabbitmq://localhost/B?autoDelete=false&queue=processed");
        }
    });

I have tried this too:

public static void main(String[] args) throws Exception {
    org.apache.camel.impl.DefaultCamelContext context = new DefaultCamelContext();

    com.rabbitmq.client.ConnectionFactory connectionFactoryWorker = new ConnectionFactory();
    com.rabbitmq.client.ConnectionFactory connectionFactoryProcessed = new ConnectionFactory();
    org.apache.camel.impl.SimpleRegistry registry = new SimpleRegistry();
    String camelBeanNameWorker = "connectionFactoryWorker";
    String camelBeanNameProcessed = "connectionFactoryProcessed";
    registry.put(camelBeanNameWorker, connectionFactoryWorker);
    registry.put(camelBeanNameProcessed, connectionFactoryProcessed);
    context.setRegistry(registry);

    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("rabbitmq://localhost/B?connectionFactory=connectionFactoryWorker&autoDelete=false&queue=worker&threadPoolSize=1&autoAck=false").
                    log(LoggingLevel.INFO, "Message ${id}").
                    to("rabbitmq://localhost/B?connectionFactory=connectionFactoryProcessed&autoDelete=false&queue=processed");
        }
    });

    context.start();
    Thread.sleep(10000l);
    context.stop();
}

Worker queue start in four messages, but Messages are re-queued:

561 Message ID-host-1510600494291-0-2

  566 Message ID-host-1510600494291-0-4

  566 Message ID-host-1510600494291-0-6

  567 Message ID-host-1510600494291-0-8

  568 Message ID-host-1510600494291-0-10

  571 Message ID-host-1510600494291-0-12

  572 Message ID-host-1510600494291-0-14

  572 Message ID-host-1510600494291-0-16

  573 Message ID-host-1510600494291-0-18

  574 Message ID-host-1510600494291-0-20

  574 Message ID-host-1510600494291-0-22

  575 Message ID-host-1510600494291-0-24

  576 Message ID-host-1510600494291-0-26

  576 Message ID-host-1510600494291-0-28

  577 Message ID-host-1510600494291-0-30

  578 Message ID-host-1510600494291-0-32

  578 Message ID-host-1510600494291-0-34

  ...

      64k after

  ...

  10561 Message ID-host-1510600494291-0-128690

  10561 Message ID-host-1510600494291-0-128692

  10561 Message ID-host-1510600494291-0-128694

  10561 Message ID-host-1510600494291-0-128696

Body:
Looking at your code, without knowing the outcome, I noticed that you are missing that you are missing the "#" when you are trying to use a bean from the registry.

What you need to do when using something from registry is

public static void main(String[] args) throws Exception {
DefaultCamelContext context = new DefaultCamelContext();

ConnectionFactory connectionFactory = new ConnectionFactory();
SimpleRegistry registry = new SimpleRegistry();
String beanNameWorker = "connectionFactoryWorker";
String beanNameProcessed = "connectionFactoryProcessed";
registry.put(beanNameWorker, connectionFactory);
registry.put(beanNameProcessed, connectionFactory);
context.setRegistry(registry);

context.addRoutes(new RouteBuilder() {
    @Override
    public void configure() throws Exception {
        from("rabbitmq://localhost/B?connectionFactory=#connectionFactoryWorker&autoDelete=false&queue=worker&threadPoolSize=1&autoAck=false").
                log(LoggingLevel.INFO, "Message ${id}").
                to("rabbitmq://localhost/B?connectionFactory=#connectionFactoryProcessed&autoDelete=false&queue=processed");
    }
});

}

By the way what is the actual outcome? what errors do you have?


问:
django download images in zip file
I use this code in DJANGO framework to can some user download images.
this code work fine and download image every time to press download some user.

but this code download absolute images I need to zip this images for any user download.

```<code>def download_image(request, id):
    product_image=MyModel.objects.get(pk=id)
    product_image_url = product_image.upload.url
    wrapper = FileWrapper(open(settings.MEDIA_ROOT+ product_image_url[6:], 'rb'))
    content_type = mimetypes.guess_type(product_image_url)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Disposition'] = "attachment; filename=%s" % product_image_url
    return response
</code>```

is easy to change this code to download images in zip file ?

答:
Try the following:</p>

```<code>def download_image(request, id):
    product_image=MyModel.objects.get(pk=id)
    product_image_url = product_image.upload.url

    image_path = settings.MEDIA_ROOT+ product_image_url[6:]
    image_name = 'whatevername.png'; # Get your file name here.

    with ZipFile('export.zip', 'w') as export_zip:
        export_zip.write(image_path, image_name)

    wrapper = FileWrapper(open('export.zip', 'rb'))
    content_type = 'application/zip'
    content_disposition = 'attachment; filename=export.zip'

    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Disposition'] = content_disposition
    return response
</code>```

Title: django download images in zip file

Body:
I use this code in DJANGO framework to can some user download images.
this code work fine and download image every time to press download some user.

but this code download absolute images I need to zip this images for any user download.

def download_image(request, id):
    product_image=MyModel.objects.get(pk=id)
    product_image_url = product_image.upload.url
    wrapper = FileWrapper(open(settings.MEDIA_ROOT+ product_image_url[6:], 'rb'))
    content_type = mimetypes.guess_type(product_image_url)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Disposition'] = "attachment; filename=%s" % product_image_url
    return response

is easy to change this code to download images in zip file ?

Body:
Try the following:

def download_image(request, id):
    product_image=MyModel.objects.get(pk=id)
    product_image_url = product_image.upload.url

    image_path = settings.MEDIA_ROOT+ product_image_url[6:]
    image_name = 'whatevername.png'; # Get your file name here.

    with ZipFile('export.zip', 'w') as export_zip:
        export_zip.write(image_path, image_name)

    wrapper = FileWrapper(open('export.zip', 'rb'))
    content_type = 'application/zip'
    content_disposition = 'attachment; filename=export.zip'

    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Disposition'] = content_disposition
    return response


问:
Eclipse/Java9: how to access internal javafx packages?
My context:

Eclipse IDE for Java Developers, Version: Oxygen.1a Release (4.7.1a), Build id: 20171005-1200oxygen

jdk9.0.1

win10

Something simple like:

```<code>import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;

import javafx.application.Application;
import javafx.stage.Stage;

public class ImportCom extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        new LambdaMultiplePropertyChangeListenerHandler();

    }

}
</code>```

won't compile due to

```<code>The type com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler is not accessible
</code>```

What to do?

looks similar but now for internal classes ;) Had been compiling until patch 530 of the beta9 support but not after - so keeping that oldish oxygen as a gold treasure ...

Note: cross-posted to eclipse forum

Edit:

Just checked that the behavior of javac on the commandline:

```<code>C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac first\ImportCom.java
first\ImportCom.java:3: error: package com.sun.javafx.scene.control is not visible
import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;
                           ^
  (package com.sun.javafx.scene.control is declared in module javafx.controls, which does not export it to the unnamed module)
1 error
</code>```

The error is similar to the one in Eclipse. Works fine with --add-exports:

```<code>C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac --add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED first\ImportCom.java
</code>```

So the question boils down to: where/how to configure Eclipse such that it compiles access to internal classes just the same way as javac?

答:
Well, it's a bit hidden:

open Java Build Path dialog of the project

select Libraries tab

select isModular entry

use the Edit... button to open the module properties dialog

select Details tab

create all required entries with the Add.. button

If you have installed the Beta plugin for Java 9 support - uninstall. Make sure the latest Java 9 support plugin is installed.

Body:
My context:

Eclipse IDE for Java Developers, Version: Oxygen.1a Release (4.7.1a), Build id: 20171005-1200oxygen

jdk9.0.1

win10

Something simple like:

import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;

import javafx.application.Application;
import javafx.stage.Stage;

public class ImportCom extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        new LambdaMultiplePropertyChangeListenerHandler();

    }

}

won't compile due to

The type com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler is not accessible

What to do?

looks similar but now for internal classes ;) Had been compiling until patch 530 of the beta9 support but not after - so keeping that oldish oxygen as a gold treasure ...

Note: cross-posted to eclipse forum

Edit:

Just checked that the behavior of javac on the commandline:

C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac first\ImportCom.java
first\ImportCom.java:3: error: package com.sun.javafx.scene.control is not visible
import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;
                           ^
  (package com.sun.javafx.scene.control is declared in module javafx.controls, which does not export it to the unnamed module)
1 error

The error is similar to the one in Eclipse. Works fine with --add-exports:

C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac --add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED first\ImportCom.java

So the question boils down to: where/how to configure Eclipse such that it compiles access to internal classes just the same way as javac?


问:
Autodesk Forge API createBucket not working
I'm trying to build an application by using the autodesk-forge-api's. To start with I created an App inside my Autodesk configuration to receive an "ClientID" and a "Client Secret" which are required to make API calls.

Somehow, when I try to use the createBucket-API call, which is documentet here I get an answer bad request 400 and I dont't know why.

here is my API call:

```<code>let oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(clientId,
  clientSecret, [
  'data:read',
  'data:write',
  'bucket:create',
  'bucket:read',
  'data:write',
  'data:read',
  'viewables:read'
], autoRefresh);

oAuth2TwoLegged.authenticate().then(function(credentials){

  var HubsApi = new ForgeSDK.HubsApi(); //Hubs Client
  var BucketsApi = new ForgeSDK.BucketsApi(); //Buckets Client

  BucketsApi.createBucket({bucketKey :"Test", policyKey: "transient"},{}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
  });

}).catch((err) => {
  console.log('oauth error: ', err)
})
</code>```

Does anyone have a suggestion what I might doing wrong?

when I use a different call, for example this:

```<code>BucketsApi.getBuckets({}, oAuth2TwoLegged, credentials).then(function(response){
   console.log('buckets: ', response.body);
  }, function(err){
    console.error(err);
});
</code>```

it works...

EDIT

If I do the following:

```<code>BucketsApi.createBucket(xyda_select_rtl, {'bucketKey' :'xyda_select_rtl',
   'policyKey': 'transient'}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
});
</code>```

I get xyda_select_rtl is not defined!?!

When I add:

```<code>var xyda_select_rtl;
</code>```

I get the error Missing the required parameter 'postBuckets' when calling createBucket

Ehhm.... yeah :-/

答:
It seems that your bucket key is duplicated, or your client id and client secrete have invalid characters. Please check those parameters in your app. And the name of the Bucket, I.e. the bucket key should be global unique. If the name you passed to the Post /buckets is existed, you will get error, too. I’d suggest you to use the naming pattern in this way:

```<code>Test + { Your Bucket Key }
</code>```

Hope it helps.

Body:
I'm trying to build an application by using the autodesk-forge-api's. To start with I created an App inside my Autodesk configuration to receive an "ClientID" and a "Client Secret" which are required to make API calls.

Somehow, when I try to use the createBucket-API call, which is documentet here I get an answer bad request 400 and I dont't know why.

here is my API call:

let oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(clientId,
  clientSecret, [
  'data:read',
  'data:write',
  'bucket:create',
  'bucket:read',
  'data:write',
  'data:read',
  'viewables:read'
], autoRefresh);

oAuth2TwoLegged.authenticate().then(function(credentials){

  var HubsApi = new ForgeSDK.HubsApi(); //Hubs Client
  var BucketsApi = new ForgeSDK.BucketsApi(); //Buckets Client

  BucketsApi.createBucket({bucketKey :"Test", policyKey: "transient"},{}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
  });

}).catch((err) => {
  console.log('oauth error: ', err)
})

Does anyone have a suggestion what I might doing wrong?

when I use a different call, for example this:

BucketsApi.getBuckets({}, oAuth2TwoLegged, credentials).then(function(response){
   console.log('buckets: ', response.body);
  }, function(err){
    console.error(err);
});

it works...

EDIT

If I do the following:

BucketsApi.createBucket(xyda_select_rtl, {'bucketKey' :'xyda_select_rtl',
   'policyKey': 'transient'}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
});

I get xyda_select_rtl is not defined!?!

When I add:

var xyda_select_rtl;

I get the error Missing the required parameter 'postBuckets' when calling createBucket

Ehhm.... yeah :-/

Body:
It seems that your bucket key is duplicated, or your client id and client secrete have invalid characters. Please check those parameters in your app. And the name of the Bucket, I.e. the bucket key should be global unique. If the name you passed to the Post /buckets is existed, you will get error, too. I’d suggest you to use the naming pattern in this way:

Test + { Your Bucket Key }

Hope it helps.


答: There are tons of shell examples in the All In One Code Framework. Maybe you can take a look at them to see whether an example has functions you want to have.</p>

Title: How can I show the "Open with" file dialog?

Body: Is there any simple way to open the "Open with" file dialog?


问:
How google map track user location all the time even if app is closed and not running in background?
In google iOS app, your timeline shows all the location tracked by google map, even if your app is closed.
Any idea, how this can be achieved?</p>

答:
When app is closed and not running in background then location never track in iOS 11.

Changes to location tracking in iOS 11

iOS 11 also makes some major changes to existing APIs. One of the affected areas is location tracking. If your app only uses location while the app is in the foreground, as most apps do, you might not have to change anything at all; however, if it’s one of those apps that continuously track user’s location throughout the day, you should probably book some time this summer for making some changes in how you do the tracking and testing possible usage scenarios.

follow this link: https://mackuba.eu/2017/07/13/changes-to-location-tracking-in-ios-11/

Hope will helpful to you!!


问:
Is it possible to sign an xml document without having to use KeyContainerName?
I want to create 2 really simple dlls:

1) that will sign an xml document
2) that will check that the xml document hasnt been modified.

I tried using the RSACryptoServiceProvider and a key container. But when I move to a different machine this does not work as the key is being stored in the machine.

I want to store the key in the dlls im creating (I know this is not reccomended) but I just cannot work out how to write some code to simply sign an xml document and then verify that it hasn't been changed.

So do I need to use symmetric key to do what I want is this possible?

Pete

答:
You already mention the problems with storing the private key in the dll, so I won't repeat that.

Do this:

On your own machine run this code:

```<code>var key = new RSACryptoServiceProvider(2048);
string publicKey = key.ToXmlString(false);
string privateKey = key.ToXmlString(true);
Console.WriteLine(publicKey);
Console.WriteLine(privateKey);
</code>```

this outputs two (long) lines. Copy those into your code:

Sign:

```<code>var privateKey = new RSACryptoServiceProvider();
privateKey.FromXmlString(/* insert the private-key XML string here */ );
privateKey.SignData(/*...*/);
</code>```

Verify:

```<code>var publicKey = new RSACryptoServiceProvider();
publicKey.FromXmlString(/* insert the public-key XML string here */ );
publicKey.VerifyData(/*...*/);
</code>```

Body:
You already mention the problems with storing the private key in the dll, so I won't repeat that.

Do this:

On your own machine run this code:

var key = new RSACryptoServiceProvider(2048);
string publicKey = key.ToXmlString(false);
string privateKey = key.ToXmlString(true);
Console.WriteLine(publicKey);
Console.WriteLine(privateKey);

this outputs two (long) lines. Copy those into your code:

Sign:

var privateKey = new RSACryptoServiceProvider();
privateKey.FromXmlString(/* insert the private-key XML string here */ );
privateKey.SignData(/*...*/);

Verify:

var publicKey = new RSACryptoServiceProvider();
publicKey.FromXmlString(/* insert the public-key XML string here */ );
publicKey.VerifyData(/*...*/);