text:
Q: Reducing Equation Loop I'm trying to create a loop where if the value of "X" is a whole number it divides it by 2 and that's the new value. Then if the new value is a whole number it divides by 2 or if it has a decimal it subtracts it by 0.5 and that becomes the new value. I want it to loop from "X" to >= 1.5
I've tried a while/if/elif and I get close but when I change my "X" value from 217 to 218 the output isn't right.
def func():
    val = 217
    while val >= 1.5:
        val = val/2
        print(val)
        if val is float:
            val = val-.5
            print(val)
        elif val is int:
            val = val/2
            print(val)
        else:
            val = val//2
            print(val)
func()

When val = 217 this renders perfectly with the exception of it going to 0.0 instead of 1.5
Also the else: val = val//2 seems off to me but this is the closest I've gotten to rending this code the way I want it to.
Output:
108.5
54.0
27.0
13.0
6.5
3.0
1.5
0.0  <--- don't get why this is here when the while loop states >= 1.5
Now if you change the val to 218
def func():
    val = 218
    while val >= 1.5:
        val = val/2
        print(val)
        if val is float:
            val = val-.5
            print(val)
        elif val is int:
            val = val/2
            print(val)
        else:
            val = val//2
            print(val)
func()

Output:
109.0
54.0
27.0
13.0
6.5
3.0
1.5
0.0
Kind of bugs out because 218/2 = 109 then 109/2 = 54.5
Since I want the code to print out each new value I would want it to show each value as if you're typing each equation then hitting the equals sign. I want the output to look like this:
Output:
109.0 (/2)
54.5 (-0.5)
54.0 (/2)
27.0 (/2)
13.5 (-0.5)
13.0 (/2)
6.5 (-0.5)
6.0 (/2)
3.0 (-1.5)
1.5 (>= 1.5)
Output is coming out close to what I want but not exactly.

A: The main problem is that the conditions 'val is float' and 'val is int' are always false, you need another way to check whether the decimal part of val is 0 or not.
A rough way to do it (but there is better with no doubt) is :
if (val * 10) % 10 == 0:  # If the decimal part is 0

Moreover, according to the algorithm you describe at the beginning, the final else shouldn't exist.
Besides, at the beginning of the loop, you forgot to divide the value by 2 only if it is round.
You make two different operations in each loop, that's why the final result may be one step ahead of what you expect, you may want to change the loop to make one operation at each iteration or add a condition on the second operation.

A: The simplest test for whether the result of dividing value x by 2 is an integer is:
int(x / 2) == x / 2

or, in general:
int(expression) == expression # to test any expression for an integer value
# but typically the expression is just a variable to avoid redundant calculations

Try this:
def func():
    val = 218
    print(val, end='')
    while val >= 1.5:
        val /= 2
        print(' (/2)', val, end='')
        if int(val) != val:
            val -= .5
            if val >= 1.5:
                print(' (-0.5)', val, end='')
    print(' (>= 1.5)')

func()

See demo at http://ideone.com/wCOxta
Prints:
218 (/2) 109.0 (/2) 54.5 (-0.5) 54.0 (/2) 27.0 (/2) 13.5 (-0.5) 13.0 (/2) 6.5 (-0.5) 6.0 (/2) 3.0 (/2) 1.5 (>= 1.5)

A: Something smooth:
x = 1.0

if type(x) is float:
    print("float")
elif type(x) is int:
    print("int")

>>> float


text:
Q: How to set date to sencha touch's date picker I am trying to set the date to date picker but not able to set the date.
bellow is my chunk of sencha touch code.
this.scheduledDatePicker = Ext.create('Ext.field.DatePicker', {
            //label: 'To',
            //labelAlign: 'right',
            //cls: 'form-block',
            value: new Date(),
            flex: 2.6,

        });

and I am setting value after page load or get values from the database as using below code. I tried this many was as you can see commented code. but cant able to set this value.
var date= Ext.Date.format(Ext.Date.parse(this.rec.get('bookingDateTime'), "Y-m-d H:i:s"), "d/m/Y");
//var date= Ext.Date.parse(this.rec.get('bookingDateTime'));
//var date= this.rec.get('bookingDateTime');

this.scheduledDatePicker.setValue(date);

can anyone tell me why my code is not working or any solution for this issue?

A: A datefield accepts a javascript date, however it seems you don't provide one.
You should check what this.rec.get('bookingDateTime') returns, and how to modify that field in such a way that you get a javascript date.
I expect that you already have a model, where you could specify that field to be of type date with a certain date format:
Ext.define('MyModel', {
    fields: [{
        name: 'bookingDateTime',
        type: 'date',
        dateFormat: 'Y-m-d H:i:s' // specify format that is received from the server
    }]
});

Then ExtJS will do the conversion for you and you could just use setValue without any parsing:
this.scheduledDatePicker.setValue(this.rec.get('bookingDateTime'));

If you don't have a model already, you can still read the string from bookingDateTime and parse it now and then and put it into the picker:
var date= Ext.Date.parse(this.rec.get('bookingDateTime'), "Y-m-d H:i:s");
console.log(date); // <- if date is null, format is not specified correctly.
this.scheduledDatePicker.setValue(date);

In both cases, console logging the interim result can help pinpoint down the issue: most of the time, the "parsed date" is null, because the format string does not match the date format received from the server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL SELECT INSERTed data from Table its in ASP Classic. MS-Access DB.
i do: INSERT INTO Orders (userId) VALUES (123)"
what i want to retrieve is orderNumber from that row. its an auto-increment number.
so i did: SELECT orderNumber FROM Orders WHERE userId=123
but since it is on the same page, the SELECT returns: Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.
i've seen somewhere RETURNING orderNumber as variable but it was for oracle and i dont know how to implement it into my asp :(
set addOrder = Server.CreateObject("ADODB.Command")
        addOrder.ActiveConnection = MM_KerenDB_STRING
        addOrder.CommandText = "INSERT INTO Orders (userId) VALUES ("&userId&")"
        addOrder.CommandType = 1
        addOrder.CommandTimeout = 0
        addOrder.Prepared = true
        addOrder.Execute()

Dim getOrderNumber
Set getOrderNumber = Server.CreateObject("ADODB.Recordset")
        getOrderNumber.ActiveConnection = MM_KerenDB_STRING
        getOrderNumber.Source = "SELECT orderNumber FROM Orders WHERE userId=" & userId
        getOrderNumber.CursorType = 0
        getOrderNumber.CursorLocation = 2
        getOrderNumber.LockType = 1
        getOrderNumber.Open()

                    session("orderNumber") = getOrderNumber.Fields.Item("orderNumber").value

A: The following might be of help if you are using their method of adding records using ADO objects.
http://support.microsoft.com/kb/221931
But without actually seeing you Classic ASP code, it is hard to give you a proper answer.


text:
Q: what is meant by "appetite of fifteen" in Sense and Sensibility? This is from the part of Sense and Sensibility where the Dashwood daughters moved to Barton Park.

He [Mr.Middleton] was a blessing to all the juvenile part of the neighborhood, for in summer he was for ever forming parties to eat cold ham and chicken out of doors, and in winter his private balls were numerous enough for any young lady who was not suffering under the insatiable appetite of fifteen.

A: Jane Austen had a quick wit and much of her writing pokes fun at various groups of people.  In this case she implies that fifteen-year old ladies have an insatiable need for continual entertainment that no number of parties could satisfy.  I would assume Austen also means that young ladies grow out of this need as they grow up.
At that time perhaps fifteen was considered much more "adult" than it is today, considering that they were already courting and being courted, but otherwise I don't know that fifteen-year-olds have changed that much in their need for activity and stimulation.

A: Read it as if "the insatiable appetite of (a person of) fifteen (years old)"


text:
Q: How to set docker's NO_PROXY with wildcard As mentioned in the official docker docs here, proxy setting for docker can be assigned here /etc/systemd/system/docker.service.d/https-proxy.conf, like:
[Service]
Environment="HTTPS_PROXY=https://proxy.example.com:443/" "NO_PROXY=localhost,127.0.0.1,docker-registry.somecorporation.com"

But, the docker's downloading relates a lot of url redirecting. So I hardly name them one by one in the setting here.
So my question is that is there any methods to achieve wildcard, such as *.docker.io.
Thanks,
Cross

A: In NO_PROXY, you can use wildcard to match multiple host with same domain. For *.docker.io, you can use .docker.io

A: I understand that this is a question from some years ago, but I guess this is still a common question for developers and I don't feel it's properly answered.
Regarding the approved answer from @Kaneg, effectively a leading . will do the trick in the majority of the cases... But not always.
Due to that, I'm writing this answer in case more people ends up in this question in a future.

First of all, we have to keep in mind that the famous NO_PROXY is an environment variable that the majority of Web Clients accept at the time of using a Web proxy server, but there is no standard about how it has to be defined or how each client should handle these.
When we set up those in Docker as environment variables, we're just forcing all the containers that will be created in the future to use those environment variables and they will be used for Docker as well (for example to download images from the official registry). Anyway, the real deal depends on what do we have inside of those containers, since that's where the requirements will get strict.
In order to simplify this to the maximum, I've taken this table from the GitLab blog (thank you, Stan Hu):

curl
wget
Ruby
Python
Go

no_proxy
Yes
Yes
Yes
Yes
Yes

NO_PROXY
Yes
No
Yes
Yes
Yes

Case precedence
lowercase
lowercase only
lowercase
lowercase
lowercase

Matches suffixes?
Yes
Yes
Yes
Yes
Yes

Strips leading .?
Yes
No
Yes
Yes
No

* maches all hosts?
Yes
No
No
Yes
Yes

Supports regexes?
No
No
No
No
No

Supports CIDR blocks?
No
No
Yes
No
Yes

Detects loopbacks IPs?
No
No
No
No
Yes

Reference
link
link
link
link
link

What does this mean?
That if we just follow the logic of setting a leading . in the NO_PROXY, first of all this one won't be understood by tools like wget, so they will pass through the Proxy anyway; and in the case that we would set the leading . as no_proxy still curl will always strip the leading . meanwhile wget won't strip it and will perform an exact string match against the hostname.
Solution
Suffixes are ALWAYS matched, so the best solution is to set docker.io as it will include whatever.docker.io. Try to avoid using a leading dot (.) if top-level domains need to be matched in every case.


text:
Q: Python Error:"TypeError: string indices must be integers" I'm here trying to parse JSON string that comes from a sql table, but while parsing it is giving the error TypeError: string indices must be integers at line result = json_normalize(json_st,'results')
here is the code snippet
from pandas.io.json import json_normalize
import pyodbc
cnxn = pyodbc.connect('connection string')
cursor = cnxn.cursor()

cursor.execute("select TOP 1 GEOCODE_ID, JSON from GEOCODE_TBL where GEOCODE_ID = 20")
ID=[]
JSON=[]

for row in cursor.fetchall():
      ID.append(row[0])
      JSON.append(row[1])

json_st1 = json.dumps(JSON)
json_st=json.loads(json_st1)

result = json_normalize(json_st,'results')

Any suggestion on this will be helpful.
Thanks
Domnick.

A: Looking at the function signature, it takes one data variable and some optional params.
pandas.io.json.json_normalize(data, record_path=None, meta=None,
meta_prefix=None, record_prefix=None, errors='raise', sep='.')

Where data : dict or list of dicts. So you can't pass it as a string. Also, why are you passing the string 'results' too?
Your data variable needs to be a dict, or list of dicts (which is, json in python)


text:
Q: what does *(iterator) and *(++iterator) means in below c++ code? Why *(it) in set upperbound returns index , while *(++it) in set upperbound returns value for the value greater than any value present in the set?
#include<bits/stdc++.h>
using namespace std;
int main() {
 set<int> s;
 s.insert(30);
 s.insert(25);
 int x=35;
 auto it = s.upper_bound(x);
 cout << *(it) << endl; //output: 2
 cout << *(++it) << endl;// output: 25
}

A: *(it) does not return an index.  If it is an iterator that references a member of the set, then *(it) is equivalent to *it  (the () are not required).  It therefore accesses the corresponding member of the set.   If it is a past-the-end iterator, the behaviour is undefined.
*(++it)  first increments it, and then accesses the corresponding set element.  So

cout << *(++it) << endl;

gives the same output as
++it;
cout << *it << endl;

which gives undefined behaviour if it was already a past-the-end iterator OR if incrementing it gives a past-the-end iterator.
In your example, the s.upper_bound(x) returns a past-the-end iterator, since x is greater than any member of the set.    Both output statements in your code therefore give undefined behaviour.


text:
Q: How to run pre-push git hook only when files in a subfolder have changed since the last push? I have a monorepo that has a C# backend with a react frontend. The frontend is in a subfolder and I'm trying to setup a git hook specifically for the react client. I've installed husky, which handles the git hooks, and I've created a pre-push hook which runs every time I try to push my latest commits.
However, I only want that pre-push hook to run if there are commits that contains changes from the frontend. The initial way I've attempted doing this is having the script run a git show command to output some filenames, and if matched to the file path of our react client, to run the command I want ran pre-push:
if git show --name-only -r --stat --oneline HEAD^^..HEAD | grep -q 'ReactClient/'; then
  npm run verify
fi

The problem is that this only checks the last 2 commits, I believe. I need to check the files changed in ALL commits for the current branch that have changed since the last time I pushed to the remote repo. How can I do this?

A: I solved this by changing the git command slightly:
currentBranch=$(git rev-parse --abbrev-ref HEAD)

if git diff-tree --no-commit-id --name-only -r HEAD..origin/$currentBranch | grep -q 'client/'; then
  cd client
  npm run verify
fi


text:
Q: FreeRADIUS with LDAP vs Kerberos The following site discusses how to setup FreeRADIUS to authenticate against an LDAP backend (it goes through a tutorial showing how to expose NT hashed passwords in FreeIPA so that FreeRADIUS can read them).
https://firstyear.id.au/blog/html/2016/01/13/FreeRADIUS:_Using_mschapv2_with_freeipa.html
It also discourages the use of Kerberos key tabs to connect FreeRADIUS to IPA because when using e.g., PAP authentication,
"FreeRADIUS can either read the NTHash and do a comparison (as above),
or it can directly bind to the LDAP server. This means in the direct
bind case, that the transport may not be encrypted due to the keytab."

On the flip side, various FreeRADIUS guides discourage the use of LDAP (e.g., see comments for the default inner-tunnel site, which states:
    #  We do NOT recommend using this.  LDAP servers are databases.
    #  They are NOT authentication servers.  FreeRADIUS is an
    #  authentication server, and knows what to do with authentication.
    #  LDAP servers do not.

What is the rationale behind the above statement, other than a generic disclaimer?
Can someone please explain, from a security standpoint, the pro's and con's of one approach vs. the other?
I've successfully setup using an LDAP backend (no KRB) and I'm using PEAP for WiFi authentication. I'd like to better understand the security tradeoffs for this scenario.

A: For FreeRADIUS
The comment is there as a generic disclaimer and to address a deficiency in FreeRADIUS.
In the majority of cases you don't know what the user's DN is to perform the bind. So first, you need to bind as an anonymous user, or with a set of privileged credentials to perform that search and find the DN.
FreeRADIUS doesn't maintain separate connection pools for different purposes, so the connection must be rebound as the authenticating user.
This means in order to authenticate a user in LDAP you end up performing three operations:

*

*Bind as a privileged/anonymous user.

*Search for the User's DN.

*Bind as the user.

If the latency is high between the LDAP server and the RADIUS server this can severely limit throughput (in terms of auth/s) as FreeRADIUS in versions <= v3.0.x implements synchronous I/O.
There's absolutely no good reason not to use bind operations to authenticate users, especially where the LDAP server is using a specialised backend authentication plugin to perform the authentication. It doesn't matter what LDAP was designed for.  The RADIUS protocol certainly wasn't designed for international roaming confederations and tunnelling TLS in multi-layered authentication schemes, yet it fills those roles reasonably well.
For IPA
The document you linked is confusing. It seems to be talking about using a service account to bind via Kerberos (GSSAPI) to the LDAP server, and because of deficiencies in 389DS, GSSAPI can't be combined with StartTLS or LDAPS, which means when the user's credentials would be submitted in the clear during that second bind operation.
Or it could be saying that because you can't use GSSAPI with StartTLS or LDAPS with 389DS, then the credentials would be submitted in the clear if you used Kerberos to perform the user binding operation.
In either case, I'm fairly sure this is a limitation in 389DS only, and that the majority of other LDAP servers would support GSSAPI over TLS encrypted LDAP connections.
Whatever the case, you should NEVER submit or retrieve credentials to an LDAP directory without using StartTLS or LDAPS as the article says:

Today the only secure, guaranteed way to protect your accounts is TLS. You should use LDAPS, and this guarantees all communication will be secure. It's simpler, faster, and better.

If communication with the directory server is in the clear, then an attacker could easily snoop on either the plaintext password being submitted to the directory server, or the NTPassword coming back.  The NTPassword is just the 16bit little endian encoding of the password, hashed with MD4, it's pretty much as good as plaintext.

A: The comment:
#  We do NOT recommend using this.  LDAP servers are databases.
#  They are NOT authentication servers.  FreeRADIUS is an
#  authentication server, and knows what to do with authentication.
#  LDAP servers do not.

is in the context where LDAP server would be used for authentication and not as a database. This basically means radius server would try to authenticate to LDAP server using supplied credentials. And they rightfully warn you this is not the purpose LDAP was designed for.
Now, if you use LDAP as a database, which IS the case is other places, there is no problem with that.


text:
Q: Split a string into 2 different substrings vb.net I'm trying to split a string into 2 subs. The first contains the first 236 (0 to 235) chars and the second one from 237 to the end of the string.
firststr = str.Substring(0, 235)
secondstr = str.Substring(235, strLength)  'strLength is the total length of the string

strLength is generating error : Index and length must refer to a location within the string.
Parameter name: length
Any help?

A: You need something like this:
secondstr = str.Substring(235, strLength - 235)

Because strLength is the length of the entire string, and you're starting at position 235, you're going past the end of the string.

A: The 2nd argument is how many charaters you need and not what the end position is. Try something like:
secondstr = str.Substring(235, strLength-235)   (perhaps you also need -1)

A: Normally data the second argument would be the length of the substring you want, in this case strLength-236. I don't know vb.net but in C# you do not need to specify the second variable strLength for secondstr when using substring because the default goes to the end of the string.
[edit] - fixed

A: If you just want to go to the end of a string then you can leave off the length parameter when using the Substring method. The default is to go to the end of the string.
secondstr = str.Substring(236)

will get the job done for you.

A: From what I see, your variable strLength has a value that's outside the boundaries of the string str.

A: I note noone picked up the other error in your code as described.
The second argument to Substring is the length returned, so firstStr contains the same as Left(str, 235), i.e. it contains 235 characters as you've written it, not 236.
For completeness, here's a VB solution to your query:
firststr = Left(str, 236)
secondstr = Mid(str, 237)


text:
Q: How mechanical HDD's determine which files to overwrite when copying data Hard drive size: 100GB and it did contain a bunch of files of varying megabytes file sizes which all got added at different times and accumilated over time... they all got deleted...
I then copied 25GB of data (small files mbs in size) onto the empty drive...
Which deleted files get overwritten first? the ones added last or the ones added first?  Or does the drive spread all the files in a scattering motion all over random places within the 100GB space.
So, is it random deleted files that get overwritten regardless of date added, or do the earliest added deleted files get overwritten first?

A: Hard disks, either HDDs or SSDs, don't understand the concept of files at all. They only store a sequence of bytes and that's all they care about. [1]
Hard disks are usually partitioned and partitions are formatted with a file system of choice (FS). [2] The file system that decides how and where files are stored.
The answer to your question is: it depends.
File system doesn't really care when a file was created or deleted. Once it's deleted, it doesn't exist anymore, file system will treat it just as garbage bytes, not as a file.
What's more, files aren't stored continuously: a single file may get split into multiple chunks and scattered all over the partition. It's file system's job to reassemble it on the fly so that OS doesn't realize it was sliced in the first place. Counter-intuitively, it may actually improve performance: controlled fragmentation can be used to facilitate the fact that outer parts of HDD platters offer better read/write speeds and to avoid situations where FS is forced to fragment a file in a sub-optimal way because it can't fit it in any desirable part of disk.
Writing patterns for specific file systems may be predictable for specific cases, but not in general. Sizes of specific files and the order in which you store them will affect it. When storing a new file, file system won't consider whether the space it's going to use was used or not; it won't prefer previously-used addresses over "clean" ones or the other way around. Once a file is deleted, FS treats the space it occupied identically as space that was never used.

[1] Modern drives have additional layer of abstraction, so the regions actually used for storage of these bytes may not be sequential or contiguous (for example because of bad block remapping in HDDs and wear leveling in SSDs). That doesn't matter for the scope of the question though, let's just say that all hard disks expose themselves to other hardware and OS as a device that can store a number of reliably addressed sequential bytes.
[2] Modern Windows versions use NTFS on OS partitions and NTFS or FAT32 on additional ones. Flash disks typically use FAT32 or sometimes exFAT. Linux usually lives in ext4 file system. Apple was using HFS+ and is now migrating to APFS. There are also some file systems for special use cases, for example scalability-oriented Btrfs and ZFS which was designed as an all-in-one fail-safe data storage solution.

A: While it is not truly random in a situation like this it is for all practical purposes random.  Note, however, that even if the directories have been overwritten sometimes the files can be found by programs that search the whole disk.  While I have done such things by eyeball in the era of floppy disks these days it is only feasible if the file has some sort of signature.


text:
Q: Solr DataImportHandler not found I am using  Solr 3.3.0 with Tomcat 6.0.26. I was able to successfully install Solr and i was even able to access its web interface using http:/localhost:8084/solr/admin.
Now i want to use its dataimporthandler to index data from my database.I have added following to my solrconfig:
<requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImport
 Handler">
<lst name="defaults">
<str name="config">data-config.xml</str>
</lst>
</requestHandler>

I have also created a data-config.xml in same directory.
My solrconfig file has following location for dataimport
  <lib dir="../../dist/" regex="apache-solr-dataimporthandler-\d.*\.jar" />

And i have checked that dataimporthandler.jar file exist in the dist folder at following path C:\web\solr\example\lib\apache-solr-3.3.0\dist
But whenever I type http:/localhost:8084/solr/dataimport or http:/localhost:8084/solr/admin/dataimport it says resource unavailable. I thought it was dur to some problem with Tomcat setting so i stopped tomcat and tried to start Solr from cmd using java -jar start.jar. And i get the following error
HTTP ERROR 500
Problem accessing /solr/. Reason:
Severe errors in solr configuration.
Check your log files for more detailed information on what may be wrong.
If you want solr to continue after configuration errors, change:

<abortOnConfigurationError>false</abortOnConfigurationError>

in solr.xml

-------------------------------------------------------------
org.apache.solr.common.SolrException: Error loading class
    'org.apache.solr.handler.dataimport.DataImportHandler'
at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:389)
at org.apache.solr.core.SolrCore.createInstance(SolrCore.java:423)
at org.apache.solr.core.SolrCore.createRequestHandler(SolrCore.java:459)
at
  org.apache.solr.core.RequestHandlers.initHandlersFromConfig(RequestHandlers.java:157)
at org.apache.solr.core.SolrCore.<init>(SolrCore.java:563)
at org.apache.solr.core.CoreContainer.create(CoreContainer.java:463)
at org.apache.solr.core.CoreContainer.load(CoreContainer.java:316)
at org.apache.solr.core.CoreContainer.load(CoreContainer.java:207)
at
   org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:130)
at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:94)
at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:713)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)
at
 org.mortbay.jetty.handler.ContextHandlerCollection.doStart
 (ContextHandlerCollection.java:156)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.xml.XmlConfiguration.main(XmlConfiguration.java:985)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.mortbay.start.Main.invokeMain(Main.java:194)
at org.mortbay.start.Main.start(Main.java:534)
at org.mortbay.start.Main.start(Main.java:441)
at org.mortbay.start.Main.main(Main.java:119)
  Caused by: java.lang.ClassNotFoundException:
  org.apache.solr.handler.dataimport.DataImportHandler
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.net.FactoryURLClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:373)
... 34 more

A: It seems that for several versions of Solr including 4.3, the dataimport handler jar is not included in the final war file when you build from source.
There is a very simple fix to this by modifying the file /solr/webapp/build.xml.

*

*Open that file and find the "dist" target.

*Find this section of the "dist" target:
<lib dir="${dist}" excludes="${exclude.from.war},${common.classpath.excludes}">

*Add this item to the list of includes in that section:
<include name="apache-solr-dataimporthandler-${version}.jar" />
Save and exit.
Now, when you build, do the following:

*

*ant dist-contrib

*ant dist

To verify that the dataimporthandler jars are in your WAR file, unpack it, and look for it among the jars in the WEB-INF/lib directory.
Some variation of this will probably work for earlier versions too.

A: The jar you are looking for (at least in 3.5) is under the ./dists folder

A: As far as you are telling us, your jar file name does not match the supplied regexp:
With the given configuration:
<lib dir="../../dist/" regex="apache-solr-dataimporthandler-\d.*\.jar" />

The file:
dataimporthandler.jar

Does not match the regexp, while it has to, as shown in the sample configuration file for Solr
Probably start by just specifying:
<lib dir="../../dist/"/>

A: i put solr jars under WEB-INF/lib

A: Make sure you have following three required fields correct.
1)  A entry for dataimport handler in solr-conf.xml
</requestHandler>
<requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
<lst name="defaults">
<str name="config">data-config.xml</str>
</lst>
</requestHandler>

2) Your Solr war file is aware of solr-home folder , and hence the libraries included in solr-home. If solr-home is added explicitly.
To make your solr.war aware of solr-home folder deploy the solr.war at server.
Go to apache-tomcat-6.0.36/webapps/solr/WEB-INF and open web.xml in any text editor.
Now search for the entry showing below
<!-- <env-entry>
<env-entry-name>solr/home</env-entry-name>
<env-entry-value> /Path/To/My/solr/Home/solr/</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry> -->

replace  value to the solr-home folder in your case. This will make solr, point solr-home folder hence lib folder inside it.
3) Add your new libraries location to /home/javaguys/solr-home/collection1/conf/solr-config.xml.  just under   tag like .
This will solve your problem i hope, for more information please check out this solution here.

A: I've been looking at this problem for a bit on my own, using solr 4.1 and tomcat.  I wasn't able to include the library I needed with <lib dir="../../dist/" regex="solr-dataimporthandler-.*\.jar" /> -->, which I figured had to be correct because from the directory that I had the solrconfig.xml in, it was two directories up and one down to dist.  It wasn't until I temporarily subbed in the direct path (for me, /opt/solr/dist) that I realized that the problem was that I was starting from the wrong directory.  It turns out that what I needed was:
<lib dir="../dist/" regex="solr-dataimporthandler-.*\.jar" /> -->

So, if you're having trouble with including this, check that you're starting from the directory that contains your conf directory, and not the conf directory itself.

A: I solved this problem by building dataimporthandler jar from the solr source. For 3.1, dataimporthandler is not included in apache-solr-core-3.1.0.jar . I couldn't find the jar file for dataimporthandler, so I built it from the source and put it in my solr lib directory

A: I am using Solr 4.0 with a Glassfish 3.1.2 container and I solved the problem by opening the solr war itself, manually just adding the jar files inside, and redeploying glassfish.

A: Had this problem twice, on Windows Tomcat, and Ubuntu Tomcat.

SOLR 4.3, and Tomcat 7

Make sure that the file below is in the SOLR_Home /lib folder

solr-dataimporthandler-4.3.0.jar

As mentioned above you also need the reference in the config file.  Adjust the path as needed.

<lib dir="../../dist/" regex="apache-solr-dataimporthandler-\d.*\.jar" />
I might have some paths messed up, but that is how I got it to work.

A: The version is 4.3.1, I copied the dataimporthandler jar to /lib but it didn't work. I added this to conf/solrconfig.xml to fix this problem.
<lib dir="../../../dist/" regex="solr-dataimporthandler-.*\.jar" />

A: You need to add below code in your solrconfig.xml file under the config tag.
Note: Please change the version of jar files accordingly.
<lib dir="${solr.install.dir:../../../..}/dist/" regex="solr-dataimporthandler-.*\.jar" />
<lib dir="${solr.install.dir:../../../..}/dist/" regex="mysql-connector-java-5.1.18-bin.jar" />

For more information you can refer connecting-solr-to-database .


text:
Q: How to create internally optimized expression for computing with high WorkingPrecision? I have large dataset and need to fit rather complicated function on it with different values of one of its parameters (this parameter must be fixed in every fit). I use the "LevenbergMarquardt" algorithm of FindMinimum as described here (with the only difference that my function is not a "black-box").
I notice that if I set
Method -> {"LevenbergMarquardt",
   "Residual" -> Sqrt[2] residualVector[optimVariables],
   "Jacobian" -> {"Symbolic", EvaluationMonitor :> ++steps}}

then FindMinimum takes 5 minutes to create an optimized form of symbolic jacobian and after this every evaluation of the jacobian takes only 2 seconds.
I need to fit my function with many different values of the parameter and to spend 5 minutes for making the jacobian that is identical for all the fits (with exception for the value of only one parameter) is a waste of time. I tried to compute symbolic form of the jacobian by myself and got identical results with automatic symbolic jacobian. I used the code:
jacobianMatrix[_List?(VectorQ[#, NumberQ] &)] =
    D[Sqrt[2] residualVector[optimVariables], {optimVariables}]

and
Method -> {"LevenbergMarquardt",
   "Residual" -> Sqrt[2] residualVector[optimVariables],
   "Jacobian" -> {jacobianMatrix[optimVariables], EvaluationMonitor :> ++steps}}

The problem is that each evaluation of this symbolic jacobian with numerical values of parameters takes 4 minutes! Obviously FindMinimum optimizes its internal representation in some way and it gives huge speedup. But FindMinimum creates the jacobian for every fit again. Is it possible to optimize the internal representation manually?
I should stress that I compute with WorkingPrecision higher than MachinePrecision. So probably compilation is not an option.

A: Thanks to the recent post by ilian who uncovered and explained the undocumented Optimization`FindFit`ObjectiveFunction, I have found Optimization`FindFit`ResidualFunction which seems to be ideally suited to the original goals of the question. With the latter we don't even need to construct the residual vector explicitly, we just specify the model function and the data and get the optimized NumericalFunction automatically! A little example from the linked thread:
data = BlockRandom[SeedRandom[12345];
   Table[{x, Exp[-2.3 x/(11 + .4 x + x^2)] + RandomReal[{-.5, .5}]}, {x,
     RandomReal[{1, 15}, 20]}]];

residual = Optimization`FindFit`ResidualFunction[data, Exp[a x/(b + c x)], {a, b, c}, x]

Experimental`NumericalFunction[{a,b,c},Block[{x={2.69745,5.61891,11.9585,7.02236,4.1302,7.48274,11.3322,10.9067,12.0728,2.47999,6.32617,5.88977,8.63809,11.2304,11.0019,8.65308,4.26835,9.26918,3.04309,9.8615},Optimization`FindFit`y$588={0.972294,0.344088,0.767092,0.460704,0.947346,1.21116,0.439919,0.675085,1.17798,0.961116,0.720896,1.18664,0.605936,0.811138,0.861414,0.670646,0.770535,0.365288,0.649543,0.551157}},E^((a x)/(b+c x))-Optimization`FindFit`y$588],-NumericalFunctionData-]

A: On the base of findings in this thread the procedure is as follows.
Assuming that residualVect is the residual vector and initGuess is the initial guess for FindMinimum, let us create an internally optimized residual vector via Experimental`CreateNumericalFunction:
resV = Experimental`CreateNumericalFunction[initGuess[[;; , 1]],
   Sqrt[2]*residualVect, {Length[residualVect]}, WorkingPrecision -> 20];

Note that we have multiplied the true residual vector by Sqrt[2] in order to get the result consistent with the ordinary FindMinimum syntax where the first argument is equal to Total[residualVect^2].
Now FindMinimum can be used as follows:
FindMinimum[Null, initGuess, Method -> {"LevenbergMarquardt",
   "Residual" :> resV[initGuess[[;; , 1]]],
   "Jacobian" :> resV["Jacobian"@initGuess[[;; , 1]]]},
                             WorkingPrecision -> 20]

This approach gives more than one order of magnitude speedup in my application.


text:
Q: When are variables to be grouped in a regression? Suppose I have a data set with data for ages 18, 19, 20, ..., 40. When would it be wise to divide a variable like this into classes? For example, instead of using all ages define a group for young people (ages 18-25), older people (26-30) and mature people (31-40).
Also, how would the decision be made on where to set the boundaries?


text:
Q: CMake and running PC-Lint at file-level in Visual Studio Is there way to run PC-Lint either for a specific file or for the whole project in CMake-generated Visual Studio projects?
Currently I'm able to run PC-Lint per-project by creating custom targets using Kitware's script, but in my environment linting the whole project may take up to 10 minutes. So, I would also like to have a possibility to lint a specific source file only (and to choose that file from Visual Studio).
I was thinking, if PC lint could be used as custom "compiler" and to create for my target another project_LINT target that uses the lint "compiler". Then I could maybe select individual files to be "compiled". Or is this idea doomed? :)


text:
Q: Confused by an argument which is used in most triangle inequality proofs in metric spaces I'm confused by the a proof of the triangle inequality. I was supposed to prove that a function is a metric, I proved everything else except the triangle inequality.
Define $B(\mathbb{R})$ as the set of all bounded functions. For each $f,g \in B(\mathbb{R})$ define $\mu(f,g)=sup_{x \in \mathbb{R}}${$|f(x)-g(x)|$} .
To show that $sup_{x \in \mathbb{R}}${$|f(x)-g(x)|$} $\leq sup_{x \in \mathbb{R}}${$|f(x)-k(x)|$}$+sup_{x \in \mathbb{R}}${$|k(x)-g(x)|$} where $k(x) \in B(\mathbb{R})$. Why is it sufficient to show that $\forall x \in \mathbb{R}, |f(x)-g(x)| \leq sup_{x \in \mathbb{R}}${$|f(x)-k(x)|$}$+sup_{x \in \mathbb{R}}${$|k(x)-g(x)|$}?
I've witnessed a similar argument here

A: Your question is, essentially, whether $f(y) \leq c$ implies $\sup_y f(y) \leq c$. This follows immediately from the definition of $\sup$: since $c$ is an upper bound of the image of $f$, it is greater than or equal to the image's least upper bound.

A: If $f(x)\le a$ for all $x\in\mathbb R$, then $\sup_{x\in\mathbb R}f(x)\le a$, for if $r:=\sup_{x\in\mathbb R}f(x)\gt a$, then $(r+a)/2$ would be an upper bound for $f(x)$ that's less than $r$, contrary to the definition of the supremum.


text:
Q: Swift 3.0 Error: Ambiguous reference to member 'subscript' when setting a Dictionary value I've got this method below which inserts a value into a dictionary. In Swift 2.x, it worked as is.  When switching to Swift 3, I get the "Ambiguous reference to member 'subscript'" error.
Can anyone help me out in understanding why. Thanks
private func GetNames() -> AnyObject? {
    var returnList : [NSDictionary] = []
    let list = self.Names as! [NSDictionary]
    for name in list {
        var dict : Dictionary<NSObject, AnyObject> = [:]
        dict["id"] = name["id"]      // <-- ******Error*******
        dict["name"] = name["name"]  // <-- ******Error*******
        returnList.append(dict as NSDictionary)
    }
    return returnList as AnyObject
}

A: In Swift 3 String is type of Structure, so it will not work with NSObject and you have declare dictionary thats key type is NSObject that is the reason you are getting that error. To solve the error simply change type of dictionary to [String:Any] form [NSObject:AnyObject] and you all set to go.
var dict : [String:Any] = [:]

Note: Also in Swift don't use NSDictionary and NSArray use Swift's native type dictionary and array.

A: The error occurs because Swift 3 needs to know all types which are subscripted by key or index.
Using Foundation collection types is counterproductive because they lack exactly that type information the compiler needs.
Returning an optional AnyObject rather than the distinct (non-optional) [[String:Any]] is counterproductive, too.
The solution is to use only (as) specific (as possible) native Swift types.
private func getNames() -> [[String:Any]] {
    var returnList = [[String:Any]]()
    let list = self.Names as! [[String:Any]]
    for name in list {
        var dict = [String:Any]()
        dict["id"] = name["id"]
        dict["name"] = name["name"]
        returnList.append(dict)
    }
    return returnList
}

or swiftier if it's guaranteed that both keys name and id always exist
private func getNames() -> [[String:Any]] {
    let list = Names as! [[String:Any]]

    return list.map { ["id" : $0["id"]!, "name" : $0["name"]!]  }
}


text:
Q: Whitelisting IP addresses in Spring I have just finished following what appeared to be a straightforward tutorial at https://www.baeldung.com/spring-security-whitelist-ip-range
But once again I have found myself going around in circles trying to get it to work and wondered if anyone could help.
I'm trying to set up an IP address whitelist to access anything under /admin. Then the rest of the paths can be access by anyone.
I can confirm that breakpoints 1,2 are fired but the important breakpoint 3 is never reached. Everything under /admin is access-denied. I don't have any other authentication stuff configured. Anyone know what is going on?
So have SecurityConfig.java:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomIpAuthenticationProvider authenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       // 1
       auth.authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/admin/**").authenticated()
        .antMatchers("/**").permitAll()
            .and()
          .csrf().disable();
    }
}

CustomIpAuthenticationProvider.java
@Component
public class CustomIpAuthenticationProvider implements AuthenticationProvider {

   private Set<String> whitelist = new HashSet<String>();

    public CustomIpAuthenticationProvider() {
        // 2
        whitelist.add("x.x.x.x");
    }

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
      // 3
      WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
      String userIp = details.getRemoteAddress();
      if(! whitelist.contains(userIp)){
          throw new BadCredentialsException("Invalid IP Address");
      }
      return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true; // or false, doesn't make any difference
    }
}


text:
Q: NLog console highlight properties I've watched the following video explaining about Serilog. I would like to use structured logging in my application as well (at least parts of it), but I prefer to use NLog (1) because it's already part of our stack and we're used to it and prefer to have the same logger on across our projects, and (2) I have read the comparison here and seems like NLog is more performant.
So I read that NLog also support structured logging and I have implemented it in a test application without a problem. It works very well.
What I saw in the video and liked about Serilog, is when writing to console it highlights the parameters passed to the logging function like this:

I would like to have the same on the console application I'm currently building. I have tried both Console target and ColoredConsole but non has that effect. Is it possible in NLog?
This is my targets configurations:
<target name="file"
            xsi:type="File"
            archiveEvery="Day"
            archiveFileName="Logs\log.{#}.txt"
            fileName="Logs\log.txt"
            archiveNumbering="DateAndSequence"
            archiveDateFormat="yyyy-MM-dd"
            archiveAboveSize="104857600"
            maxArchiveFiles="30"
            layout="${longdate} | ${uppercase:${level}} | ${logger} | ${threadid} | ${message} ${exception}"
            />

    <target xsi:type="ColoredConsole"
          name="ColorConsole"
          layout="${uppercase:${level}}: ${message} ${exception:innerFormat=Message,StackTrace}"
          header="Memoriez API"
          useDefaultRowHighlightingRules="false"
          >
      <highlight-word foregroundColor="Green" ignoreCase="true" text="info" wholeWords="true" />
      <highlight-word foregroundColor="Red" ignoreCase="true" text="warn" wholeWords="true" />
      <highlight-word backgroundColor="Red" foregroundColor="White" ignoreCase="true" text="error" wholeWords="true" />
      <highlight-row backgroundColor="DarkRed" foregroundColor="Yellow" condition="level == LogLevel.Fatal" />
    </target>

A: I do not think you can colorized the parameters in ColoredConsoleTarget. It might be possible to use WordHighlighting, but you would quickly run into issues where matching a number would highlight all numbers and not just the parameter.
My guess is that you would need to write a custom ColoredConsoleTarget in order to highlight parameters. I just looked at the src\NLog\Targets\ColoredConsoleTarget.cs file and it only offers RowHighlightingRules and WordHighlightingRules. It looks like when the color codes are applied the LogEventInfo has been rendered into a plain string.
I think you would need to write a custom RenderLogEvent function that would render the color escape sequences for parameters. It would be a bit tricky because the GenerateColorEscapeSequences for WordHighlighting would escape any color sequences generated before it is called).
Here are my thoughts:

*

*Create a new class ColoredParamConsoleTarget with code copied from    ColoredConsoleTarget. It doesn't look like there are virtual methods to just override the existing class.

*Create a ColoredRenderLogEvent method and parse for parameters and add color sequences before and after parameters.

*Replace calls to RenderLogEvent with ColoredRenderLogEvent


text:
Q: Reflection does not respect @ symbol with reserved keyword classes I have a situation where the following class is created by the code generator. I don't have a control of how it generates.
    using System;
    using System.Reflection;

    namespace MyClasses
    {

        public class @event { };

    public class Program
    {
        public static void Main()
        {

            @event e = (@event) (Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, "MyClasses.@event")).Unwrap();
            Console.WriteLine("Created.");
        }
    }
    }

As you can see that it sees the class name with event reserved word, and it adds @ sign. After that it tries to create an object of the same using reflection by passing @ symbol, which reflection rejects.
If I replace it with
   @event e = (@event) (Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, "MyClasses.event")).Unwrap();
It works.
What is the possible solution here? I don't have a control on how it adds @ or uses @ ? I understand that reflection does not know about @ symbol being added. Thus, there has to be a way for the reflection to ignore @symbol while creating an object because technically you cannot have @ in your variable or a class name.
Fiddler link:  https://dotnetfiddle.net/wBs7GA


text:
Q: Removing duplicate urls python BeautifulSoup using set() blows apart the urls In python I have used BeautifulSoup to scrape urls from a website for a project and everything works great until I try to remove the duplicates by passing the tags into a set  object. The tags are "blown apart". Here is my code and example of print results.
file = open('parsed_data.csv', 'w')

for link in soup.find_all('a', attrs={'href': re.compile("^http")}):

    soup_link = str(link)
    if soup_link.endswith('/') or soup_link.endswith('#'):
        soup_link = soup_link[-1]

    soup_link_unique = str(set(soup_link))

    print (soup_link)
    print (soup_link_unique)

    file.write(soup_link_unique)
    file.flush()
    file.close
```
Before passing into set object:

After passing into a set object:
{'I', 'S', '\n', 'C', '>', 'u', '"', '-', 'i', 'Y', 'L', 'M', 'p', '.', 'c', ')', 'B', '2', 't', 'N', '<', ' ', 'b', 'w', 'e', 'E', '/', 'O', ':', 'U', 'x', 'o', 'W', 'f', '(', 'l', 'D', 'F', 'g', 'd', '_', '=', 'n', 's', 'h', 'a', 'T', 'v', 'r', ';', 'm', 'y'}

A: Create a set before the for loop and add new elements to the set using the method add():
soup_link_unique = set()

for link in soup.find_all('a', attrs={'href': re.compile("^http")}):
    soup_link = str(link)
    if soup_link.endswith('/') or soup_link.endswith('#'):
        soup_link = soup_link[-1]
    soup_link_unique.add(soup_link)

Example:
my_set = set('ABCDE')
print(my_set)
# {'E', 'D', 'C', 'B', 'A'}

vs
my_set = set()
my_set.add('ABCDE')
print(my_set)
# {'ABCDE'}


text:
Q: PivotField NumberFormat not being applied via VBA although it works manually PivotTable fields (measures) loose their formatting when removed from the pivot table. You have to re-format them after adding them back to the pivot table. I'm using Excel 2019, PowerPivot with datamodel inside the Excel.
I need formatting which includes different colors for +-0. This is the formatting: [Color10]0,00%;[Red]-0,00%;[Black]- (Color10 is a correct coded color in Excel for number formattting)
I'm trying to set up a macro which shall do that. I've recorded a macro. When the macro is run, it "invents" its own formatting and does not apply the one I gave it to do.
So, after the code is run, the numberformat applied is [Color10]#.000%;[Red]-#.000%;[Black]- instead of [Color10]0,00%;[Red]-0,00%;[Black]-. Note that when I apply this desired formatting manually - it stays as such.
It seems the issue is not related to the PivotTables or powerpivot itself. The same issue appears when trying to do
ActiveSheet.Range("F1").NumberFormat = "[Color10]0,00%;[Red]-0,00%;[Black]-"

It works if I apply desired formatting to a cell manually, and then apply the formatting from that cell to the pivottable field like this:
.PivotFields("[Measures].[M To Market vs IMS Volume %]").NumberFormat = ActiveSheet.Range("F1").NumberFormat

What am I missing?
Other non-macro options which I tried:

*

*This is NOT supported within Excel data model (colors!)

*This is not supported with DAX format function (colors!)

*Using manual formatting of cells even with setting pivottable property to preserve cell formatting on update doesn't preserve it when you change the fields in the pivot table.

*Same thing if you try ConditionalFormatting

Macro options which I tried:

*

*on pivottable update even for the worksheet - Excel regularly crashes (it calls the procedure like 30 times if I leave on error resume next; it throws an error otherwise and crashes.)

*I've deleted the "ghost" custom formatting, tried again, and Excel seemed to recreate that custom formatting that I did not wanted.

*I've searched for potential escape characters for % sign in VBA string but nothing special came up except for the double quotation marks themselves.

Sub set_pivottable_number_formatting()

    With ActiveSheet.PivotTables(1)
        MsgBox .PivotFields("[Measures].[M To Market vs IMS Volume %]").NumberFormat
        .PivotFields("[Measures].[M To Market vs IMS Volume %]").NumberFormat = "[Color10]0,00%;[Red]-0,00%;[Black]-"

        MsgBox .PivotFields("[Measures].[M To Market vs IMS Volume %]").NumberFormat
    End With

End Sub


text:
Q: Deactivating command blocks I have a command block that teleports you to another place - it is permanently on (because of redstone), so whenever I get close to the command block, it teleports me - it is really annoying. How can I deactivate it?

A: You could use McEdit, or go as close as possible to the command block, press F3 (fn + f3 on a mac), and find out the coordinates of the command block or the Redstone powering it, click t and type /setblock x y z air (replace x y and z with the command block or redstone coordinates)

A: *

*You can run a Minecraft server locally[1][2], set enable-command-block=false in server.properties (if it isn't already) and then just join the server IP localhost, go to the command block and break it.

*You can change the command in the command block using NBTEdit: Open the save folder with it, go to region\<the region file with the command block in it>\<the chunk with the command block in it>\Level\TileEntitites\13 entries\Command, double click, change it, "OK", then "Save" in the toolbar.

*You can get roughly the coordinates of the command block, then subtract 15 from each axis for the first set of coordinates and add 15 for the second set: /fill <x y z> <x y z> air 0 replace command_block

*You can use MCEdit. I can't give you instructions on that, because I haven't used it yet. But it's probably pretty easy to use.


text:
Q: reading the association relationship I read the illustrated relationship as:Class A associated with class B
So,what is the meaning of :
1) +class B at the end of association
2)0..1
Now,how can I read the relationship?

A: completely agree with @Wolfgang Fahl and @Idan Arye
Here some elaboration
1)your question touches the Association ends and in your case the
visibility (+)followed by role-name(class B)

An association end specifies the role that the object at one end of a
  relationship performs. Each end of a relationship has properties that
  specify the role of the association end, its multiplicity, visibility,
  navigability, and constraints.

2)to be more involved,look at the following class diagram:

customer may have many reservation
but each reservation owns by one customer
Hope this help you

A: 2) - for each instance of A there can be 0 or 1 instances of B associated with it.

A: the + denotes the visibility of the role. "+" is public. private would be shown as "-". The name of the role is classB which is the name of the class the role belongs to in lower case.


text:
Q: Using SQL databases I need to gather data for a client from multiple sources I have multiple databases that contain pieces of data that I need to collect on my clients.  Without giving any specific examples, due to confidentiality of the actual data, I will simply refer to what the field names are.
My Master table and three other tables contain the following columns -
Social Security Number,
Medicare Number,
Medicaid Number,
Phone Number,
Date of Birth,
Last Name,
First Name

The goal is to read a master record and, if all of the specified fields do not contain data, go and look at the other data sources to see if one of them DO contain the missing data.
Let me tell you an example of what the problem might be and see what suggestions you can give me to help me achieve my goal.  In my example I will call the master table Table 1.
Table 1 - Is missing the DOB, SSN & Medicaid# for this record.
Table 2 - Contains the DOB, Medicare# and Last & First Name.
Table 3 - Has DOB, Medicaid#, Phone Number and Last & First Name.
Table 4 - DOB, SSN, Medicare#, and Phone Number, and Last & First Name.
Currently, I am doing the following:
I created a view called View 1 to combine all of the tables together. The uncommon fields are simply NULL for the tables no containing the field.
I have nested case statements for each of the desired fields.  I look to see if the field in Table 1 is NULL, I begin doing a SubSelect statement to look for a matching record in the View 1 for each of the possible matching fields along with any secondary field to double check when needed - like if I do just DOB and Last & First Name matches.
I have a temporary table that gets updated with the findings prior to me running through the checks again.  I run through it multiple times since the first time through it might not have had a hit with one field, but the second time through it would find a match.
Does anyone see a better way of doing it thn what I have described?

A: This is the part that loses me:

I have a temporary table that gets updated with the findings prior to
  me running through the checks again. I run through it multiple times
  since the first time through it might not have had a hit with one
  field, but the second time through it would find a match.

Without that I would suggest left joining the tables to the master then using COALESCE() to find your best NOT NULL value.
COALESCE(Table_1.DOB,Table_2.DOB,Table_3.DOB,Table_4.DOB)


text:
Q: Sorting with two digits in string - Python I am new to Python and I have a hard time solving this.
I am trying to sort a list to be able to human sort it 1) by the first number and 2) the second number. I would like to have something like this:
'1-1bird'
'1-1mouse'
'1-1nmouses'
'1-2mouse'
'1-2nmouses'
'1-3bird'
'10-1birds'
(...)

Those numbers can be from 1 to 99 ex: 99-99bird is possible.
This is the code I have after a couple of headaches. Being able to then sort by the following first letter would be a bonus.
Here is what I've tried:
#!/usr/bin/python

myList = list()
myList = ['1-10bird', '1-10mouse', '1-10nmouses', '1-10person', '1-10cat', '1-11bird', '1-11mouse', '1-11nmouses', '1-11person', '1-11cat', '1-12bird', '1-12mouse', '1-12nmouses', '1-12person', '1-13mouse', '1-13nmouses', '1-13person', '1-14bird', '1-14mouse', '1-14nmouses', '1-14person', '1-14cat', '1-15cat', '1-1bird', '1-1mouse', '1-1nmouses', '1-1person', '1-1cat', '1-2bird', '1-2mouse', '1-2nmouses', '1-2person', '1-2cat', '1-3bird', '1-3mouse', '1-3nmouses', '1-3person', '1-3cat', '2-14cat', '2-15cat', '2-16cat', '2-1bird', '2-1mouse', '2-1nmouses', '2-1person', '2-1cat', '2-2bird', '2-2mouse', '2-2nmouses', '2-2person']

def mysort(x,y):
x1=""
y1=""

for myletter in x :
    if myletter.isdigit() or "-" in myletter:
        x1=x1+myletter

x1 = x1.split("-")

for myletter in y :
    if myletter.isdigit() or "-" in myletter:
        y1=y1+myletter

y1 = y1.split("-")

if x1[0]>y1[0]:
    return 1
elif x1[0]==y1[0]:
    if x1[1]>y1[1]:
        return 1
    elif x1==y1:
        return 0
    else :
        return -1
else :
    return -1

myList.sort(mysort)
print myList

Thanks !
Martin

A: You have some good ideas with splitting on '-' and using isalpha() and isdigit(), but then we'll use those to create a function that takes in an item and returns a "clean" version of the item, which can be easily sorted. It will create a three-digit, zero-padded representation of the first number, then a similar thing with the second number, then the "word" portion (instead of just the first character). The result looks something like "001001bird" (that won't display - it'll just be used internally). The built-in function sorted() will use this callback function as a key, taking each element, passing it to the callback, and basing the sort order on the returned value. In the test, I use the * operator and the sep argument to print it without needing to construct a loop, but looping is perfectly fine as well.
def callback(item):
    phrase = item.split('-')
    first = phrase[0].rjust(3, '0')
    second = ''.join(filter(str.isdigit, phrase[1])).rjust(3, '0')
    word = ''.join(filter(str.isalpha, phrase[1]))
    return first + second + word

Test:
>>> myList = ['1-10bird', '1-10mouse', '1-10nmouses', '1-10person', '1-10cat', '1-11bird', '1-11mouse', '1-11nmouses', '1-11person', '1-11cat', '1-12bird', '1-12mouse', '1-12nmouses', '1-12person', '1-13mouse', '1-13nmouses', '1-13person', '1-14bird', '1-14mouse', '1-14nmouses', '1-14person', '1-14cat', '1-15cat', '1-1bird', '1-1mouse', '1-1nmouses', '1-1person', '1-1cat', '1-2bird', '1-2mouse', '1-2nmouses', '1-2person', '1-2cat', '1-3bird', '1-3mouse', '1-3nmouses', '1-3person', '1-3cat', '2-14cat', '2-15cat', '2-16cat', '2-1bird', '2-1mouse', '2-1nmouses', '2-1person', '2-1cat', '2-2bird', '2-2mouse', '2-2nmouses', '2-2person']
>>> print(*sorted(myList, key=callback), sep='\n')
1-1bird
1-1cat
1-1mouse
1-1nmouses
1-1person
1-2bird
1-2cat
1-2mouse
1-2nmouses
1-2person
1-3bird
1-3cat
1-3mouse
1-3nmouses
1-3person
1-10bird
1-10cat
1-10mouse
1-10nmouses
1-10person
1-11bird
1-11cat
1-11mouse
1-11nmouses
1-11person
1-12bird
1-12mouse
1-12nmouses
1-12person
1-13mouse
1-13nmouses
1-13person
1-14bird
1-14cat
1-14mouse
1-14nmouses
1-14person
1-15cat
2-1bird
2-1cat
2-1mouse
2-1nmouses
2-1person
2-2bird
2-2mouse
2-2nmouses
2-2person
2-14cat
2-15cat
2-16cat

A: You need leading zeros. Strings are sorted alphabetically with the order different from the one for digits. It should be
'01-1bird'
'01-1mouse'
'01-1nmouses'
'01-2mouse'
'01-2nmouses'
'01-3bird'
'10-1birds'

As you you see 1 goes after 0.

A: The other answers here are very respectable, I'm sure, but for full credit you should ensure that your answer fits on a single line and uses as many list comprehensions as possible:
import itertools
[''.join(r) for r in sorted([[''.join(x) for _, x in
           itertools.groupby(v, key=str.isdigit)]
           for v in myList], key=lambda v: (int(v[0]), int(v[2]), v[3]))]

That should do nicely:
['1-1bird',
 '1-1cat',
 '1-1mouse',
 '1-1nmouses',
 '1-1person',
 '1-2bird',
 '1-2cat',
 '1-2mouse',
 ...
 '2-2person',
 '2-14cat',
 '2-15cat',
 '2-16cat']


text:
Q: Not getting row count, unless providing decimal expression in R Why nrow/NROW  is not giving results without decimal expression in R?
I tried calculating the number of rows in R and did not get results with nrow/NROW.
I tried the summary option but with that, I have to provide decimal expression.
I rounded the column using df$WAGE_RATE <- round(df$WAGE_RATE, digit = 0)
> class(h1b$WAGE_RATE)
"numeric"

> nrow(df$WAGE_RATE < '1000000')
NULL

> nrow(df$WAGE_RATE < '1000000.00')
NULL

> summarise(df, ct = sum(as.numeric(WAGE_RATE < '100000')))
 A tibble: 1 x 1
     ct
  <dbl>
1     0

> summarise(df, ct = sum(as.numeric(WAGE_RATE < '100000.00')))
 A tibble: 1 x 1
     ct
  <dbl>
1  9052

A: First of all, if you are dealing with a numeric column, you should not compare to a character (i.e. '1000000').
Second, When you do a comparison, you'll get a vector with TRUE/FALSE. Look at the example below:
mtcars$mpg < 22
 # [1]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE
 # [12] TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE
 # [23] TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE

As TRUE is equivalent of 1, you can get the sum and it tells you number of rows which are satisfying that condition (If you count number of TRUE entries, you'll see 23 of them).
sum(mtcars$mpg < 22)
 # [1] 23

But if you want to use nrow, you need to provide it with a data.frame. For that, you need to subset your data based on that condition. You can read more about that here: Extract a subset of a dataframe based on a condition involving a field. I simply provide the solution:
nrow(mtcars[mtcars$mpg < 22,])
 # [1] 23


text:
Q: WSS 3.0 site -where to store images and CSS files? I am creating a WSS 3.0 site and am not sure where to store images and CSS files.
I am thinking of creating a document library and adding 2 subfolders for images and CSS files.
Would that be a good practice? Or should I create 2 document libraries for the images and CSS files (instead of subfolders)?
Thank you for your help.

A: How are these images being used - are they part of the site template/design, and how many users do you have?
If you are deploying "branding" to change the sharepoint look and feel then you should probably deploy these as a sharepoint feature for better performance and easier maintenance. When you upload these files into the document library you will generate additional database calls. Features are served from disk on the IIS application running sharepoint which is less costly. Whether you need to go to this effort depends on your answer to the question above.


text:
Q: gpg: invalid key resource URL following WineHQ official guide I'm following the official guide to install WineHQ on my ubuntu 20.4.2 machine.
sudo dpkg --add-architecture i386
wget -nc https://dl.winehq.org/wine-builds/winehq.key

Which return
2021-03-27 23:49:12 (6.30 MB/s) - 'winehq.key' saved [3220/3220]

Now when I try to add this key,
sudo apt-key add winehq.key

I get this error:
gpg: invalid key resource URL '/tmp/apt-key-gpghome.pz8gFybm20/home:manuelschneid3r.asc.gpg'
gpg: keyblock resource '(null)': General error
gpg: key 7721F63BD38B4796: 2 signatures not checked due to missing keys
gpg: key 1488EB46E192A257: 1 signature not checked due to a missing key
gpg: key 1488EB46E192A257: 1 signature not checked due to a missing key
gpg: key 3B4FE6ACC0B21F32: 3 signatures not checked due to missing keys
gpg: key D94AA3F0EFE21092: 3 signatures not checked due to missing keys
gpg: key 871920D1991BC93C: 1 signature not checked due to a missing key
gpg: key 76F1A20FF987672F: 1 signature not checked due to a missing key
gpg: Total number processed: 10
gpg:       skipped new keys: 10

Even piping the command generate the same error. How to resolve it?
Update
I tried to update packages (guessing it will fix) but found this,
 falamiw@falamiw  ~  sudo apt-get update
Hit:1 http://packages.microsoft.com/repos/code stable InRelease
Get:2 https://dl.winehq.org/wine-builds/ubuntu focal InRelease [6,257 B]
Hit:3 http://dl.google.com/linux/chrome/deb stable InRelease
Err:2 https://dl.winehq.org/wine-builds/ubuntu focal InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 76F1A20FF987672F
Ign:4 http://ppa.launchpad.net/audacity-team/daily/ubuntu focal InRelease
Get:5 http://apt.postgresql.org/pub/repos/apt focal-pgdg InRelease [81.6 kB]
Hit:6 http://download.opensuse.org/repositories/home:/manuelschneid3r/xUbuntu_20.04  InRelease
Err:5 http://apt.postgresql.org/pub/repos/apt focal-pgdg InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 7FCC7D46ACCC4CF8
Hit:7 http://bd.archive.ubuntu.com/ubuntu focal InRelease
Get:8 http://security.ubuntu.com/ubuntu focal-security InRelease [109 kB]
Hit:9 http://ppa.launchpad.net/gerardpuig/ppa/ubuntu focal InRelease
Hit:10 http://archive.canonical.com/ubuntu focal InRelease
Get:11 http://bd.archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Err:12 http://ppa.launchpad.net/audacity-team/daily/ubuntu focal Release
  404  Not Found [IP: 91.189.95.85 80]
Get:13 http://bd.archive.ubuntu.com/ubuntu focal-backports InRelease [101 kB]
Reading package lists... Done
W: GPG error: https://dl.winehq.org/wine-builds/ubuntu focal InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 76F1A20FF987672F
E: The repository 'https://dl.winehq.org/wine-builds/ubuntu focal InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: GPG error: http://apt.postgresql.org/pub/repos/apt focal-pgdg InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 7FCC7D46ACCC4CF8
E: The repository 'http://apt.postgresql.org/pub/repos/apt focal-pgdg InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://ppa.launchpad.net/audacity-team/daily/ubuntu focal Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

Then tried to solve this following this
 ✘ falamiw@falamiw  ~  sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com --recv-keys 76F1A20FF987672F
Executing: /tmp/apt-key-gpghome.D1LG9HG0HV/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 76F1A20FF987672F
gpg: key 76F1A20FF987672F: public key "WineHQ packages <wine-devel@winehq.org>" imported
gpg: Total number processed: 1
gpg:               imported: 1
gpg: invalid key resource URL '/tmp/apt-key-gpghome.D1LG9HG0HV/home:manuelschneid3r.asc.gpg'
gpg: keyblock resource '(null)': General error
gpg: key 7721F63BD38B4796: 2 signatures not checked due to missing keys
gpg: key 1488EB46E192A257: 1 signature not checked due to a missing key
gpg: key 1488EB46E192A257: 1 signature not checked due to a missing key
gpg: key 3B4FE6ACC0B21F32: 3 signatures not checked due to missing keys
gpg: key D94AA3F0EFE21092: 3 signatures not checked due to missing keys
gpg: key 871920D1991BC93C: 1 signature not checked due to a missing key
gpg: Total number processed: 10
gpg:       skipped new keys: 10

A: For whom who are facing the similar issue I faced,

*

*In software & updates app → other softwares. Unchecked http://ppa.* (which create Err:* ), here is the original post where I get this.

*If possible uninstall those software packages and reinstall them

For WineHQ I follow this instruction afterward, which create no issue at all. Thanks, @Markus Ueberall Who help me to figure out a lot of things and give solution to resolve them.


text:
Q: How to set first option as default option I have worked on angular 4 project.
In this project, I have a requirement to set the first option as default option in select list.
But problem is that this select box is under a child component and data from this select box is build passed from parent component.
For better understanding the code is as follow:
parent component html :
<serviceSelect [services]="services"></serviceSelect>

child component html:
<select [(ngModel)]="selectedServiceType" [ngModelOptions]="{standalone: true}" (ngModelChange)="getServiceType($event)">
   <ng-container *ngFor="let service of settings?.service_type">
       <option [ngValue]="service">{{service.name}}</option>
   </ng-container>
</select>

child component .ts code:
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';

@Component({
   selector: 'serviceSelect',
   templateUrl: './serviceSelect.component.html',
   styleUrls: ['./serviceSelect.component.scss']
})
export class serviceSelectComponent {
      @Input() services : any;
      selectedServiceType: any;

      getServiceType(event) {
        this.selectedServiceType = event;
      }
}

We do not have access to services variable in ngOnInit or ngAfterViewInit.
I have tried to set default value through these functions. If any other suggestion how to first option as default let me know.


text:
Q: JSON Getting path not using ajax i have a txt file named simpleJson.txt
{"Dev":[
             {"firstName":"Ivy","lastName":"Razonales", "middleName":"Andres" },
             {"firstName":"Alexis","lastName":"Escober", "middleName":"Johnson" },
             {"firstName":"Dennis John","lastName":"Biel", "middleName":"Smith" }]
}

and here is my function
function jsoninTxt_func(){

    var obj = JSON.parse("simpleJson.txt");
    var txt = "";
    for (i = 0; i < obj.Dev.length; i++) {
        txt = txt + obj.Dev[i].firstName + " "
                + obj.Dev[i].middleName + " "
                + obj.Dev[i].lastName + "
"
    }
    document.getElementById("jsoninTxt").innerHTML = txt;

}

I need help how to fix this without using AJAX or JQUERY just the json itself
var obj = JSON.parse("simpleJson.txt");

A: Without using AJAX or JQUERY means you have to hard-code the JSON in your function as follows -- no longer in a file:
function jsoninTxt_func(){
    var obj = {"Dev":[
        {"firstName":"Ivy","lastName":"Razonales", "middleName":"Andres" },
        {"firstName":"Alexis","lastName":"Escober", "middleName":"Johnson" },
        {"firstName":"Dennis John","lastName":"Biel", "middleName":"Smith" }]
              };
    var txt = "";
    for (i = 0; i < obj.Dev.length; i++) {
        txt = txt + obj.Dev[i].firstName + " "
        + obj.Dev[i].middleName + " "
        + obj.Dev[i].lastName + "
"
    }
    document.getElementById("jsoninTxt").innerHTML = txt;
}

jsoninTxt_func();

JSFIDDLE DEMO


text:
Q: location rewrite for multiple domains I am working on multiple projects so I have multiple domains :
1. domain1
2. domani2

how to rewrite for example
domain1/user to domain1/?page=user,
domain2/user to domain2/clientArea/userMain

Now I am using :
   location /user {
     rewrite ^/user$ /?page=user;
   }

but it rewrites all my domains.
P.S : I am new to nginx, and I am using Winginx local server;

A: There's 2 ways to do this depending on whether you have 1 or 2 server-blocks (if you expect lots of configuration differences between the 2 domains use 2, if the 2 domains have mostly the same content use 1)
in the case of 2 server-blocks config looks like this:
server {
  server_name domain1;
  location /user/ { rewrite ^ $scheme://$host/?page=user; }
  # add in rest of domain 1 config
}

server {
  server_name domain2;
  location /user/ { rewrite ^ $scheme://$host/clientArea/userMain; }
  # add in the rest of your domain 2 config

}
in the case of a single server-block it would look like this:
server {
  server_name domain1 domain2;
  location /user/ {
    if ($host = domain1) { rewrite ^ $scheme://$host/?page=user; }
    if ($host = domain2) { rewrite ^ $scheme://$host/clientArea/userMain; }
  }
}

Note: that you can use the ^ regex as rewrite condition because because the location /user/ block it's in already selects out the url's you want to rewrite. That makes it slightly more efficient as the regex will be matched faster.


text:
Q: Why does forEach work with e.target.children but not getElementById children? I have an SVG/button that contains several color elements. The idea is to have the elements slide in, one-by-one on mouseEnter, and leave through the opposite side on mouseLeave, then reset so it can be performed again.
When using [...e.target.children] to create an array, the subsequent forEach function works correctly. When using getElementById and converting to array, I am getting the error "is not a function.
The former returns a list of actual elements while the latter returns just a list. How can I correctly convert the array so the forEach function works?
<svg id="HeroButton" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 270 48">
  <title>HeroButton</title>
  <polygon className="pink" points="29 23 52 0 15 0 0 0 0 48 15 48 54 48 29 23" fill="#ed3e88"/>
  <polygon className="yellow" points="97.5 40.5 114 24 96 24 96 0 52 0 29 23 54 48 82 48 82 40.5 97.5 40.5" fill="#fded52"/>
  <polygon className="turq" points="155.5 19.5 175 0 116 0 96 0 96 24 114 24 97.5 40.5 82 40.5 82 48 116 48 156.5 48 185 19.5 155.5 19.5" fill="#17adcb"/>
  <polygon className="beige" points="224.5 33 224.5 13.5 238 0 189 0 175 0 155.5 19.5 185 19.5 156.5 48 189 48 239.5 48 224.5 33" fill="#ffffc7"/>
  <polygon className="turq2" points="243 0 238 0 224.5 13.5 224.5 33 239.5 48 243 48 270 48 270 0 243 0" fill="#17adcb"/>
</svg>

export default class HeroButton extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      translate: "translateX(100%)",
      opacity: 1
    }
  };
  componentDidMount() {
    // const polygons = [...document.getElementById('HeroButton').children;
    const polygons = Array.from(document.getElementById('HeroButton').children);
    console.log({polygons})
    this.updatePolygons(polygons);
    this.setState({
      translate: "translateX(-100%)",
      opacity: 0
    });
  };
  handleMouseEnter = (polygons) => {
    this.updatePolygons(polygons)
  };
  handleMouseLeave = (polygons) => {
    this.setState({
      translate: "translateX(100%)",
      opacity: 1
    });
  };
  updatePolygons = (polygons) => {
    // const polygons = [...e.target.children];
    polygons.forEach(child => {
      child.style.transform = this.state.translate;
      child.style.opacity = this.state.opacity;
    });
  };
  render() {
    return(
      <button>
        <HeroButtonSVG
          onMouseEnter={this.handleMouseEnter}
          onMouseLeave={this.handleMouseLeave}
        />
        Check out my work
      </button>
    );
  };
};

.Hero button {
  position: relative;
  overflow: hidden;
  display: flex;
  background: transparent;
  border: none;
  transition: all .3s ease;
  text-transform: uppercase;
  outline: none;
}

.Hero button svg {
  display: flex;
  width: 275px;
  border: 1px solid white;
}

.Hero button svg polygon {
  /* transform: translateX(100%); */
  transition: all .3s ease;
}

.Hero button svg polygon.yellow {
  transition-delay: .1s;
}

.Hero button svg polygon.turq {
  transition-delay: .2s;
}

.Hero button svg polygon.beige {
  transition-delay: .3s;
}

.Hero button svg polygon.turq2 {
  transition-delay: .4s;
}

.Hero button span {
  display: inline-flex;
  position: absolute;
  top: 50%;
  left: 50%;
  white-space: nowrap;
  color: white;
  font-family: Raleway;
  font-weight: 400;
  font-size: var(--medium);
  transform: translate(-50%,-50%);
  pointer-events: none;
}

.Hero button span i {
  margin-left: var(--small);
}

A: Look at the two pieces of code you have here:
Event Handler
  updatePolygons = (polygons) => {
    // const polygons = [...e.target.children];
    polygons.forEach(child => {
      child.style.transform = this.state.translate;
      child.style.opacity = this.state.opacity;
    });
  };

Event Listener
    <HeroButtonSVG
      onMouseEnter={this.handleMouseEnter}
      onMouseLeave={this.handleMouseLeave}
    />

The value that gets passed into updatedPolygons() is not an array. Therefore it does not have a method called forEach(). Which is why you get the error "polygons.forEach() is not a function" when you run this code.
However, the actual value that gets passed is the event, an object {}. When you go deeper into the properties, you can access the children array like event.target.children, which is an array you can iterate over. So .forEach() is legal. Hence [...event.target.children]
It looks like you're trying to use the polygons variable you defined inside componentDidMount(). However, that polygons is not available outside componentDidMount(). You can explicitly create a polygons property and access/mutate it from anywhere in your component.
Additionally, I've created some extra logic to help you create the animation you want. See working code and sandbox below:
import React from "react";
import ReactDOM from "react-dom";
import HeroButtonSVG from "./HeroButtonSVG";

import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      translate: "translateX(100%)",
      opacity: 1
    };
  }

  polygons = [];

  componentDidMount() {
    // const polygons = [...document.getElementById('HeroButton').children;
    this.polygons = Array.from(document.getElementById("HeroButton").children);
    this.setState(
      {
        translate: "translateX(100%)",
        opacity: 0
      },
      () => this.updatePolygons()
    );
  }
  handleMouseEnter = () => {
    this.setState(
      {
        translate: "translateX(0%)",
        opacity: 1
      },
      () => this.updatePolygons()
    );
  };
  handleMouseLeave = () => {
    this.setState(
      {
        translate: "translateX(100%)",
        opacity: 0
      },
      () => this.updatePolygons()
    );
  };
  updatePolygons = () => {
    // const polygons = [...e.target.children];
    this.polygons.forEach(child => {
      child.style.transform = this.state.translate;
      child.style.opacity = this.state.opacity;
    });

    console.log(this.polygons);
  };
  render() {
    return (

        <button>
          <HeroButtonSVG
            onMouseEnter={this.handleMouseEnter}
            onMouseLeave={this.handleMouseLeave}
          />

            Check out my work

        </button>

    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

So with the polygons property defined, you can access it from anywhere in your component. Additionally, you do not need to explicitly pass it to your event-handlers. Simply use this.polygons anytime you want to use it.
Sandbox: https://codesandbox.io/s/dark-surf-v87m7

A: gumball,
you can take the children in a different array and then can use the forEach on that array.
const el = document.getElementsByClassName('js-favorite-btn s-btn s-btn__unset c-pointer py8')

when using el[0].children.forEach gives me error
el[0].children.forEach is not a function

But when using
const arr = [el[0].children]

and then running a forEach works.
I hope this works with you.


text:
Q: Set Up Xcode In Terminal I was wondering how I could import a Xcode project into terminal on Mac. Right now the terminal just says My name and Macbook Pro. How could I get the terminal default line to say My Xcode project name so I can install the Cocoa Pods.
Sorry if this is a confusing question, I am new to Xcode.
Thanks.


text:
Q: Escaping this javascript code in php I'm failing at escaping this code snippet that I only want to make visible on the page if a username is logged in. Then it just echoes that code, but as you can see, it's a large chunk that I need to escape. How do I go about that with this? Normally I don't have too much trouble with it myself but this code won't simply work otherwise.
//if user is logged in echo the code

if (isset($_SESSION['username'])){

echo '

   ';
  }
?>

A: The simplest approach, IMHO would be to use a nowdoc:
$javascript = <<<'JAVASCRIPT'

JAVASCRIPT

if (isset($_SESSION['username'])) {
    echo $javascript;
}

A: The issue is that you have single quotes to encapsulate the HTML and more inside the HTML that haven't been escaped \'.  See PHP Strings.
But to present an alternative since there is no PHP in the HTML, just break out of PHP:
<?php
if (isset($_SESSION['username'])){
?>

<?php
  }
?>

Also see Alternative syntax for control structures that may be easier or more readable.


text:
Q: In image gallery, images are not adjust properly I have some problem with image gallery, I want space right side of image but don't want to change the width of main div because header and footer have same width as main div, So I want image gallery adjust in main div. My code is as below:
HTML:

Eiffel Tower - Paris, France

Taj Mahal - Agra, India

Harbour Bridge - Sydney, Australia

Opera House - Sydney, Australia

Twin Towers - Kuala Lumpur, Malaysia

Tower Bridge - London, UK

CSS:
.main1{width: 73%; margin: 0 auto;border: 1px solid red;}

.content-box-left-bootomgrid{width:32%;float:left;}

.content-box-left-bootomgrid p{
font-family: Times New Roman, Helvetica, sans-serif;
color: #000000;
font-size: 0.875em;
padding: 0.5em 0;
line-height: 1.8em;
text-align:center;}

.content-box-left-bootomgrid img{
background:#000000;
padding:6px;
display:block;
width: 96%;
transition: 0.5s ease;
-o-transition: 0.5s ease;
-webkit-transition: 0.5s ease;}

.content-box-left-bootomgrid:hover img{
background:#71D6EA;}

A: try box-sizing: border-box. It emulates the ie box-model.
https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing


text:
Q: How to use google analytics content group data in a real time I have a website that enabled google analytics content grouping by tracking code.
For channel one ==> ga('set', 'contentGroup1', 'Channel1');
For channel two ==> ga('set', 'contentGroup1', 'Channel2');
Can I use it like above so later I can check what data for Channel1 and Channel2
Also I want to check is it possible to use content grouping data in the real time ?

A: As a matter of nomenclature, content groupings have nothing to do with "Channels" as the word is usually used in Analytics. "Channel" mostly refers to the marketing channel, i.e. the way you have acquired a visit by a user. Channel is a session based metric that does not change during a session (because changing the channel will by definition start a new session). You can see the information that defines the channel (i.e. source, medium, campaign) in the realtime view (but not the channel itself).
On the other hand it might be that you are simply using the english word "channel" to separate your content into groups.
Content groups are a hit based metric, meaning this does not pertain to visits or user but to individual pageviews. So yes of course, you can see data per content group - you'd have to go to the behavior reports in the menu; if you look at the "All pages" data table there is a small navigation above the table where you can select your content groups as primary dimension. This will show you aggregated hit based metrics (pageviews, entrances, bounces etc) per content group.
You cannot use this in realtime view.


text:
Q: Doctrine2 doesn't set sequence to default for id column (postgres) Just a simple example: If I want create a table with auto fill id in postgres I run this sql:
CREATE SEQUENCE person_id_seq  START 1;

CREATE TABLE person (
    id         integer PRIMARY KEY DEFAULT nextval('person_id_seq'),
    name       varchar(100) NOT NULL
);

and in doctrine I set all property
class Person {

/**
 * @Id
 * @Column(type="integer", nullable=false)
 * @GeneratedValue(strategy="SEQUENCE")
 * @SequenceGenerator(sequenceName="person_id_seq", initialValue=1, allocationSize=100)
 */
private $id;

but when I generated sql (php doctrine orm:schema-tool:create --dump-sql) I got it:
CREATE TABLE person (
    id INT NOT NULL,
    name VARCHAR(100) NOT NULL
);
CREATE SEQUENCE person_id_seq INCREMENT BY 100 MINVALUE 1 START 1

but don't set it to default
\d person
      Column       |              Type              | Modifiers
-------------------+--------------------------------+-----------
 id                | integer                        | not null
...
..
.

A: I encountered this problem today and I found that:

*

*IDENTITY work good, because it uses SERIAL type for PostgreSQL, which automatically creates related sequence and set default value as nextval(sequence)

*AUTO creates table and then related sequence, but doesn't set default value for id column.
It can be set by adding following code:
/**
 * Webpage's ID
 *
 * @ORM\Id
 * @ORM\Column(type="integer", options={"default"="nextval('webpages_id_seq'::regclass)"})
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $id;

but unfortunately Doctrine create table first, so we need to swap SQL code creating table and sequence in order that sequence will be created first

*SEQUENCE works the same as AUTO

A: From the fine manual:

4.8.1. Identifier Generation Strategies
  ...
AUTO (default): Tells Doctrine to pick the strategy that is preferred by the used database platform. The preferred strategies are IDENTITY for MySQL, SQLite and MsSQL and SEQUENCE for Oracle and PostgreSQL. This strategy provides full portability.
  ...
IDENTITY: Tells Doctrine to use special identity columns in the database that generate a value on insertion of a row. This strategy does currently not provide full portability and is supported by the following platforms: MySQL/SQLite (AUTO_INCREMENT), MSSQL (IDENTITY) and PostgreSQL (SERIAL).

They suggest AUTO for maximum portability:
/**
 * @Id
 * @Column(type="integer", nullable=false)
 * @GeneratedValue
 */

That should create and wire up a sequence for you. An alternative would be to ask for a serial column using the IDENTITY strategy:
/**
 * @Id
 * @Column(type="integer", nullable=false)
 * @GeneratedValue(strategy="IDENTITY")
 */

This one should create your id column as type serial and PostgreSQL will create the sequence and set up the default value for you.
The documentation indicates that what you're doing should work but the documentation usually only provides a simplified version of reality.
Try using strategy="AUTO". If that doesn't work, try strategy="IDENTITY".

A: I also encounter, that the sequence is generated, but not assigned.
So, this is the output of bin/console doctrine:schema:create --dump-sql
CREATE TABLE data_sample (id INT NOT NULL, hashvalue VARCHAR(64) DEFAULT NULL, date TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, refdate TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, value NUMERIC(20, 2) NOT NULL, PRIMARY KEY(id));

CREATE SEQUENCE data_sample_id_seq INCREMENT BY 1 MINVALUE 1 START 1;

A: Example of XML PostgreSQL Serial type
<id name="addressId" type="integer" column="address_id">
  <generator strategy="IDENTITY"/>
  <options>
    <option name="default">nextval('decide_config.address_address_id_seq'::regclass)</option>
  </options>
</id>


text:
Q: Cannot access folder xampp I have htdocs/myproject/web folder but I cannot access that web folder, i can access all others folders inside htdocs/myproject/. It doesn't show when I open localhost in web browser and it shows folder structre. Other folders are showing, where could be problem ? .. This project is downloaded from SVN.

A: You could check if there is a .htaccess file in the directory where indexing is disabled (for example Options -Indexes).


text:
Q: System.Windows.Forms.Timer And MessageBox can someone please let me know why the System.Windows.Forms.Timer continues to show multiple message boxes? I thought that it is on GUI thread ... and therefore after the first messagebox the GUI thread should block. But this is not the case
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    int nValue = 0;

    void tmr_Tick(object sender, EventArgs e)
    {
        nValue++;
        MessageBox.Show(nValue.ToString());
    }

    System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();

    private void btnStartTimer_Click(object sender, EventArgs e)
    {
        tmr.Interval = 500;
        tmr.Enabled = true;
        tmr.Tick += new EventHandler(tmr_Tick);
    }
}

A: The MessageBox.Show() method includes (as all modal dialogs do) a message loop that continues to pump window messages.
Window messages are what allow a window to interact with the user (update itself, accept input, etc.), as well as what allows the Forms.Timer class to work.
If you want your Forms.Timer to stop ticking when the dialog is shown, you need to set the timer's Enabled property to false before you show the dialog.

A: In your Tick event stop the timer and then start again after MessageBox.Show like:
void tmr_Tick(object sender, EventArgs e)
{
    tmr.Enabled = false;
    nValue++;
    MessageBox.Show(nValue.ToString());
    tmr.Enabled = true;
}

The reason you are getting repeated MessgeBoxes is because your timer is continuing after showing the first MessageBox.

A: A message box does not block the GUI-Thread. It's as simple as that. You can interact with the message box, after all :)
Also: The internal workings of the timer are not clear, but I would guess that it runs on another thread and just returns on the GUI-Thread.


text:
Q: ImproperlyConfigured: Error importing middleware - Django wsgi error Apache I have a Python Django site in one of my AWS Linux Server. First of all, let me tell you what I have done to host my Django app on my server. By default, the server has been installed with Python 2.6.9. For my application, I have compiled and installed Python 2.7.6 in a different location(/opt/python2.7.6). Still, the default python is 2.6.9. My application is under a virtual environment which has been created against this newly installed Python(2.7.6). My Web server is Apache2 (Version 2.4) and installed WSGI module by compiling the same against Python 2.7.6 using the below command.
./configure --with-python=/opt/python2.7.6/bin/python
I have configured apache accordingly and I am getting the following error. Kindly advice me how to resolve this issue.
[Mon Mar 21 10:38:32.669216 2016] [:info] [pid 26256] mod_wsgi (pid=26256): Create interpreter 'www.example.com|'.
[Mon Mar 21 10:38:32.671113 2016] [:info] [pid 26256] mod_wsgi (pid=26256): Adding '/home/testuser/example.com' to path.
[Mon Mar 21 10:38:32.671607 2016] [:info] [pid 26256] mod_wsgi (pid=26256): Adding '/home/testuser/venv/lib/python2.7/site-packages' to path.
[Mon Mar 21 10:38:32.672621 2016] [:info] [pid 26256] mod_wsgi (pid=26256): Adding '/home/testuser/example.com/example' to path.
[Mon Mar 21 10:38:32.681871 2016] [:info] [pid 26256] [client x.x.x.x:46626] mod_wsgi (pid=26256, process='www.example.com', application='www.example.com|'): Loading WSGI script '/home/testuser/example.com/example/wsgi.py'.
[Mon Mar 21 06:38:33.341024 2016] [:error] [pid 26256] [client x.x.x.x:46626] mod_wsgi (pid=26256): Exception occurred processing WSGI script '/home/testuser/example.com/example/wsgi.py'.
[Mon Mar 21 06:38:33.341297 2016] [:error] [pid 26256] [client x.x.x.x:46626] Traceback (most recent call last):
[Mon Mar 21 06:38:33.341478 2016] [:error] [pid 26256] [client x.x.x.x:46626]   File "/home/testuser/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 236, in __call__
[Mon Mar 21 06:38:33.341772 2016] [:error] [pid 26256] [client x.x.x.x:46626]     self.load_middleware()
[Mon Mar 21 06:38:33.341926 2016] [:error] [pid 26256] [client x.x.x.x:46626]   File "/home/testuser/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 53, in load_middleware
[Mon Mar 21 06:38:33.342238 2016] [:error] [pid 26256] [client x.x.x.x:46626]     raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
[Mon Mar 21 06:38:33.342400 2016] [:error] [pid 26256] [client x.x.x.x:46626] ImproperlyConfigured: Error importing middleware django.contrib.auth.middleware: "/home/testuser/venv/lib/python2.7/site-packages/psycopg2/_psycopg.so: undefined symbol: PyUnicodeUCS2_AsUTF8String"

I have tried many things to resolve this issue from google suggestions but not yet working.
Below is my apache conf file.
<VirtualHost  *:80>
ServerName www.example.com

DocumentRoot /home/testuser/example.com
LogLevel info
ErrorLog /home/testuser/http_error.log
CustomLog /home/testuser/http_access.log combined

WSGIDaemonProcess www.example.com processes=2 threads=15 display-name=%{GROUP} python-path=/home/testuser/example.com:/home/testuser/venv/lib/python2.7/site-packages
WSGIProcessGroup www.example.com

WSGIScriptAlias / /home/testuser/example.com/example/wsgi.py
Alias /media /home/testuser/site_assets/media
Alias /static /home/testuser/example.com/.static_built
<Directory /home/testuser/example.com/example>
    <Files wsgi.py>
        Order allow,deny
        Allow from all
    </Files>
</Directory>
</VirtualHost>

Please note, the site work well with standalone python runserver command.
Please let me know if any other details you need.
Thanks,

A: I got it resolved. I had three Python versions(2.7.6, 2.6.9 and 2.7.10) running on my server, but by default it was 2.6.9. Even though my python virtual environment was against 2.7.6, Apache didn't pick up that python for my application. I don't know why that happened. When I add **WSGIPythonHome* as pointing to my virtual environment python, at the top of my apache configuration file it worked perfect. Please see the updated apache configuration file below.
WSGIPythonHome /home/testuser/venv
<VirtualHost  *:80>
ServerName www.example.com

DocumentRoot /home/testuser/example.com
LogLevel info
ErrorLog /home/testuser/http_error.log
CustomLog /home/testuser/http_access.log combined

WSGIDaemonProcess www.example.com processes=2 threads=15 display-name=%{GROUP} python-path=/home/testuser/example.com:/home/testuser/venv/lib/python2.7/site-packages
WSGIProcessGroup www.example.com

WSGIScriptAlias / /home/testuser/example.com/example/wsgi.py
Alias /media /home/testuser/site_assets/media
Alias /static /home/testuser/example.com/.static_built
<Directory /home/testuser/example.com/example>
    <Files wsgi.py>
        Order allow,deny
        Allow from all
    </Files>
</Directory>
</VirtualHost>


text:
Q: Saving Files in to the memory/virtual file C# Is there any possibilities to save a file to a virtual folder or something.
I use a method, which needs a string(path,where to save the file) as parameter to save the content. But i just want to save the file into the memory.Can I programmatically create a virtual folder/path?

A: If your component want to recevice a file, you need a file on your HDD/SSD. In those cases, i prefer to use the APP-Data folder and create a sub directory in it. It is accessable over: Environment.SpecialFolder.LocalApplicationData.
To come back to your question, it is not possible. Because the method you want to use, will take the os file system.
The only in memory solution would be, if there is an overload which accept a MemoryStream or just a Stream.