问:
Is it possible to use ijson to create and load JSON objects in memory (not from/to a file)?
I'm trying to use ijson instead of json to be able to efficiently dump/load dictionaries to/from strings (in-memory, not from a file) [1].

Are there any examples for ijson analogous to standard dumping/loading with json? All sources I've seen that use ijson have examples with files only.

[1] -- Dictionaries are being converted to strings in order to store them in a set

答:
To complement omri_saadon's answer in the vein of performance,

Here is a link (serializer speed comparisons) that measures some lesser known JSON modules, one of which was found to effectively outperform the others (msgpack) and can be used interchangeably with json.

Hence, instead of ijson or standard json, msgpack is presently being used for the dict/str conversions.

To install:
    pip install msgpack

To use:
    import msgpack as json # can use dumps/loads functions


来源: stackexchange

问:
Connection String to an SQL server MVC C#
i am making an online shop mvc web , i made a table for categories and filled it with data , and made a table for products and filled it with data, now how to connect to these database to preview them on web (NOTE: i want to press on store on web , then it will take us to categories then after pressing categories we will have the products in these categories.
This is my Store Controller:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCOnlineShop.Models;

namespace MVCOnlineShop.Controllers
{
    public class StoreController : Controller
    {
        OnlineStoreEntities storeDB = new OnlineStoreEntities();
        //
        // GET: /Store/

        public ActionResult Index()
        {
            var Categories = storeDB.Categories.ToList();
            return View(Categories);
        }
        //
        // GET: /Store/Browse
        public ActionResult Browse(string Category)
        {
            // Retrieve Category and its Associated Products from database
            var CategoryModel = storeDB.Categories.Include("Products")
                .Single(g => g.Name == Category);

            return View(CategoryModel);
        }
        //
        // GET: /Store/Details
        public ActionResult Details(int id)
        {
            var Product = storeDB.Products.Find(id);

            return View(Product);
        }
        //
        // GET: /Store/Browse?Category=Games

    }
}
</code>```

Can you please give me the correct form of connection string to an SQL server

答:
Press f12 on OnlineStoreEntities class then check the connectionString mentioned in OnlineStoreEntities :base("connectionstringName") .
Check the connection string name in webconfig.
In web config you can change the connection string values.

https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/database-first-development/creating-the-web-application

go through this tutorial for DB first approach .

ContentLicense: CC BY-SA 3.0

Body:
i am making an online shop mvc web , i made a table for categories and filled it with data , and made a table for products and filled it with data, now how to connect to these database to preview them on web (NOTE: i want to press on store on web , then it will take us to categories then after pressing categories we will have the products in these categories.
This is my Store Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCOnlineShop.Models;

namespace MVCOnlineShop.Controllers
{
    public class StoreController : Controller
    {
        OnlineStoreEntities storeDB = new OnlineStoreEntities();
        //
        // GET: /Store/

        public ActionResult Index()
        {
            var Categories = storeDB.Categories.ToList();
            return View(Categories);
        }
        //
        // GET: /Store/Browse
        public ActionResult Browse(string Category)
        {
            // Retrieve Category and its Associated Products from database
            var CategoryModel = storeDB.Categories.Include("Products")
                .Single(g => g.Name == Category);

            return View(CategoryModel);
        }
        //
        // GET: /Store/Details
        public ActionResult Details(int id)
        {
            var Product = storeDB.Products.Find(id);

            return View(Product);
        }
        //
        // GET: /Store/Browse?Category=Games

    }
}

Can you please give me the correct form of connection string to an SQL server


问:
jquery/ajax json data function not working
I have the following function it suppose to talk to another server retrieve the json data and display it the problem is the function is not even initiating a query I'm I doing something wronge? the code is uploaded into the apache tomcat server and I used wireshark for traces and there are none on the http port  here is the code </p>

```<code>$(document).ready( function() {
var home_add='http://wcf.net:3300/gateway';
$('#handshake').click(function(){
alert(" sending json data");
 function handshake(){     /*testing the function */
                      var data_send = {
                          "supportedConnectionTypes": "long-polling",
                          "channel": "/meta/handshake",
                          "version": "1:0"
                          };
                      $.ajax({                 /* start ajax function to send data */
                          url:home_add,
                          type:'POST',
                          datatype:'json',
                          contanttype:'text/json',
                          async: false,
                          error:function(){ alert("handshake didn't go through")}, /* call disconnect function */
                          data:JSON.stringify(data_send),
                          success:function(data){
                          $("p").append(data+"<br/>");
                           alert("successful handshake")
                           }
                          })

                          }
})})
</code>```

<p>Thank you in advance for the feedback
Lava </p>

答:
u dont call handshake function...

```<code>$(document).ready(function () {
var home_add = 'http://wcf.net:3300/gateway';
$('#handshake').click(function () {
    alert(" sending json data");
    $.ajax({                 /* start ajax function to send data */
        url: home_add,
        type: 'POST',
        datatype: 'json',
        contanttype: 'text/json',
        async: false,
        error: function () { alert("handshake didn't go through") }, /* call disconnect function */
        data: {
            "supportedConnectionTypes": "long-polling",
            "channel": "/meta/handshake",
            "version": "1:0"
        },
        success: function (data) {
            $("p").append(data + "<br/>");
            alert("successful handshake")
        }
    });

});
</code>```

});

ContentLicense: CC BY-SA 2.5

Body:
I have the following function it suppose to talk to another server retrieve the json data and display it the problem is the function is not even initiating a query I'm I doing something wronge? the code is uploaded into the apache tomcat server and I used wireshark for traces and there are none on the http port  here is the code

$(document).ready( function() {
var home_add='http://wcf.net:3300/gateway';
$('#handshake').click(function(){
alert(" sending json data");
 function handshake(){     /*testing the function */
                      var data_send = {
                          "supportedConnectionTypes": "long-polling",
                          "channel": "/meta/handshake",
                          "version": "1:0"
                          };
                      $.ajax({                 /* start ajax function to send data */
                          url:home_add,
                          type:'POST',
                          datatype:'json',
                          contanttype:'text/json',
                          async: false,
                          error:function(){ alert("handshake didn't go through")}, /* call disconnect function */
                          data:JSON.stringify(data_send),
                          success:function(data){
                          $("p").append(data+"
");
                           alert("successful handshake")
                           }
                          })

                          }
})})

Thank you in advance for the feedback
Lava

Body:
u dont call handshake function...

$(document).ready(function () {
var home_add = 'http://wcf.net:3300/gateway';
$('#handshake').click(function () {
    alert(" sending json data");
    $.ajax({                 /* start ajax function to send data */
        url: home_add,
        type: 'POST',
        datatype: 'json',
        contanttype: 'text/json',
        async: false,
        error: function () { alert("handshake didn't go through") }, /* call disconnect function */
        data: {
            "supportedConnectionTypes": "long-polling",
            "channel": "/meta/handshake",
            "version": "1:0"
        },
        success: function (data) {
            $("p").append(data + "<br/>");
            alert("successful handshake")
        }
    });

});

});


问:
How to import a module in a subdirectory that imports another module in that same subdirectory?
In a module that I import, I'm trying to import another module, that is located in that same directory.

My files look something like this...

```<code>project
├── main.py
└── app
    └── foo.py
    └── bar.py
</code>```

main.py

```<code>import app.foo as Foo
</code>```

foo.py

```<code>import bar
</code>```

So now, when I run main.py, I get a

```<code>ModuleNotFoundError: No module named 'bar'
</code>```

There are so many similar questions, but none of them seem to be my exact situation.

How can I get this to work?

答:
This is mainly because when run main.py directly, Python would use the directory where main.py locates as the current running directory, thus when you import bar directly in foo.py, Python interpreter will try to find bar module in that running directory, where bar.py doesn't exist apparently. That is the reason why relative import is needed, as answered by @Robert Szczelina.

If you run foo.py directly, the sentense import bar will be right.

Body:
In a module that I import, I'm trying to import another module, that is located in that same directory.

My files look something like this...

project
├── main.py
└── app
    └── foo.py
    └── bar.py

main.py

import app.foo as Foo

foo.py

import bar

So now, when I run main.py, I get a

ModuleNotFoundError: No module named 'bar'

There are so many similar questions, but none of them seem to be my exact situation.

How can I get this to work?


问:
Java: java.util.Preferences Failing
My program saves encrypted product key data to the computer with the java.util.Preferences class (system preferences, not user).  The problem is, on both Windows and Linux (haven't tested on OSX, but it's probably the same), if I don't run the program with sudo or with Administrator privileges, it emits an exception or warning whenever it tries to read or save the data.

Obviously requiring the user to run the program with Admin privileges would be impractical.  Optimally, I'd like the operating system to ask the user for permission.

This is quite silly, and removes half the purpose of Preferences.  How can this be fixed?

Here's a summary what I need: I need my program to ask for permission from the operating system to save system settings.

Here is the error information

Here's the error when the when I try to read a node (because the node doesn't exist):

```<code>Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences <init>
WARNING: Could not create windows registry node Software\JavaSoft\Prefs\myapp at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences WindowsRegOpenKey1
WARNING: Trying to recreate Windows registry node Software\JavaSoft\Prefs\myapp at root 0x80000002.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences openKey
WARNING: Could not open windows registry node Software\JavaSoft\Prefs\myapp at root 0x80000002. Windows RegOpenKey(...) returned error code 2.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences WindowsRegOpenKey1
WARNING: Trying to recreate Windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences openKey
WARNING: Could not open windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002. Windows RegOpenKey(...) returned error code 2.
</code>```

And this is what happens when I try to write to a node:

```<code>Mar 18, 2011 9:43:11 AM java.util.prefs.WindowsPreferences WindowsRegOpenKey1
WARNING: Trying to recreate Windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002.
Mar 18, 2011 9:43:11 AM java.util.prefs.WindowsPreferences openKey
WARNING: Could not open windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002. Windows RegOpenKey(...) returned error code 2.
</code>```

答:
The solution for me was not obvious - it was to update my cryptography security jars from Oracle as it seems to be a key length restriction (I didn't believe it was related, until I tried it).

Download from Oracle website

The download contains instructions and explains:

Due to import control restrictions of some countries, the version of
  the JCE policy files that are bundled in the Java Runtime Environment,
  or JRE(TM), 8 environment allow "strong" but limited cryptography to be
  used. This download bundle (the one including this README file)
  provides "unlimited strength" policy files which contain no
  restrictions on cryptographic strengths.

This apparently applies to Registry keys too

Title: Java: java.util.Preferences Failing

Body:
My program saves encrypted product key data to the computer with the java.util.Preferences class (system preferences, not user).  The problem is, on both Windows and Linux (haven't tested on OSX, but it's probably the same), if I don't run the program with sudo or with Administrator privileges, it emits an exception or warning whenever it tries to read or save the data.

Obviously requiring the user to run the program with Admin privileges would be impractical.  Optimally, I'd like the operating system to ask the user for permission.

This is quite silly, and removes half the purpose of Preferences.  How can this be fixed?

Here's a summary what I need: I need my program to ask for permission from the operating system to save system settings.

Here is the error information

Here's the error when the when I try to read a node (because the node doesn't exist):

Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences <init>
WARNING: Could not create windows registry node Software\JavaSoft\Prefs\myapp at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences WindowsRegOpenKey1
WARNING: Trying to recreate Windows registry node Software\JavaSoft\Prefs\myapp at root 0x80000002.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences openKey
WARNING: Could not open windows registry node Software\JavaSoft\Prefs\myapp at root 0x80000002. Windows RegOpenKey(...) returned error code 2.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences WindowsRegOpenKey1
WARNING: Trying to recreate Windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002.
Mar 18, 2011 9:41:15 AM java.util.prefs.WindowsPreferences openKey
WARNING: Could not open windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002. Windows RegOpenKey(...) returned error code 2.

And this is what happens when I try to write to a node:

Mar 18, 2011 9:43:11 AM java.util.prefs.WindowsPreferences WindowsRegOpenKey1
WARNING: Trying to recreate Windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002.
Mar 18, 2011 9:43:11 AM java.util.prefs.WindowsPreferences openKey
WARNING: Could not open windows registry node Software\JavaSoft\Prefs\myapp\subpackage at root 0x80000002. Windows RegOpenKey(...) returned error code 2.


问:
Can't destroy cookie and session in same time?
I'm trying to destroy visitors cookie and session at same time when he/she logs out. Like this:

```<code>setcookie($id, '', time()-13600, "/");
unset($_SESSION[$id]);
</code>```

Although cookie destroys but user is still logged in because session not destroying.

Note: I can't use session_unset() because it will destroy all the sessions.

PS: I solved my problem just by not setting session but only cookie, still i can't solve problem i asked above.

答:
for destroy all sessions use this code

```<code><?php
session_destroy();
</code>```

for unset any session you can do it by session : key

```<code><?php
unset($_SESSION['key_name']);
</code>```

Body:
I'm trying to destroy visitors cookie and session at same time when he/she logs out. Like this:

setcookie($id, '', time()-13600, "/");
unset($_SESSION[$id]);

Although cookie destroys but user is still logged in because session not destroying.

Note: I can't use session_unset() because it will destroy all the sessions.

PS: I solved my problem just by not setting session but only cookie, still i can't solve problem i asked above.

Body:
for destroy all sessions use this code

<?php
session_destroy();

for unset any session you can do it by session : key

<?php
unset($_SESSION['key_name']);


问:
FileMover 24hrs - Python
so I am supposed to move files(.txt)that are new and that have also been edited within a 24hour time frame. Files with the extension .txt should go from folder A to B. My code works, however, it is moving one single file at a time after every time I press F5 to run the program. Would someone please help me move all files by clicking just once?

Thanks

```<code>import os
import datetime
import shutil

source = ("/Users/SD/Desktop/A")
destination = ("/Users/SD/Desktop/B")
currentTime = datetime.datetime.now()
oldFile = currentTime - datetime.timedelta(hours=24)
for files in os.listdir(source):
    if files.endswith('.txt'):
        path = os.path.join(source, files)
        st = os.stat(path)
        mTime = datetime.datetime.fromtimestamp(st.st_mTime)

        if mTime > oldFile:
            print('{} ~ last modified {}'.format(path, mTime))

fileSource = os.path.join(source, files)
fileDestination = os.path.join(destination, files)
shutil.move(fileSource, fileDestination)
print("\tMoved {} to {}.\n".format(files, destination))
</code>```

答:
Your indentation is off i think in your code, you move the file after the for-loop. This results in only the last file of the for-loop being moved. Move the last bit of code inside the loop, and inside the last if-statement specifically, to move any file that matches your criteria.

Furthermore your time testing really confuses me, and i doubt it even does what you think it does. I've replaced it with a (to me) clearer testing...

```<code>import os
import datetime
import shutil

source = ("/Users/../Desktop/A")
destination = ("/Users/../Desktop/B")
currentTime = datetime.datetime.now()
for files in os.listdir(source):
    if files.endswith('.txt'):
        path = os.path.join(source, files)
        st = os.stat(path)
        #---New Time Test setup---#
        tDelta = currentTime - datetime.datetime.fromtimestamp(st.st_mtime)
        maxDelta = 24*3600
        if tDelta.total_seconds() < maxDelta:
            print('{} ~ last modified {}'.format(path, tDelta))
            fileSource = os.path.join(source, files)
            fileDestination = os.path.join(destination, files)
            shutil.move(fileSource, fileDestination)
            print("\tMoved {} to {}.\n".format(files, destination))
</code>```

Files before:

```<code>..\Desktop\A\
  -text_a.txt
  -text_b.txt
..\Desktop\B\
  ~Empty~
</code>```

Files after:

```<code>..\Desktop\A\
  ~Empty~
..\Desktop\B\
  -text_a.txt
  -text_b.txt
</code>```

PS: I assume there is a little error in your code and oldFile should be dayOld or vice versa. You should edit this...

Title: FileMover 24hrs - Python

Body:
so I am supposed to move files(.txt)that are new and that have also been edited within a 24hour time frame. Files with the extension .txt should go from folder A to B. My code works, however, it is moving one single file at a time after every time I press F5 to run the program. Would someone please help me move all files by clicking just once?

Thanks

import os
import datetime
import shutil

source = ("/Users/SD/Desktop/A")
destination = ("/Users/SD/Desktop/B")
currentTime = datetime.datetime.now()
oldFile = currentTime - datetime.timedelta(hours=24)
for files in os.listdir(source):
    if files.endswith('.txt'):
        path = os.path.join(source, files)
        st = os.stat(path)
        mTime = datetime.datetime.fromtimestamp(st.st_mTime)

        if mTime > oldFile:
            print('{} ~ last modified {}'.format(path, mTime))

fileSource = os.path.join(source, files)
fileDestination = os.path.join(destination, files)
shutil.move(fileSource, fileDestination)
print("\tMoved {} to {}.\n".format(files, destination))

Body:
Your indentation is off i think in your code, you move the file after the for-loop. This results in only the last file of the for-loop being moved. Move the last bit of code inside the loop, and inside the last if-statement specifically, to move any file that matches your criteria.

Furthermore your time testing really confuses me, and i doubt it even does what you think it does. I've replaced it with a (to me) clearer testing...

import os
import datetime
import shutil

source = ("/Users/../Desktop/A")
destination = ("/Users/../Desktop/B")
currentTime = datetime.datetime.now()
for files in os.listdir(source):
    if files.endswith('.txt'):
        path = os.path.join(source, files)
        st = os.stat(path)
        #---New Time Test setup---#
        tDelta = currentTime - datetime.datetime.fromtimestamp(st.st_mtime)
        maxDelta = 24*3600
        if tDelta.total_seconds() < maxDelta:
            print('{} ~ last modified {}'.format(path, tDelta))
            fileSource = os.path.join(source, files)
            fileDestination = os.path.join(destination, files)
            shutil.move(fileSource, fileDestination)
            print("\tMoved {} to {}.\n".format(files, destination))

Files before:

..\Desktop\A\
  -text_a.txt
  -text_b.txt
..\Desktop\B\
  ~Empty~

Files after:

..\Desktop\A\
  ~Empty~
..\Desktop\B\
  -text_a.txt
  -text_b.txt

PS: I assume there is a little error in your code and oldFile should be dayOld or vice versa. You should edit this...


问:
How do procedures work with object types in PL/SQL?
I don't fully understand the purpose of procedures for PL/SQL object types. From reading online, the impression I got was that functions should not modify the data and should only return a value, instead procedures should be used, however it appears that for object types, changes in a procedure don't propagate outside the local context:

```<code>CREATE OR REPLACE TYPE TestType FORCE
AS OBJECT
(
    TestValue NUMBER

, CONSTRUCTOR FUNCTION TestType
    RETURN SELF AS RESULT

,   MEMBER PROCEDURE IncrementValueAsProcedure

,   MEMBER FUNCTION IncrementValueAsFunction
    RETURN TestType
)
/

CREATE OR REPLACE TYPE BODY TestType
AS
    CONSTRUCTOR FUNCTION TestType
    RETURN SELF AS RESULT
  IS
  BEGIN
        SELF.TestValue := 0;
        RETURN;
    END;

    MEMBER PROCEDURE IncrementValueAsProcedure
    IS
        MyType TestType := SELF;
    BEGIN
        MyType.TestValue := TestValue + 1;
    END;

    MEMBER FUNCTION IncrementValueAsFunction
    RETURN TestType
    IS
        MyType TestType := SELF;
    BEGIN
        MyType.TestValue := TestValue + 1;
        RETURN MyType;
    END;
END;
/

DECLARE
    MyTest TestType;
BEGIN
    MyTest := TestType();
    DBMS_OUTPUT.PUT_LINE(MyTest.TestValue);
    MyTest.IncrementValueAsProcedure();
    DBMS_OUTPUT.PUT_LINE(MyTest.TestValue);
    MyTest := MyTest.IncrementValueAsFunction();
    DBMS_OUTPUT.PUT_LINE(MyTest.TestValue);
END;
</code>```

This gives the output:

```<code>0
0
1
</code>```

So the change in the update procedure hasn't been picked up. What am I doing wrong?

答:
Oh, worked this out.

```<code>MEMBER PROCEDURE IncrementValueAsProcedure
IS
    MyType TestType := SELF;
BEGIN
    MyType.TestValue := TestValue + 1;
END;
</code>```

This creates a copy of the current object and updates it. The following works as expected:

```<code>MEMBER PROCEDURE IncrementValueAsProcedure
IS
BEGIN
    TestValue := TestValue + 1;
END;
</code>```

Body:
I don't fully understand the purpose of procedures for PL/SQL object types. From reading online, the impression I got was that functions should not modify the data and should only return a value, instead procedures should be used, however it appears that for object types, changes in a procedure don't propagate outside the local context:

CREATE OR REPLACE TYPE TestType FORCE
AS OBJECT
(
    TestValue NUMBER

, CONSTRUCTOR FUNCTION TestType
    RETURN SELF AS RESULT

,   MEMBER PROCEDURE IncrementValueAsProcedure

,   MEMBER FUNCTION IncrementValueAsFunction
    RETURN TestType
)
/

CREATE OR REPLACE TYPE BODY TestType
AS
    CONSTRUCTOR FUNCTION TestType
    RETURN SELF AS RESULT
  IS
  BEGIN
        SELF.TestValue := 0;
        RETURN;
    END;

    MEMBER PROCEDURE IncrementValueAsProcedure
    IS
        MyType TestType := SELF;
    BEGIN
        MyType.TestValue := TestValue + 1;
    END;

    MEMBER FUNCTION IncrementValueAsFunction
    RETURN TestType
    IS
        MyType TestType := SELF;
    BEGIN
        MyType.TestValue := TestValue + 1;
        RETURN MyType;
    END;
END;
/

DECLARE
    MyTest TestType;
BEGIN
    MyTest := TestType();
    DBMS_OUTPUT.PUT_LINE(MyTest.TestValue);
    MyTest.IncrementValueAsProcedure();
    DBMS_OUTPUT.PUT_LINE(MyTest.TestValue);
    MyTest := MyTest.IncrementValueAsFunction();
    DBMS_OUTPUT.PUT_LINE(MyTest.TestValue);
END;

This gives the output:

0
0
1

So the change in the update procedure hasn't been picked up. What am I doing wrong?

Body:
Oh, worked this out.

MEMBER PROCEDURE IncrementValueAsProcedure
IS
    MyType TestType := SELF;
BEGIN
    MyType.TestValue := TestValue + 1;
END;

This creates a copy of the current object and updates it. The following works as expected:

MEMBER PROCEDURE IncrementValueAsProcedure
IS
BEGIN
    TestValue := TestValue + 1;
END;


问:
SQL - how to get all rows in parent based on number of children of that parent?
I have 2 tables:

parent table: id, name

child table: id, name, id_parent

Now, I want to list rows in parent table have the number rows of children is 3.

答:
I edit my query like this.

```<code>select p.*, count(c.id)
from parents p
join children c
     on c.id_parent = p.id
group by p.id
having count(*) = 3
</code>```

is it ok ? jarlh

Body:
I edit my query like this.

select p.*, count(c.id)
from parents p
join children c
     on c.id_parent = p.id
group by p.id
having count(*) = 3

is it ok ? jarlh


问:
Legend in bar3 in MATLAB
I can't figure out how to create the legends (for colors) in the attached code?</p>

```<code>test1=[5 10 7;
    1 100 0;
    1 3 2];

test2=[10 15 10;
    10 80 10;
    5 5 15];

test3=[10 10 10;
    20 200 20;
    30 10 30];

core=bar3(test1);
set(core,'FaceColor',[1 0 0]); %red
for i=1:length(core)
    zz=get(core(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i);
        k=k+1;
    end
    set(core(i),'Zdata',zz);
end
hold on
core=bar3(test2);
set(core,'FaceColor',[0 1 1]);%cyan
hold off
for i=1:length(core)
    zz=get(core(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test3(k,i);
        k=k+1;
    end
    set(core(i),'Zdata',zz);
end
hold on
core=bar3(test3);
set(core,'FaceColor',[1 1 0]);%yellow
hold off
</code>```

答:
First, I would rename all cores to core1, core2 and core3 to correspond to test1, test2 and test3, and also not to override the handles. Then, if you check the size of each of these using e.g. size(core1), you will see that each of these contains 3 handles to 3 plots. All 3 have the same color, so you can just pick one handle and supply it to the legend as a first argument. So at the end you just need to add

```<code>legend([core1(1) core2(1) core3(1)], {'A', 'B', 'C'});
</code>```

The full code

```<code>test1=[5 10 7;
    1 100 0;
    1 3 2];

test2=[10 15 10;
    10 80 10;
    5 5 15];

test3=[10 10 10;
    20 200 20;
    30 10 30];

core1=bar3(test1);
set(core1,'FaceColor',[1 0 0]); %red
for i=1:length(core1)
    zz=get(core1(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core1)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i);
        k=k+1;
    end
    set(core1(i),'Zdata',zz);
end
legend({'A'});
hold on
core2=bar3(test2);
set(core2,'FaceColor',[0 1 1]);%cyan
hold off
for i=1:length(core2)
    zz=get(core2(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core2)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test3(k,i);
        k=k+1;
    end
    set(core2(i),'Zdata',zz);
end
hold on
core3=bar3(test3);
set(core3,'FaceColor',[1 1 0]);%yellow
hold off

legend([core1(1) core2(1) core3(1)], {'A', 'B', 'C'});
</code>```

Title: Legend in bar3 in MATLAB

Body:
I can't figure out how to create the legends (for colors) in the attached code?

test1=[5 10 7;
    1 100 0;
    1 3 2];

test2=[10 15 10;
    10 80 10;
    5 5 15];

test3=[10 10 10;
    20 200 20;
    30 10 30];

core=bar3(test1);
set(core,'FaceColor',[1 0 0]); %red
for i=1:length(core)
    zz=get(core(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i);
        k=k+1;
    end
    set(core(i),'Zdata',zz);
end
hold on
core=bar3(test2);
set(core,'FaceColor',[0 1 1]);%cyan
hold off
for i=1:length(core)
    zz=get(core(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test3(k,i);
        k=k+1;
    end
    set(core(i),'Zdata',zz);
end
hold on
core=bar3(test3);
set(core,'FaceColor',[1 1 0]);%yellow
hold off

Body:
First, I would rename all cores to core1, core2 and core3 to correspond to test1, test2 and test3, and also not to override the handles. Then, if you check the size of each of these using e.g. size(core1), you will see that each of these contains 3 handles to 3 plots. All 3 have the same color, so you can just pick one handle and supply it to the legend as a first argument. So at the end you just need to add

legend([core1(1) core2(1) core3(1)], {'A', 'B', 'C'});

The full code

test1=[5 10 7;
    1 100 0;
    1 3 2];

test2=[10 15 10;
    10 80 10;
    5 5 15];

test3=[10 10 10;
    20 200 20;
    30 10 30];

core1=bar3(test1);
set(core1,'FaceColor',[1 0 0]); %red
for i=1:length(core1)
    zz=get(core1(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core1)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i);
        k=k+1;
    end
    set(core1(i),'Zdata',zz);
end
legend({'A'});
hold on
core2=bar3(test2);
set(core2,'FaceColor',[0 1 1]);%cyan
hold off
for i=1:length(core2)
    zz=get(core2(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core2)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test3(k,i);
        k=k+1;
    end
    set(core2(i),'Zdata',zz);
end
hold on
core3=bar3(test3);
set(core3,'FaceColor',[1 1 0]);%yellow
hold off

legend([core1(1) core2(1) core3(1)], {'A', 'B', 'C'});


问:
How do you reverse a string in-place in JavaScript?
How do you reverse a string in-place in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse(), .charAt() etc.)?

答:
Something like this should be done following the best practices:

(function(){
 'use strict';
 var str = "testing";

 //using array methods
 var arr = new Array();
 arr = str.split("");
 arr.reverse();
 console.log(arr);

 //using custom methods
 var reverseString = function(str){

  if(str == null || str == undefined || str.length == 0 ){
   return "";
  }

  if(str.length == 1){
   return str;
  }

  var rev = [];
  for(var i = 0; i < str.length; i++){
   rev[i] = str[str.length - 1 - i];
  }
  return rev;
 }

 console.log(reverseString(str));

})();```

OwnerDisplayName: Jake

ContentLicense: CC BY-SA 4.0


问:
Remove Duplicate ids from select query
I have the following table

```<code>ID     NAME    POINT
100    AAA     100
100    AAA     150
100    AAA     70
200    DDD     100
200    DDD     65
300    FFF     50
</code>```

I would like to delete duplicate id from this table. I would like to get below

```<code>ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50
</code>```

I already used DISTINCT keyword in my select query likes this

```<code>SELECT DISTINCT ID,NAME,POINT FROM Tab ORDER BY ID;
</code>```

It is not ok. I just need one unique id per record.So How to remove duplicate ids from select query? My condition is If all records are the same then take the first record.

答:
Use the rowid pseudocolumn.

```<code>DELETE FROM your_table
WHERE rowid not in (SELECT MIN(rowid) FROM your_table GROUP BY id, name);
</code>```

If you have more columns in your PK, add them in the group by list.

Title: Remove Duplicate ids from select query

Body:
I have the following table

ID     NAME    POINT
100    AAA     100
100    AAA     150
100    AAA     70
200    DDD     100
200    DDD     65
300    FFF     50

I would like to delete duplicate id from this table. I would like to get below

ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50

I already used DISTINCT keyword in my select query likes this

SELECT DISTINCT ID,NAME,POINT FROM Tab ORDER BY ID;

It is not ok. I just need one unique id per record.So How to remove duplicate ids from select query? My condition is If all records are the same then take the first record.

Body:
Use the rowid pseudocolumn.

DELETE FROM your_table
WHERE rowid not in (SELECT MIN(rowid) FROM your_table GROUP BY id, name);

If you have more columns in your PK, add them in the group by list.


问:
Is there a "nice" way to advance a pointer to a struct by one byte?
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

```<code>#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}
</code>```

The compiler reports an error on the "nice" part:

```<code>% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^
</code>```

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

答:
This doesn't make much sense. If you were to increase the struct pointer by 1 byte, you would end up with a misaligned address, which would be problematic on most systems. I'll have to assume that your system is not any of the mainstream 32/64 bit CPUs (not x86, ARM, PowerPC etc) or otherwise your question makes no sense.

To increase the address by one byte, simply do this:

```<code>ps = (s_t*) ((uintptr_t)ps + 1);
</code>```

Body:
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}

The compiler reports an error on the "nice" part:

% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

Body:
This doesn't make much sense. If you were to increase the struct pointer by 1 byte, you would end up with a misaligned address, which would be problematic on most systems. I'll have to assume that your system is not any of the mainstream 32/64 bit CPUs (not x86, ARM, PowerPC etc) or otherwise your question makes no sense.

To increase the address by one byte, simply do this:

ps = (s_t*) ((uintptr_t)ps + 1);


问:
Create an Array from existing array with additional element added
I have a method that takes vararg Array of strings

```<code>void count(long delta, String... tags);
</code>```

I have a predefined array of tags for the most cases

```<code>String[] tags = { "foo_tag:Foo",
                  "bar_tag:Bar",
                  "baz_tag:Baz"
                };
</code>```

and only one tag to be added to predefined tags in each call "project_id:12345"

So the call of count should look like this:

```<code>count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");
</code>```

How can I simply create a new array containing my existing one plus additional element just in place of calling the method?

Something like this hypothetical Arrays.append method:

```<code>count(delta, Arrays.append(tags, "project_id:12345"));
</code>```

This is storing statistics operation, not a business logic, so I want this operation to be as fast as possible.

Currently, I have helper method appendTag, but it doesn't look elegant as for me

```<code>private String[] appendTag(String[] tags, String s)
{
    String[] result = new String[tags.length + 1];
    System.arraycopy(tags, 0, result, 0, tags.length);
    result[result.length-1] = s;
    return result;
}
</code>```

答:
In java, arrays have a fixed size so it won't be possible to extend an array by appending new elements to it.

You will need to create a new array with a larger size and copy the first one elements into it, then add new elements to it, but it's not dynamic yet.

What I can suggest is to use a Collection maybe an ArrayList you will profit from its built-in methods like .add()

Body:
I have a method that takes vararg Array of strings

void count(long delta, String... tags);

I have a predefined array of tags for the most cases

String[] tags = { "foo_tag:Foo",
                  "bar_tag:Bar",
                  "baz_tag:Baz"
                };

and only one tag to be added to predefined tags in each call "project_id:12345"

So the call of count should look like this:

count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");

How can I simply create a new array containing my existing one plus additional element just in place of calling the method?

Something like this hypothetical Arrays.append method:

count(delta, Arrays.append(tags, "project_id:12345"));

This is storing statistics operation, not a business logic, so I want this operation to be as fast as possible.

Currently, I have helper method appendTag, but it doesn't look elegant as for me

private String[] appendTag(String[] tags, String s)
{
    String[] result = new String[tags.length + 1];
    System.arraycopy(tags, 0, result, 0, tags.length);
    result[result.length-1] = s;
    return result;
}


问:
How to fill the entire cell with a color in CKEditor
I created a plugin that allows me to put a background color in a table cell in 1 click.
The problem is that I do not know how to make the whole cell colored.

Here is the code of my plugin.

CKEDITOR.plugins.add( 'TrameF', { //meme nom que le dossier associé
    init: function( editor ) {

        editor.addCommand( 'TrameF', {
            exec: function( editor ) {

                editor.insertHtml( '
'+
                    '
 ');
            }
         });
    }
});```

Can someone help me ? Thanks, have a good day.

答:
You need to get the  element and set its style. To do that, you need to traverse backwards the DOM from the point you clicked:

```<code>var el = editor.getSelection().getStartElement();
while (el) {
    if (el.getName() == 'td' || el.getName() == 'th') {
        el.setStyle('background-color', '#BCE0EA');
        break;
    }
    el = el.getParent();
}
</code>```

Body:
I created a plugin that allows me to put a background color in a table cell in 1 click.
The problem is that I do not know how to make the whole cell colored.

Here is the code of my plugin.

CKEDITOR.plugins.add( 'TrameF', { //meme nom que le dossier associé
    init: function( editor ) {

        editor.addCommand( 'TrameF', {
            exec: function( editor ) {

                editor.insertHtml( '
'+
                    '
 ');
            }
         });
    }
});

Can someone help me ? Thanks, have a good day.

Body:
You need to get the <td> element and set its style. To do that, you need to traverse backwards the DOM from the point you clicked:

var el = editor.getSelection().getStartElement();
while (el) {
    if (el.getName() == 'td' || el.getName() == 'th') {
        el.setStyle('background-color', '#BCE0EA');
        break;
    }
    el = el.getParent();
}


问:
Updating data on rows deleted event
I have a custom page with a form and a grid. When a row from a grid is deleted, I want to update some other rows. I am therefore handling the rowdeleted event. I confirmed (through debugging) that the event is firing correctly and that the data is being updated correctly.

The only issue I have is that the screen still shows the old values. My delete row correctly disappears but the other rows do not get updated.

For each row that I change, I am calling the Update method of the Data View. However, this still does not refresh the user interface.
Interesting, if I save, all my changes get correctly updated to the database. Which confirms that this is a UI isssue.

Is there any additional step that I need to perform to refresh the user interface? Or should I just avoid doing updates in Row Deleted event?

答: I managed to solve the issue by calling View.RequestRefresh(). However, I am not sure whether this is a standard practice. But I did find it used in several places in the Acumatica code</p>

Title: Updating data on rows deleted event


问:
How to remove 'null' values in laravel controller while retrieving data from database
The results in $data variable. I want to remove null values at output.

The following code:

```<code>    $data = json_decode(json_encode($data),true);
</code>```

I am copying $data to $data1 later to merge the two variables using below code:

```<code>$data1 = $data;
$unique= array_merge($data1,$data);
$final =array_values(array_map("unserialize",array_unique(array_map("serialize", $unique))));
</code>```

答:
You can use array_filter to remove the null value fro the array

Do like this

```<code>$data = json_decode(json_encode($data),true);
$data =array_filter($data);
</code>```

Modification

As you are dealing with Multi dimensional array (as you said in comment),to remove the array which have null data you need to use array_map , array_filter and in_array.

Do like this

```<code>$data = json_decode(json_encode($data),true);
$data =array_map('array_filter',$data);
$data=array_map(function ($data){
            if(!in_array(null,$data))
                return $data;
        },$data);
$data=array_filter($data);
</code>```

It will give output as

It will work for you.

Body:
The results in $data variable. I want to remove null values at output.

The following code:

    $data = json_decode(json_encode($data),true);

I am copying $data to $data1 later to merge the two variables using below code:

$data1 = $data;
$unique= array_merge($data1,$data);
$final =array_values(array_map("unserialize",array_unique(array_map("serialize", $unique))));

Body:
You can use array_filter to remove the null value fro the array

Do like this

$data = json_decode(json_encode($data),true);
$data =array_filter($data);

Modification

As you are dealing with Multi dimensional array (as you said in comment),to remove the array which have null data you need to use array_map , array_filter and in_array.

Do like this

$data = json_decode(json_encode($data),true);
$data =array_map('array_filter',$data);
$data=array_map(function ($data){
            if(!in_array(null,$data))
                return $data;
        },$data);
$data=array_filter($data);

It will give output as

It will work for you.


问:
Comment shortcut Android Studio
I'm searching for useful Android Studio keyboard shortcut for commenting code, as in Sublime Text or Eclipse.

When I press either cmd+/ or cmd+maj+/ nothing happens...

答:
For multiline comment in android studio

select the statement that you want to commented then

use ctrl+shift+/

```<code>and for removing mutiline comment

select the statement that you want to uncommented then

use **ctrl+shift+/**
</code>```

SINGLE LINE COMMENT

For single line comment

use ctrl+/

Title: Comment shortcut Android Studio

Body:
For multiline comment in android studio

select the statement that you want to commented then

use ctrl+shift+/

and for removing mutiline comment

select the statement that you want to uncommented then

use **ctrl+shift+/**

SINGLE LINE COMMENT

For single line comment

use ctrl+/


问:
Error in input pipeline using queues in tensorflow
I am getting this error for the below mentioned code. Kindly help me out with this.
This code is printing variables number of batches everytime I run this code. I am unable to figure out the error.

OutOfRangeError (see above for traceback): FIFOQueue
  '_2_batch/fifo_queue' is closed and has insufficient elements
  (requested 15, current size 0)     [[Node: batch =
  QueueDequeueManyV2[component_types=[DT_FLOAT], timeout_ms=-1,
  _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, batch/n)]]

```<code>import tensorflow as tf
import numpy as np
import os

batch_size = 16
min_queue = 256

def load_image():
    length = calculate_size("./Coco_subset_5356")

    names = tf.train.match_filenames_once("./Coco_subset_5356/*.jpg")

    # Extracted names from the file
    filename_queue = tf.train.string_input_producer(names)

    #Initialised the File reader
    reader = tf.WholeFileReader()

    key, value = reader.read(filename_queue)
    my_img = tf.image.decode_jpeg(value, channels = 3)
    my_img = tf.image.resize_images(my_img, [256,256])
    my_img.set_shape((256,256,3))

    print(length)

    images = tf.train.batch(
      [my_img],
      batch_size=batch_size,
      num_threads=1,
      capacity=min_queue + 3*batch_size)

     print(images)

with tf.Session() as sess:
    #sess.run(init_op)
    tf.local_variables_initializer().run()
    #print(tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES))

    #For coordination between queue runner and the reader
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord = coord)
    for j in range(length/batch_size):
        #optimizer.run(feed_dict={input_batch: images[i])
        x = sess.run(images)
        print(j)
        print(x.shape)

    coord.request_stop()
    coord.join(threads)

def calculate_size(img_dir):
    file = []
    for subdir, dirs, files in os.walk(img_dir):
        for i in files:
            i = os.path.join(img_dir, i)
            file.append(i)
        length = len(file)
    return length

load_image()
</code>```

答:
Disclaimer: This is not a proper answer, but I can't post code in a comment and this might point you in the right direction.

As anticipated in my comment to the question, I had the very same error on one of my datasets. In my case, the problem was the fact that not all images in my dataset could be decoded as jpg files. Truncated images and, in my case, 1x1 pixel images were hidden in my data and whenever I'd try to prcess the dataset I'd have the queues closing reporting errors I had a hard time fiding.

I solved the problem writing a small filter script that goes through all files one-by-one and logs those it cannot process:

import tensorflow as tf
import glob

image_data_placeholder = tf.placeholder(tf.string)

filenames = glob.glob(r'C:\my_test_folder\*.jpg')
decoded_img_op = tf.image.decode_jpeg(image_data_placeholder)

with tf.Session() as sess:
  for fn in filenames:
    with open(fn, 'rb') as fp:
      image_data = fp.read()
    try:
      sess.run(decoded_img_op, feed_dict={image_data_placeholder:image_data})
    except:
      # log the filename o the broken image (or delete/move/etc)
      print('Cannot decode file {}'.format(fn))
```

It's not the most efficient of implementations, but it was good enough for my use-case.

Body:
I am getting this error for the below mentioned code. Kindly help me out with this.
This code is printing variables number of batches everytime I run this code. I am unable to figure out the error.

OutOfRangeError (see above for traceback): FIFOQueue
  '_2_batch/fifo_queue' is closed and has insufficient elements
  (requested 15, current size 0)     [[Node: batch =
  QueueDequeueManyV2[component_types=[DT_FLOAT], timeout_ms=-1,
  _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, batch/n)]]

import tensorflow as tf
import numpy as np
import os

batch_size = 16
min_queue = 256

def load_image():
    length = calculate_size("./Coco_subset_5356")

    names = tf.train.match_filenames_once("./Coco_subset_5356/*.jpg")

    # Extracted names from the file
    filename_queue = tf.train.string_input_producer(names)

    #Initialised the File reader
    reader = tf.WholeFileReader()

    key, value = reader.read(filename_queue)
    my_img = tf.image.decode_jpeg(value, channels = 3)
    my_img = tf.image.resize_images(my_img, [256,256])
    my_img.set_shape((256,256,3))

    print(length)

    images = tf.train.batch(
      [my_img],
      batch_size=batch_size,
      num_threads=1,
      capacity=min_queue + 3*batch_size)

     print(images)

with tf.Session() as sess:
    #sess.run(init_op)
    tf.local_variables_initializer().run()
    #print(tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES))

    #For coordination between queue runner and the reader
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord = coord)
    for j in range(length/batch_size):
        #optimizer.run(feed_dict={input_batch: images[i])
        x = sess.run(images)
        print(j)
        print(x.shape)

    coord.request_stop()
    coord.join(threads)

def calculate_size(img_dir):
    file = []
    for subdir, dirs, files in os.walk(img_dir):
        for i in files:
            i = os.path.join(img_dir, i)
            file.append(i)
        length = len(file)
    return length

load_image()

Body:
Disclaimer: This is not a proper answer, but I can't post code in a comment and this might point you in the right direction.

As anticipated in my comment to the question, I had the very same error on one of my datasets. In my case, the problem was the fact that not all images in my dataset could be decoded as jpg files. Truncated images and, in my case, 1x1 pixel images were hidden in my data and whenever I'd try to prcess the dataset I'd have the queues closing reporting errors I had a hard time fiding.

I solved the problem writing a small filter script that goes through all files one-by-one and logs those it cannot process:

import tensorflow as tf
import glob

image_data_placeholder = tf.placeholder(tf.string)

filenames = glob.glob(r'C:\my_test_folder\*.jpg')
decoded_img_op = tf.image.decode_jpeg(image_data_placeholder)

with tf.Session() as sess:
  for fn in filenames:
    with open(fn, 'rb') as fp:
      image_data = fp.read()
    try:
      sess.run(decoded_img_op, feed_dict={image_data_placeholder:image_data})
    except:
      # log the filename o the broken image (or delete/move/etc)
      print('Cannot decode file {}'.format(fn))

It's not the most efficient of implementations, but it was good enough for my use-case.


问:
Validate a SQL WHERE Clause in javascript
How can I validate a string and know if it is a valid SQL where clause.
Ex of invalid string: WHERE 1=1  AND EMPRESA = 'CMIP' AND CD_MAQ ==="jjj"
Ex of valid string :WHERE 1=1  AND EMPRESA = 'CMIP' AND CD_MAQ ="jjj"

Appreciate your help.

答:
Sorry you cannot do this easily... Unless you fancy writing a SQL Parser in Javascript.

One solution would be to post the query to a backend which runs it in a try catch block and returns if there was an error or not.

I dread to think what the regex/rules list for this validation would be doing it manually.

Why do you want to do this?? Explain your actual goal rather than your suggested solution and we can maybe come up with a better idea...
If you are passing a WHERE clause to SQL from a search page as you suggest - this is not the correct way to do it...

Please use Parameterized queries instead.

Also read up on SQL Injection: What is SQL injection?


问:
Using C# to connect to ConnectWise API
I intend to create a program using C# which will update tickets in ConnectWise using, eventually, data from another API.

Thus far I've wanted to test to GET some invoices. For this I installed the latest SDK and referenced it in Visual studio (SDK 2017.3).

The documentation claims that this should suffice:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConnectWiseDotNetSDK;
using ConnectWiseDotNetSDK.ConnectWise;
using ConnectWiseDotNetSDK.ConnectWise.Client;
using ConnectWiseDotNetSDK.ConnectWise.Client.System.Api;
using ConnectWiseDotNetSDK.ConnectWise.Client.System.Model;

private static List<Invoice> getInvoices()
{
    var client = getApiClient();
    var invoicesApi = new InvoiceApi(client);
    var response = invoicesApi.GetInvoices();
    var invoices = response.GetResult<List<Invoice>>();
    foreach (var invoice in invoices)
    {
        Console.WriteLine(invoice);
    }
    return invoices;
}
</code>```

(where I have added all the using .... rows, the documentation does not clarify which are needed).

This however gives me an error that getApiClient() does not exist in this context. I reckon I must create the function, which will provide my authentication etc. Thus I've done:

```<code>private static getApiClient()
{
    string BaseUri = "https://eu-myconnectwise.net/v4_6_Release/apis/3.0/finance/invoices"
    string ContentType = "application/json";
    string Authstring = "xxxxyyxxxx";
}
</code>```

This does not work. I have no idea how to create the client variable in the main program.

Has anyone gotten the SDK to work using C#?

答:
You can use the tool SoapUI (enter link description here).
This tool helps you to test all different WEB Interfaces.</p>

Title: Using C# to connect to ConnectWise API

Body:
I intend to create a program using C# which will update tickets in ConnectWise using, eventually, data from another API.

Thus far I've wanted to test to GET some invoices. For this I installed the latest SDK and referenced it in Visual studio (SDK 2017.3).

The documentation claims that this should suffice:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConnectWiseDotNetSDK;
using ConnectWiseDotNetSDK.ConnectWise;
using ConnectWiseDotNetSDK.ConnectWise.Client;
using ConnectWiseDotNetSDK.ConnectWise.Client.System.Api;
using ConnectWiseDotNetSDK.ConnectWise.Client.System.Model;

private static List<Invoice> getInvoices()
{
    var client = getApiClient();
    var invoicesApi = new InvoiceApi(client);
    var response = invoicesApi.GetInvoices();
    var invoices = response.GetResult<List<Invoice>>();
    foreach (var invoice in invoices)
    {
        Console.WriteLine(invoice);
    }
    return invoices;
}

(where I have added all the using .... rows, the documentation does not clarify which are needed).

This however gives me an error that getApiClient() does not exist in this context. I reckon I must create the function, which will provide my authentication etc. Thus I've done:

private static getApiClient()
{
    string BaseUri = "https://eu-myconnectwise.net/v4_6_Release/apis/3.0/finance/invoices"
    string ContentType = "application/json";
    string Authstring = "xxxxyyxxxx";
}

This does not work. I have no idea how to create the client variable in the main program.

Has anyone gotten the SDK to work using C#?


问:
Fetch particular fields from Firebase database
I am working on firebase project, where i stored user info within a Table.
Now my requirement is to show all user's in a Table.
Here is my database snapshot

I can fetch all user's with from database using

```<code>       if let user = FIRAuth.auth()?.currentUser {
            self.ref?.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let name = value?["name"] as? String ?? ""
                let email = value?["email"] as? String ?? ""

            // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }
</code>```

Above code return me users array with bod, email, name, gender.
But i want to fetch only email and name of users.
Is there a way to fetch only specified fields from Database ?

答:
When you read a node, you'll have to retrieve its entire content. So, there is no way to fetch only specific fields from the data returned on reading a path.

Having said that, if it's possible for your use case, I would suggest you to denormalise data with the purpose of queries that only retrieve the information that you need.

For doing that, you can have a separate node that can be called something like Users-NameandEmailList. Now, in this table, have user uids as your child keys, and each entry shall have only a an email and name field.

Something like this :-

```<code>Users-NameandEmailList :{

       user1key :{
             name : "ABC"
             email : "abc@abc.com"
                 },
       user2key : {..},

                        }
</code>```

I agree that this could lead to replication of data, but if you want to minimise download redundancy and optimise for speed, then this is the way to go!

Body:
I am working on firebase project, where i stored user info within a Table.
Now my requirement is to show all user's in a Table.
Here is my database snapshot

I can fetch all user's with from database using

       if let user = FIRAuth.auth()?.currentUser {
            self.ref?.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let name = value?["name"] as? String ?? ""
                let email = value?["email"] as? String ?? ""

            // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }

Above code return me users array with bod, email, name, gender.
But i want to fetch only email and name of users.
Is there a way to fetch only specified fields from Database ?

Body:
When you read a node, you'll have to retrieve its entire content. So, there is no way to fetch only specific fields from the data returned on reading a path.

Having said that, if it's possible for your use case, I would suggest you to denormalise data with the purpose of queries that only retrieve the information that you need.

For doing that, you can have a separate node that can be called something like Users-NameandEmailList. Now, in this table, have user uids as your child keys, and each entry shall have only a an email and name field.

Something like this :-

Users-NameandEmailList :{

       user1key :{
             name : "ABC"
             email : "abc@abc.com"
                 },
       user2key : {..},

                        }

I agree that this could lead to replication of data, but if you want to minimise download redundancy and optimise for speed, then this is the way to go!


问:
Application crashes after installing iOS 4.2
I recently installed iOS 4.2 for my iPod after then my application started to crash.

The scenario is: I launch my application wait until it's up and running then hit the iPod home button then launch my application again, my application starts again for seconds then crashes.

my application is a job search engine, so in all of its navigation pages it's communicating with internet server.

I think the problem has to do with applicationDidEnterBackground, applicationWillEnterForeground, or applicationDidBecomeActive methods. I do not have an code in these methods and I do not know if I need to, to prevent the crash.

I do not understand what happens after I hit the home button and my application goes to the background:

will it still be running in the background (because of the multithreading thing in iOS4.2).

Sometimes when I relaunch my application it goes to last page I left in before hitting the home button and sometime it starts from the home page.

I do not understand what's going on, I just want it every time it starts to start in the home page.

I was just about to submit my application to the Apple Store just before I updated to iOS4.2 and the crash starts to happen. I'd really appreciate if someone can help me with this issue that I'm not even able/or know how to debug.

Thanks a lot in advance.
Regards,

答:
Xcode / Organizer will show your device crash logs.

Xcode -> COMMAND+CONTROL+O -> Device Logs or you (making sure the device is connected) can select the iPod from the list of devices, then choose Device Logs.

You don't need to have any code in the applicationDidEnterBackground, applicationWillEnterForeground, or applicationDidBecomeActive delegates, so that's not making your app crash.

I would definitely check out some of those logs in Organizer. Maybe post some of them here, or pastie.org


问:
My JQuery post data to 'textbox' how to post it to 'div'?
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});
```

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

答:
I think that you must use .text or .html in place .value.
look at this example using jquery:</p>

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>text demo</title>
  <style>
  p {
    color: blue;
    margin: 8px;
  }
  b {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p><b>Test</b> Paragraph.</p>
<p></p>

<script>
var str = $( "p:first" ).text();
$( "p:last" ).html( str );
</script>

</body>
</html>
</code>```

Body:
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

Body:
I think that you must use .text or .html in place .value.
look at this example using jquery:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>text demo</title>
  <style>
  p {
    color: blue;
    margin: 8px;
  }
  b {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p><b>Test</b> Paragraph.</p>
<p></p>

<script>
var str = $( "p:first" ).text();
$( "p:last" ).html( str );
</script>

</body>
</html>


问:
Angular 2 Field Masking
I want to mask a field for example:  having phone number of 10 digit (123-123-1234) I need to mask in such a way that (xxx-xxx-1234). Also While submit the page I need to send original variable (123-123-1234) to service.

Any help would be greatly appreciated.

Thanks.

答:
You can create a pipe for it like below:

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'mask'
})
export class NumberMaskPipe implements PipeTransform {
  transform(number: string): string {
    const visibleDigits = 4;
    let maskedSection = number.slice(0, -visibleDigits);
    let visibleSection = number.slice(-visibleDigits);
    return maskedSection.replace(/./g, '*') + visibleSection;
  }
}
</code>```

And in your component you can do:

```<code>export class PhoneNumberComponent implements OnInit {
  phoneNumber: string;

  constructor() {}

  ngOnInit() {
    this.phoneNumber = "2131232131238867";
  }
}
</code>```

Finally in the component:

```<code><p>Your phone number is: {{ phoneNumber | mask }}</p>
</code>```

Pipe here is dynamic so even if user enters different number of digits it will only mask till but not the last four digits. Please try the example with different number of digits as well.

Here's a working plunker:https://plnkr.co/edit/NKRQpVB1Darw8MxrqucP?p=preview

Title: Angular 2 Field Masking

Body:
You can create a pipe for it like below:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'mask'
})
export class NumberMaskPipe implements PipeTransform {
  transform(number: string): string {
    const visibleDigits = 4;
    let maskedSection = number.slice(0, -visibleDigits);
    let visibleSection = number.slice(-visibleDigits);
    return maskedSection.replace(/./g, '*') + visibleSection;
  }
}

And in your component you can do:

export class PhoneNumberComponent implements OnInit {
  phoneNumber: string;

  constructor() {}

  ngOnInit() {
    this.phoneNumber = "2131232131238867";
  }
}

Finally in the component:

<p>Your phone number is: {{ phoneNumber | mask }}</p>

Pipe here is dynamic so even if user enters different number of digits it will only mask till but not the last four digits. Please try the example with different number of digits as well.

Here's a working plunker:https://plnkr.co/edit/NKRQpVB1Darw8MxrqucP?p=preview


Title: how to insert multi-row in mysql if it's not exist

Body:
I just want to insert multi-row at same time.
but I want to ignore each one that already in table.
I just make query but It had a syntax problem.
Any one can help me to solve it?
here is my sql query:

INSERT INTO `targetmediaid` (`pageid`, `targetpageid`, `mediaid`)
SELECT "4578583556", "5633144318", "1544121716250721765_5633144318"  UNION
SELECT "4578583556", "5633144318", "1544121605403655131_5633144318"  UNION
SELECT "4578583556", "5633144318", "1544121513523117304_5633144318"  UNION
SELECT "4578583556", "5633144318", "1544121293112402936_5633144318"  UNION
SELECT "4578583556", "5633144318", "1544121119770209275_5633144318"  UNION
SELECT "4578583556", "5633144318", "1544121021170710600_5633144318"  UNION
SELECT "4578583556", "5633144318", "1544120871450810242_5633144318"  UNION
SELECT "4578583556", "5633144318", "1542556083004139499_5633144318"  as t
WHERE NOT EXISTS
   ( SELECT `pageid`, `targetpageid`, `mediaid`
       FROM `targetmediaid`
      WHERE `mediaid`
         IN  ("1544121716250721765_5633144318" ,
              "1544121605403655131_5633144318" ,
              "1544121513523117304_5633144318" ,
              "1544121293112402936_5633144318" ,
              "1544121119770209275_5633144318" ,
              "1544121021170710600_5633144318" ,
              "1544120871450810242_5633144318" ,
              "1542556083004139499_5633144318"
             )

Body:
Create a unique index on pageid, targetpageid, mediaid columns and use INSERT IGNORE statement.

INSERT IGNORE INTO targetmediaid (pageid, targetpageid, mediaid) VALUES ("4578583556", "5633144318", "1544121716250721765_5633144318"), ("4578583556", "5633144318", "1544121605403655131_5633144318"),("4578583556", "5633144318", "1544121513523117304_5633144318")..... and so on.


问:
How to pass an object into a variable in JavaScript?
I have a form in HTML where there is a field that has the ID attribute of Field 1, where the value is taken and assigned to variable Field1 that then gets fed into the var template.

I create a new date object and assign it to the var creationTime and I need to pass this also into the var template. How can I achieve this? The code below does not work...

```<code>$(function () {
$('#DownloadButton').click(update);
});

var creationTime = new Date();

var template = [
'<Field1><?Field1?></Field1>',
'<creationtime><?creationTime?></creationTime>',

 ].join('\r\n');

function update() {
  var variables = {

'Field1': $('#Field1').val(),
};

 var newXml = template.replace(/<\?(\w+)\?>/g,
function(match, name) {
  return variables[name];
    });
</code>```

答:
You need to put creationTime inside variables object where your replace function does lookup.

$(function () {
$('#DownloadButton').click(function() {
    console.log(update())
  });
});

var template = [
'<Field1><?Field1?></Field1>',
'<creationtime><?creationTime?></creationTime>',

 ].join('\r\n');

function update() {
  var variables = {
    'Field1': $('#Field1').val(),
    creationTime: new Date
  };

 return template.replace(/<\?(\w+)\?>/g, function(match, name) { return variables[name];});
}

console.log(update())

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Field1">
<button id="DownloadButton">DownloadButton</button></code>```

Body:
I have a form in HTML where there is a field that has the ID attribute of Field 1, where the value is taken and assigned to variable Field1 that then gets fed into the var template.

I create a new date object and assign it to the var creationTime and I need to pass this also into the var template. How can I achieve this? The code below does not work...

$(function () {
$('#DownloadButton').click(update);
});

var creationTime = new Date();

var template = [
'<Field1><?Field1?></Field1>',
'<creationtime><?creationTime?></creationTime>',

 ].join('\r\n');

function update() {
  var variables = {

'Field1': $('#Field1').val(),
};

 var newXml = template.replace(/<\?(\w+)\?>/g,
function(match, name) {
  return variables[name];
    });

Body:
You need to put creationTime inside variables object where your replace function does lookup.

$(function () {
$('#DownloadButton').click(function() {
    console.log(update())
  });
});

var template = [
'<Field1><?Field1?></Field1>',
'<creationtime><?creationTime?></creationTime>',

 ].join('\r\n');

function update() {
  var variables = {
    'Field1': $('#Field1').val(),
    creationTime: new Date
  };

 return template.replace(/<\?(\w+)\?>/g, function(match, name) { return variables[name];});
}

console.log(update())

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Field1">
<button id="DownloadButton">DownloadButton</button>


问:
Sequencing Components in Feature Element
I want to replace a file that has been installed by my installer. In the following code the "OneCoreFiles" component should install the files first time( which is working) and the component "ConfigCopyFile" should replace that config file.

But the code is not working as expected. The component 'ConfigCopyFile' is getting executed first and then the 'OnecoreFiles'. I want it to work the other way.

I am still learning WIX and thought that the components in Feature elements are executed in the order in which they are declared.

Code Snippet:

```<code><Component Id="ConfigCopyFile" Guid="{98E61055-5A84-4003-90D1-7A67677D7465}">
  <Condition>CONFIGFILEEXISTS</Condition>
  <CopyFile Id="ConfigFileId" SourceProperty="CONFIGFILEEXISTS" DestinationProperty  ="INSTALLDIR"/>
</Component>

<Feature Id="ProductFeature" Title="OneCore Features" Level="1">
        <ComponentRef Id="LogEntries" />
        <ComponentGroupRef Id="OneCoreFiles" />
        <ComponentRef Id="AppDBConfiguration" />
        <ComponentRef Id="SqlServerConfiguration" />
        <ComponentRef Id="OracleConfiguration" />
        <ComponentRef Id="IISConfiguration" />
        <ComponentRef Id="ConfigCopyFile" />
    </Feature>
</code>```

This must be quite simple to solve. Am I missing something. Please advice.

答:
You are thinking of WiX in the wrong way. It's not a scripting language. It's a way of representing Windows Installer databases which are declarative in nature not imperative.   If I list a bunch of components and files it's non deterministic the order the files will be copied.  I'm only saying that these files need to be installed not how to install them.

Windows Installer does expose sequence tables which drive the order of things ( such as create folders then copy files ) but it doesn't micromanage to the level of copy this file before that file.

Suggested  InstallExecute Sequence

InstallExecuteSequence Table

Body:
I want to replace a file that has been installed by my installer. In the following code the "OneCoreFiles" component should install the files first time( which is working) and the component "ConfigCopyFile" should replace that config file.

But the code is not working as expected. The component 'ConfigCopyFile' is getting executed first and then the 'OnecoreFiles'. I want it to work the other way.

I am still learning WIX and thought that the components in Feature elements are executed in the order in which they are declared.

Code Snippet:

<Component Id="ConfigCopyFile" Guid="{98E61055-5A84-4003-90D1-7A67677D7465}">
  <Condition>CONFIGFILEEXISTS</Condition>
  <CopyFile Id="ConfigFileId" SourceProperty="CONFIGFILEEXISTS" DestinationProperty  ="INSTALLDIR"/>
</Component>

<Feature Id="ProductFeature" Title="OneCore Features" Level="1">
        <ComponentRef Id="LogEntries" />
        <ComponentGroupRef Id="OneCoreFiles" />
        <ComponentRef Id="AppDBConfiguration" />
        <ComponentRef Id="SqlServerConfiguration" />
        <ComponentRef Id="OracleConfiguration" />
        <ComponentRef Id="IISConfiguration" />
        <ComponentRef Id="ConfigCopyFile" />
    </Feature>

This must be quite simple to solve. Am I missing something. Please advice.


问:
Formula for Row Number will Change Itself When Table Expands
I've been using a formula to create row numbers for an expanding table at Column A, with the formula beginning as

```<code>=IF($C2="","",COUNTA($C$2:$C2))
</code>```

The situation can be recreated when:

I Have a number of rows in the table, lets say 10 (therefore, C2 to
C11 is filled)

At column A, at the end of this table in the example, the formula at
A11 should be

```<code> =IF($C11="","",COUNTA($C$2:$C11))
</code>```

I type a number outside of the table, at C12

The table auto expands

But Now, look at A11 and A12.....why are their formulas
identical?

Also, A11's font was changed on its own

This made me unable to quickly expand the table without manually filling down the formula for column A every time I expand the table. Can anyone point me to the right direction to stop this from happening?

答:
If you don't have any irrelevant data under your table, you can try passing the whole column to COUNTA() formula:

```<code>COUNTA($C:$C)
</code>```

Body:
I've been using a formula to create row numbers for an expanding table at Column A, with the formula beginning as

=IF($C2="","",COUNTA($C$2:$C2))

The situation can be recreated when:

I Have a number of rows in the table, lets say 10 (therefore, C2 to
C11 is filled)

At column A, at the end of this table in the example, the formula at
A11 should be

 =IF($C11="","",COUNTA($C$2:$C11))

I type a number outside of the table, at C12

The table auto expands

But Now, look at A11 and A12.....why are their formulas
identical?

Also, A11's font was changed on its own

This made me unable to quickly expand the table without manually filling down the formula for column A every time I expand the table. Can anyone point me to the right direction to stop this from happening?

Body:
If you don't have any irrelevant data under your table, you can try passing the whole column to COUNTA() formula:

COUNTA($C:$C)


问:
application server from angular cli not able to reference style.css
I am starting my angular application using angular cli using ng serve command.
The application is not able to serve the style.css file and I get a 404 on the browser.

My style.css and index.html are at the same level under the src folder.
In my index.html I am referencing style.css as below

```<code><link rel="stylesheet" href="styles.css">
</code>```

I also see that styles.css is referenced in angular-cli.json file

```<code>"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
</code>```

How do I figure out why I am getting a 404 when the app is trying to load styles.css

below is my folder structure

```<code>web/
  angular-cli.json
  src/
    index.html
    styles.css
  app/
</code>```

答:
Once your project is compiled, all files in the angular-cli.json are bundled. It means they are all re-written in a vendor file, which changes name and is minified.

This is means that putting a reference to style.css in your index.html gives a 404, since the file doesn't exist anymore. Just remove the reference and you should be good to go.

Body:
I am starting my angular application using angular cli using ng serve command.
The application is not able to serve the style.css file and I get a 404 on the browser.

My style.css and index.html are at the same level under the src folder.
In my index.html I am referencing style.css as below

<link rel="stylesheet" href="styles.css">

I also see that styles.css is referenced in angular-cli.json file

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],

How do I figure out why I am getting a 404 when the app is trying to load styles.css

below is my folder structure

web/
  angular-cli.json
  src/
    index.html
    styles.css
  app/


问:
JavaFX new custom pop out window
I am searching for the example of pop out windows in JavaFX.
I have JavaFX application and at one point I need a pop out window to appear. this popout windows needs some complicated inputs which I need to process and check and come back to main appliation/window.

Now the problem is I can not find anywhere an example how in one JavaFX controller class call now JavaFX pop out window? I only find examle how to make Dialog pop out windows but I can not find example of a new pop out window based on JavaFX (I saw one solution where there is two windows in paralel but I would need one to be created only when needed).

Do you know of such example of JavaFx custom popout window?

答:
Khalid SAB 'S answer is great. If you are using sceneBuilder to create fxml file , don't set the setController (in the function showPopupWindow()).

just use -

FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml.file"));

Because fxml file automatically initialize the related class.

Title: JavaFX new custom pop out window


问:
Is salting with a hashed version of the user's password just as secure as salting with a pre-defined string?
Basically, what I'm asking is if salting a password by appending a hashed version of it to the end of it is just as secure as salting with a different string. So:

Is this:

```<code>$pass = "pass";
$salt = sha1(md5($pass));
$pass = md5($pass.$salt);
</code>```

As secure as this?

```<code>$pass = "pass";
$salt = "4D9ds*^dkrUI45^#dkd*3fD8&!dlvd*";
$pass = md5($pass.$salt);
</code>```

答:
The first example is as secure as hashing without using any salt at all, because it still just requires the password and nothing more to crack. In other words, you are just applying the hashing functions to the same thing a few times more.

A better bet is still to create a salt for each user and store it alongside, separately. A fixed salt for everyone is alright, I guess, because you cannot use the password to determine the salt. However, generating a unique salt for each user is even better because then it would take more information than just the password to crack it (e.g. username, date registered, or some other info).

Body:
Basically, what I'm asking is if salting a password by appending a hashed version of it to the end of it is just as secure as salting with a different string. So:

Is this:

$pass = "pass";
$salt = sha1(md5($pass));
$pass = md5($pass.$salt);

As secure as this?

$pass = "pass";
$salt = "4D9ds*^dkrUI45^#dkd*3fD8&!dlvd*";
$pass = md5($pass.$salt);


问:
Change the color of the button by using html color codes
I want to change the color of the button when it is pressed in windows form app and I want to use the color codes. Is there a way to make button color #C0C0C0 ??

答:
You can use rgb equivalent.Color spaces of #c0c0c0 RGB =   192 192 192

```<code>     button1.ForeColor= Color.FromArgb(192, 192, 192);
</code>```

Body:
You can use rgb equivalent.Color spaces of #c0c0c0 RGB =   192 192 192

     button1.ForeColor= Color.FromArgb(192, 192, 192);


答:
array_filter will work perfectly if you're only working with arrays containing strings. Be careful otherwise as array_filter will also remove 0, '', and false.

See this answer: Remove empty array elements

Title: How to remove 'null' values in laravel controller while retrieving data from database

Body:
The results in $data variable. I want to remove null values at output.

The following code:

    $data = json_decode(json_encode($data),true);

I am copying $data to $data1 later to merge the two variables using below code:

$data1 = $data;
$unique= array_merge($data1,$data);
$final =array_values(array_map("unserialize",array_unique(array_map("serialize", $unique))));


问:
How to consolidate results from multiple invocations of a stored procedure?
I have a stored procedure that is supposed to work as follows:

```<code>DECLARE @TagNames AS TABLE
(
    tag NVARCHAR(50) NOT NULL
)

-- Get list of tags
INSERT INTO @TagNames
SELECT tag
FROM tagTable
WHERE tag LIKE @tagPattern

-- Create unified result set, combining results from stored proc for each tag
SELECT n.tag, r.time, r.value FROM @TagNames AS n
CROSS APPLY
    dbo.GetResultsForTag(n.tag) AS r -- Not valid
</code>```

However, I can't use CROSS APPLY because dbo.GetResultsForTag() is a stored procedure.

The implementation of dbo.GetResultsForTag() relies on calling EXEC on dynamic SQL passed to a linked server, so I believe it can't be converted into a table-valued function. Dynamic SQL isn't permitted in table-valued functions.

The linked server communicates via an OLE-DB provider, but it's not an SQL Server instance. It's an OSISoft PI process historian database. Normally it's quite easy to query for multiple tags of data in a single query, but in this case I'm doing some calculations which require me to supply a filter expression which specifies a single tag name. So each tag needs a separate query to the data source.

As far as I know, stored procedures can't be used as the right-hand side of a JOIN?

What other options are open to me for consolidating these results together? Just a cursor?

Edit: I've figured out how to fix the underlying obstacles which were forcing me to use dynamic SQL and a stored procedure. Now I can use regular SQL, which allows me to use a Table Valued Function instead of a stored proc, which allows me to use JOIN and CROSS APPLY instead of ugly cursor hacks.

答:
Rewrite your stored proc as a Table Valued Function??

Alternatively, re-write it to take off the filter, dump it to a table (maybe a temp table), then join to that.

Body:
I have a stored procedure that is supposed to work as follows:

DECLARE @TagNames AS TABLE
(
    tag NVARCHAR(50) NOT NULL
)

-- Get list of tags
INSERT INTO @TagNames
SELECT tag
FROM tagTable
WHERE tag LIKE @tagPattern

-- Create unified result set, combining results from stored proc for each tag
SELECT n.tag, r.time, r.value FROM @TagNames AS n
CROSS APPLY
    dbo.GetResultsForTag(n.tag) AS r -- Not valid

However, I can't use CROSS APPLY because dbo.GetResultsForTag() is a stored procedure.

The implementation of dbo.GetResultsForTag() relies on calling EXEC on dynamic SQL passed to a linked server, so I believe it can't be converted into a table-valued function. Dynamic SQL isn't permitted in table-valued functions.

The linked server communicates via an OLE-DB provider, but it's not an SQL Server instance. It's an OSISoft PI process historian database. Normally it's quite easy to query for multiple tags of data in a single query, but in this case I'm doing some calculations which require me to supply a filter expression which specifies a single tag name. So each tag needs a separate query to the data source.

As far as I know, stored procedures can't be used as the right-hand side of a JOIN?

What other options are open to me for consolidating these results together? Just a cursor?

Edit: I've figured out how to fix the underlying obstacles which were forcing me to use dynamic SQL and a stored procedure. Now I can use regular SQL, which allows me to use a Table Valued Function instead of a stored proc, which allows me to use JOIN and CROSS APPLY instead of ugly cursor hacks.


答:
If you're trying to write output in a single file, this is a bash one-liner that would work:</p>

```<code>IFS=' ' read -r -a array <<< $(cat results|tr -s ' ' |tr -d '\n'); while test "${#array[@]}" -ge "1"; do for i in {1..15}; do echo -n ${array[0]}; array=("${array[@]:1}"); done; echo; done > results_formatted
</code>```

Title: Sort block of numbers into columns

Body:
i have a file with alot of data written out of a simulation:

  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.00000000E+00  0.00000000E+00  0.00000000E+00  0.00000000E+00
  0.93071889E-02
  0.14952319E-13  0.55746201E-11  0.89816722E-11  0.46833532E-11  0.14964636E-13
 -0.92995325E-47  0.79969902E-46  0.00000000E+00 -0.21442451-105 -0.86924526E-93
  0.00000000E+00 -0.85777333E-93  0.48179949-102  0.00000000E+00
  0.18614378E-01
  0.12050471E-12  0.44928328E-10  0.72404536E-10  0.37744496E-10  0.12066634E-12
  0.25848493E-36 -0.13804858E-35  0.56376226E-83  0.20648121E-74 -0.89608567E-66
 -0.20861629E-76 -0.87854256E-66 -0.23574755E-73 -0.73275846E-82

Desired Output is: Each Block of Data written in its own column and the column starts with the "header" of each block, which is the first number. For example the last block should look like this:

0.18614378E-01 0.12050471E-12  0.44928328E-10  0.72404536E-10 0.37744496E-10  0.12066634E-12 0.25848493E-36 -0.13804858E-35  0.56376226E-83 0.20648121E-74 -0.89608567E-66 -0.20861629E-76 -0.87854256E-66 -0.23574755E-73 -0.73275846E-82

I thought about using AWK with FS=' ', but i don’t know how to tell my bash script to stop after reading 15 numbers and how to save those 15 numbers and output them into a separate file (using printf maybe?)

Thanks!

Body:
If you're trying to write output in a single file, this is a bash one-liner that would work:

IFS=' ' read -r -a array <<< $(cat results|tr -s ' ' |tr -d '\n'); while test "${#array[@]}" -ge "1"; do for i in {1..15}; do echo -n ${array[0]}; array=("${array[@]:1}"); done; echo; done > results_formatted


答:
I'm not sure if you're asking this but try something like this,</p>

```<code>var totCost = document.getElementById("totcost").value;
$("#yourDivID").html(totCost);
</code>```

Title: My JQuery post data to 'textbox' how to post it to 'div'?

Body:
I'm very new to JQuery.
I already can, get the data from textbox and do some calculation and show it to other 'textbox' though I want to post it to 'div' or 'p' whatever it is as long as not textbox.

here's my code

Participant fee (IDR):

Populi fee (IDR):

<input type="text" id="popcost">

Total Estimated Cost (IDR):

<input type="text" id="totcost">

$(document).ready(function(){
$('#calc').click(function(){
        var num_participant = parseInt($("num_participant").val());
        var reward = parseInt($("reward").val());
        var esttime = parseInt($("esttime").val());
        var parcost = num_participant*reward;
        var popcost = (parcost*0.1)+(num_participant*150);
        var totcost = parcost+popcost;
        /*
        document.getElementById("result").style.display = "block";
        document.getElementById("parcost").value = parcost;
        document.getElementById("popcost").value = popcost;
        document.getElementById("totcost").value = totcost;*/

        document.getElementById("result").style.display = "block";
        $("#parcost").html(parcost);
        $("#popcost").html(popcost);
        $("#totcost").html(totcost);

        return false;
});

});

Still wont work, if I change it from "document.getelementById" to "$".
and even using "document.getelementById" it won't showed on the "div".

any ideas?

Body:
I'm not sure if you're asking this but try something like this,

var totCost = document.getElementById("totcost").value;
$("#yourDivID").html(totCost);


问:
jquery waiting for .ajax() to complete within .each() iteration
Ive a jquery function that obtains text from all nodes of a particular class using the jquery .each() selector:

```<code>function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                console.log(node_text);
              })
            }
</code>```

That works as expected. Next, I want to send the text to a php script using .ajax() :

```<code>function get_php_text(node_text)
            {
               let url = `myphp.php?string_text=${node_text}`;
                 $.ajax(
                      {
                        url: url,
                        success: function(result)
                          {
                            console.log(result);
                          }
                      });
            }
</code>```

That function also works as expected.

When I run the following:

```<code>function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                get_php_text(node_text);
              })
            }
</code>```

I run into a problem as get_php_text() is not waiting for each .each() iteration to complete.

How can I rewrite the get_text() function so that it waits for the get_php_text() to return before going to the next iteration?

答:
You can make it so that the iterating is done inside the success handler of your ajax call, by making get_php_text() recursive. This way the next iteration will only occur after the previous one has finished its ajax request.

```<code>function get_text() {
  let node_text_array = [];
  $(".my_class").each(function() {
    node_text_array.push($(this).text());
  });
  get_php_text(node_text_array);
}

function get_php_text(node_text_array) {
  if (node_text_array.length>0) {
    let node_text = node_text_array.splice(0,1);
    let url = 'myphp.php?string_text=${node_text}';
    $.ajax({
      url: url,
      success: function(result) {
        console.log(result);
        get_php_text(node_text_array);
      }
    });
  }
}
</code>```

Body:
Ive a jquery function that obtains text from all nodes of a particular class using the jquery .each() selector:

function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                console.log(node_text);
              })
            }

That works as expected. Next, I want to send the text to a php script using .ajax() :

function get_php_text(node_text)
            {
               let url = `myphp.php?string_text=${node_text}`;
                 $.ajax(
                      {
                        url: url,
                        success: function(result)
                          {
                            console.log(result);
                          }
                      });
            }

That function also works as expected.

When I run the following:

function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                get_php_text(node_text);
              })
            }

I run into a problem as get_php_text() is not waiting for each .each() iteration to complete.

How can I rewrite the get_text() function so that it waits for the get_php_text() to return before going to the next iteration?

Body:
You can make it so that the iterating is done inside the success handler of your ajax call, by making get_php_text() recursive. This way the next iteration will only occur after the previous one has finished its ajax request.

function get_text() {
  let node_text_array = [];
  $(".my_class").each(function() {
    node_text_array.push($(this).text());
  });
  get_php_text(node_text_array);
}

function get_php_text(node_text_array) {
  if (node_text_array.length>0) {
    let node_text = node_text_array.splice(0,1);
    let url = 'myphp.php?string_text=${node_text}';
    $.ajax({
      url: url,
      success: function(result) {
        console.log(result);
        get_php_text(node_text_array);
      }
    });
  }
}


问:
How to erase image specific areas by dragging the mouse in python GUI?
I want to use some python libraries to create a GUI app with which I can smear some area by dragging the mouse?
I am truly faithfully to thank anyone who can give me a hand. Thank you.</p>

答: Most graphic libraries should capture the mouse pointer. Specifically I recommend PyQt, which is very powerful, and you can access many things at the level of widgets. All the documentation can be found here</p>


答:
Programmatically

[YourSuperview setClipsToBounds:YES]

Title: Subview displaying outside the bounds of the parent UIView

Body:
I have a UIView that contain another subview. The subview's frame is outside of the bounds of the super view. But the entire subview is visible in when I run the application.
Example:

++++++++++++++++++++++++++++
+                          +
+       Super view         +
+                          +
+                          +
+     --------------------------
+     -  Subview           +   -
+     -                    +   -
+     --------------------------
+                          +
+                          +
++++++++++++++++++++++++++++

Should be:

++++++++++++++++++++++++++++
+                          +
+       Super view         +
+                          +
+                          +
+     ---------------------+
+     -  Subview           +
+     -                    +
+     ---------------------+
+                          +
+                          +
++++++++++++++++++++++++++++

Any idea?