text:
Q: Error in "Building a RESTful Web Service" I am a newbie in Spring Framework. I am studying a tutorial. It is at https://spring.io/guides/gs/rest-service/
below is my doing.
STS's version is 3.7.2
[Menu] - File - New - Spring starter project
Name : rest-service
Type : Gradle(STS)
Packaging : Jar
Java Version : 1.8
Group : com.example
Artifact : rest-service
Version : 0.0.1-SNAPSHOT
Description : Building a RESTful Web Service
Package : com.example
click [Next]
Not Select any Dependency.
click [Next]
Full Url : http://start.spring.io/starter.zip?name=rest-service2&groupId=com.example&artifactId=rest-service&version=0.0.1-SNAPSHOT&description=Building+a+RESTful+Web+Service&packageName=com.example&type=gradle-project&packaging=jar&javaVersion=1.8&language=java&bootVersion=1.3.0.RELEASE
click [Finish]
copy and paste source
change "package hello;" to "package com.example;"
package com.example;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

package com.example;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                        String.format(template, name));
    }
}

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestServiceApplication.class, args);
    }
}

I clicked [Run As] - [Spring Boot App] but it is strange. If I download and run that project, it is well. If I make a project and type source, Error occurs. I thought that build.gradle has a problem. But I don't know exactly.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.0.RELEASE)

2015-12-02 15:51:50.706  INFO 4808 --- [           main] com.example.RestServiceApplication       : Starting RestServiceApplication on John-PC with PID 4808 (C:\Users\John\Documents\workspace-sts-3.7.1.RELEASE\rest-service\bin started by John in C:\Users\John\Documents\workspace-sts-3.7.1.RELEASE\rest-service)
2015-12-02 15:51:50.708  INFO 4808 --- [           main] com.example.RestServiceApplication       : No profiles are active
2015-12-02 15:51:50.744  INFO 4808 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@45afc369: startup date [Wed Dec 02 15:51:50 KST 2015]; root of context hierarchy
2015-12-02 15:51:51.334  INFO 4808 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-12-02 15:51:51.343  INFO 4808 --- [           main] com.example.RestServiceApplication       : Started RestServiceApplication in 0.818 seconds (JVM running for 1.268)
2015-12-02 15:51:51.343  INFO 4808 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@45afc369: startup date [Wed Dec 02 15:51:50 KST 2015]; root of context hierarchy
2015-12-02 15:51:51.345  INFO 4808 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

How can I fix it?


text:
Q: Numero random de 2 cifras en javascript tengo una duda, estoy realizando una aplicación en la cual cuando el usuario olvida su contraseña, se le generará una aleatoria al introducir su usuario, es una prueba.
Tengo echo esto: Math.floor(Math.random() * (1 - 99)) + 1;
Quiero generar un numero random entre 1 y 99 pero que sea positivo, ya que aveces me genera un numero negativo.
Gracias de antemano.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Line defined by two geographical points crossing circle area with defined radius I'm trying to calculate the number of lines crossing a circle area defined by a center and radius.

This algorithm didn't work for me, it returns too many lines.
Is there any other approach which could help my to calculate the lines crossing the circle?

A: The shapely library can help you. There is no real circle, but a polygon can substitute it. The minimum solution can be:
from shapely.geometry import Point, Linestring
c = Point(0, 0).buffer(10)    # circle approximation from 64 points
l = LineString([(-11, -11), (11, 30)])  # line from two points
c.intersects(l)  # returns True
l1 = LineString([(-1, -1), (1, 3)])     # another line
c.intersects(l1) # returns True
l2 = LineString([(-11, -20), (11, -30)])     # another line
c.intersects(l2) # returns False


text:
Q: How do I know that my MySQL alter table statement is working? I am running an alter table statement over a table with 350 million rows.  How can I know that the statement is actually doing something and is not hung?  Equally I'd hate to disturb a statement potentially moments before it finishes.  Especially after it has run for hours.
I need to be able to script this in either Bash or PERL as I the host is a Redhat Linux box.  The statement in this case is:
ALTER TABLE table_name AUTO_INCREMENT = 1;

A: What you're actually looking for is this. SHOW PROCESSLIST. I will also add that updating auto increments does indeed take an extraordinary amount of time when working with large data sets (as you've discovered)
http://dev.mysql.com/doc/refman/5.1/en/show-processlist.html
If you open up a new connection to the DB and run that command, it will show you what stage (not how long is left) the query being run is at. Either copying to temp table, finalizing, etc

A: As others have mentioned, SHOW PROCESSLIST is your friend. Sometimes. When having multiple long queries you might want to add FULL to that statement: SHOW FULL PROCESSLIST. With FULL the result will contain the complete query in the Info column.
I wonder why your query is slow in the first place. MySQL should have a good idea about where to look for the last record in that table. If it's auto_increment it's indexed as well, and it should be super easy for MySQL to do.
PROCESSLIST often gives a good hint on where MySQL is in it's work, and especially if a query/command is blocked for some reason.

A: Just to give to you another option ...
You can try developer tool SQLyog  .
it shows query profile with variations in variables along with progress of statement


text:
Q: Adjust the starting position of bar plots in ggplot I was wondering if there is a way for me to adjust the location where the notches of the axis meet the edge of the bar plot. If you see in the image below all the notches of the x-axis line up in the center of the bar, I would like them to line up with the left edge of the bar! Is this possible?
Edit: Heres what my code looks like
hr6_xy = data.frame(hr6_bins, hr6_Occur)

hr6_plot = ggplot(hr6_xy, aes(hr6_bins, hr6_Occur)) +
  geom_bar(stat = "identity",
           color = 'black', fill = 'pink', width = 1)
hr6_plot = hr6_plot + theme_bw()
hr6_plot = hr6_plot + ggtitle("hr6 (68 sites)")
hr6_plot = hr6_plot + xlab("Distance to TSS from Motif Center, kb")
hr6_plot = hr6_plot + ylab("Occurances")
hr6_plot

A: Two ways I can think of:
(a) shift the position of the bars with position_nudge
ggplot(data = iris, aes(y=Sepal.Length, x = Species)) +
  geom_bar(stat = "summary", width = 0.8,
           position = position_nudge(x = 0.4))

(b) shift the position of the ticks on the x-axis with scale_x_continuous
ggplot(data = iris, aes(y=Sepal.Length, x = as.numeric(Species))) +
  geom_bar(stat = "summary", width = 0.8) +
  scale_x_continuous(breaks = c(0.6, 1.6, 2.6),
                     labels = levels(iris$Species))


text:
Q: How to check if an elasticsearch node runs? Sometimes I found one of my elasticsearch program on a node does not response (hanging) although its pid still exists.
Is there a way to detect this by using any API?
elasticsearch has _cluster/nodes and _cluster/_headth. But I assume the API goes to the master node. Maybe master nodes are busy and return the response of the APIs slowly, which may not mean the current node slow.
Is there a way to check the node status only on the current machine?


text:
Q: How does iTunes know what albums to associate with each album artwork file? I have recently been trying to systematically extract album artwork from my iTunes library, such that I can use them elsewhere.
I understand that all the album artwork is stored in the Album Artwork folder, inside iTunes-specific .itc2 files. I have researched and found that these files are simply wrappers for PNG, JPG, and RAW image data.
Which is fine - I can extract those images as I wish - however, I cannot determine how iTunes knows which .itc2 file belongs to each album. For playlist artwork, I have found that the second part of the file's name is equal to the Playlist Persistent ID found under the corresponding playlist in the iTunes Music Library.xml file. Yet it seems the same is not true for album artwork - there is nothing like an "Album Persistent ID" parameter.
So how does iTunes know which album each album artwork file belongs to?


text:
Q: Can I buy a horse for my follower? Can I buy a horse for my follower? I have my own horse, but I feel sorry for Lydia, and she lags behind me quite a bit.

A: No, not yet, but it is high on a list of mod requests.
For the PC at least, (if there will be modding for the console that will be a long wait)  the Creation Kit will be released in January, the console one has not yet been verified for a release date yet.  Already, people are getting ready to make a mod for this reason, but they lack the resources.  If you have a PC, check the Nexus in mid January.

A: Current mods that can allow you to buy or acquire horses for your followers to use:
Original / Legendary Edition (PC)
Mounted Followers

...this mod once installed lets your follower have and ride a horse that will spawn near your last ridden horse.
It works with stolen horses, quest horses, but of course works best with stabled horses.

Note:
1 - I suggest you to never mount the follower horse, it may result in the follower mounting yours and after you dismount you'd have to catch your horse that tries to go back to stables.
2 - You can fast travel but note that your follower may not be teleporting with you if you were mounted, IT IS NOT AN ISSUE tho your companion will come back after a while (specially if you transition to doors etc)
3 - Once their AI kicks in followers are rather slow (they walk) to catch their horse ( just go.. they will catch up ).
4 - The AI will not enter combat unless you dismount and so the normal behavior starts.
5 - If your follower is very close to you and you dismount, they may not dismount at first... but once you start moving they will.
6 - Follower horses are not owned by the player so they will show with Red name.. this is totally normal! they are not supposed to be mounted by you!
7 - If for some reason follower horses aren't showing up, mount up on your horse and then dismount.. in few seconds follower horses should show up.

Horses For Followers

Horses for Followers will make new horses available to buy at all the main stables Better Follower Improvements will enable your companion to ride them and follow you. To make followers mount their steeds, all you need to do is mount your own and they will follow suit. When combat ensues, they will dismount and engage in combat as normal. The horses are set to avoid combat if possible, unlike the vanilla player's horse. Now that you have two horses to pay for, you will appreciate their increased survivability.

The horses will be owned by the current Follower Faction or Player Faction, which means that even if you change followers, there is no need to buy a new horse for each one.

Horse Branding

Mark any horse or mount for followers to ride, mark them for yourself
so they are not stolen, stop them from going away when you dismount
and similar expanded control..

Horse Branding has been tested with TCG Extended Version and TCG +
Multifollowers combo. Meaning if you want to ride around with a dozen
followers use the said mod combo!!

With the Horse Branding mod, you can make your follower ride non-horse mounts (like Mammoths and Wolfs) with this mod: Like a Boss.

Special Edition (PC)
Convenient Horses

Convenient Horses for Skyrim Special Edition is... aiming
to overhaul the horse system in Skyrim. Unlike its predecessor, it has
been built from the ground up to radically change the way you interact
with and use horses...
Features

*

*Mounted harvesting of ingredients.

*Mounted interaction with people and corpses.

*Mounted combat horse charge.

*Horse stabling, naming and quick swapping.

*Horse encumbrance system and mobile storage. Horse dialogue interaction and fast dismount.

*Horse follow and combat behavior customization.

*Horse whistle and calling.

*Horse attribute training. Horse equipment crafting and discovery. Followers' horses and mounted combat.

Immersive Horses

Immersive Horses is a lightweight overhaul for the horses in Skyrim built on SKSE64 and SkyUI SE. The goal of Immersive Horses is to improve on nearly every aspect of Skyrim's horses while remaining as true as possible to the original game. Immersive Horses adds a range of new commands and related options for horses as well as an integrated ownership and follower system designed specifically for horses.

A: Sadly no. I don't see this being an official Bethesda/Obsidian-released DLC either. The PC version has a fairly large modding community, so there might be something in that avenue, but I don't know if it'll be high on the list of requests.
As for console commands in the PC version, there's no way to get a follower to ride a horse.


text:
Q: Override existing java annotation I am trying to create a customized Java annotation to override the default message of @SafeHtml . But failed.
Maybe my code is wrong.
@Documented
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@SafeHtml(message="Html coding text is not allowed")
public @interface MySafeHtml {
  @AliasFor(annotation = SafeHtml.class)
  String message() default "Html coding text is not allowed";
}


text:
Q: SQL Server Excel Worksheets Import I am working on an import script, the idea being to import multiple workbooks into one table. I have made progress, so I am able to import one workbook successfully into my table. What I want to do is create a query that will loop a folder read the file names and import the data into my database in Microsoft SQL Server Management Studio.
--Creating the TABLE--
CREATE TABLE BrewinDolphinHoldings
(
    recordID INT AUTO_NUMBER
    FUNDNAME VARCHAR(25),
    SEDOL VARCHAR(7),
    ISIN VARCHAR(11),
    NAME VARCHAR(20),
    WEIGHT INTEGER(3)
)

constraint[pk_recordID]PRIMARYKEY
(
    [recordID] ASC
)

INSERT INTO BrewinDolphinHoldings
VALUES
("HoldingsData', GB125451241, DavidsHoldings, 22)

--SELECTING THE SHEET--

SELECT/UPDATE? *
FROM OPENROWSET('Microsoft.JET.OLEDB.4.0',
                'Excel 8.0;Database=X:\CC\sql\DEMO\SpreadsheetName + '.xlsx',
                'SELECT * FROM [Sheet1$]') AS HoldingsData

So essentially my question is, I want to create a loop a loop that will read the file name in a directory, and the import will read that name every time it loops and import the relevant spreadsheets? so,for example:
DECLARE SpreadsheetName as STRING
DECLARE FileExtension as '.xlsx'

FOR EACH ITEM IN DIRECTORY
X=1
Y=MAX
FILENAME THAT LOOP READS = SpreadsheetName
SELECT * FROM
OPENROWSET('Microsoft.JET.OLEDB.12.0',
'Excel 8.0;Database=X:\CC\sql\DEMO\SpreadsheetName + fileExtension.xls
END LOOP

So, I'm thinking maybe something like this? Although I don't know if the loop will overwrite my database? maybe instead of UPDATE I should use INSERT?
I don't want to use SSIS, preferably a query, although if anyone can recommend anything I could look into, or, help me with this loop It would greatly help
I'm open to new ideas from you guys, so if anyone can try and fix my code, or give me a few examples of imports for multiple excel sheets, would be greatly appreciated!
I'm new to SQL Server, I do have some previous programming experience!
Thanks!

A: You can use bcp to do what you are talking about to import any type of delimited text file, such as csv or text tab delimited. If it is possible generate/save the spreadsheets as csv and use this method. See these links.
Import Multiple CSV Files to SQL Server from a Folder
http://www.databasejournal.com/features/mssql/article.php/3325701/Import-multiple-Files-to-SQL-Server-using-T-SQL.htm
If it has to be excel, then you can't use bcp, but these should still help you with the logic for the loops on the file folders. I have never used the excel openrowset before, but if you have it working like you said, it should be able to insert in just the same. You can still use the xp_cmdshell/xp_dirtree to look at the  files and generate the path even though you can't import it with bcp.
How to list files inside a folder with SQL Server
I would then say it would be easiest to do a insert from a select statement from the openrowset to put it into the table.
http://www.w3schools.com/sql/sql_insert_into_select.asp
Make sure xp_cmdshell is enabled on your sql server instance as well.
https://msdn.microsoft.com/en-us/library/ms190693(v=sql.110).aspx


text:
Q: I can't access the text in the span using BeautifulSoup Hi Everyone receive error msg when executing this code :
from bs4 import BeautifulSoup
import requests
import html.parser
from requests_html import HTMLSession

session = HTMLSession()
response = session.get("https://www.imdb.com/chart/boxoffice/?ref_=nv_ch_cht")
soup = BeautifulSoup(response.content, 'html.parser')
tables = soup.find_all("tr")

for table in tables:
    movie_name = table.find("span", class_ = "secondaryInfo")
    print(movie_name)

output:

movie_name = table.find("span", class_ = "secondaryInfo").text
AttributeError: 'NoneType' object has no attribute 'text'

A: You selected for the first row which is the header and doesn't have that class as it doesn't list the prices. An alternative way is to simply exclude the header with a css selector of nth-child(n+2). You also only need requests.
from bs4 import BeautifulSoup
import requests

response = requests.get("https://www.imdb.com/chart/boxoffice/?ref_=nv_ch_cht")
soup = BeautifulSoup(response.content, 'html.parser')

for row in soup.select('tr:nth-child(n+2)'):
    movie_name = row.find("span", class_ = "secondaryInfo")
    print(movie_name.text)

A: Just use the SelectorGadget Chrome extension to grab CSS selector by clicking on the desired element in your browser without inventing anything superfluous. However, it's not working perfectly if the HTML structure is terrible.
You're looking for this:
for result in soup.select(".titleColumn a"):
    movie_name = result.text

Also, there's no need in using HTMLSession IF you don't want to persist certain parameters across requests to the same host (website).

Code and example in the online IDE:
from bs4 import BeautifulSoup
import requests

# user-agent is used to act as a real user visit
# this could reduce the chance (a little bit) of being blocked by a website
# and prevent from IP limit block or permanent ban
headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}

response = requests.get("https://www.imdb.com/chart/boxoffice/?ref_=nv_ch_cht", headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

for result in soup.select(".titleColumn a"):
    movie_name = result.text
    print(movie_name)

# output
'''
Eternals
Dune: Part One
No Time to Die
Venom: Let There Be Carnage
Ron's Gone Wrong
The French Dispatch
Halloween Kills
Spencer
Antlers
Last Night in Soho
'''

P.S. There's a dedicated web scraping blog of mine. If you need to parse search engines, have a try using SerpApi.

Disclaimer, I work for SerpApi.


text:
Q: React - How to get the value form Materialize's Switches? I'm using switches component (designed by Materialize) inside React components, and I'd like to know, how could I get the value when the user has changed the switch (on/of).

    Any
    <input type="checkbox" onChange={() => alert('changed')}/>

    All

I tried to set a onChange event to verify if I can, at least, get when it's triggered.

A: As a start, I would recommend using react-materialize, which has been written into components for react here https://react-materialize.github.io/#/forms.
I guess the problem is that onChange works only for JSX, and from your code it looks like you are using plain HTML?
I have added your onChange event into my JSX and it works as expected.
If you used react-materialize, your code would look something like this:
<Input name='on' type='switch' onLabel='Any' offLabel='All' onChange={() => alert('changed')}/>


text:
Q: unshift + file.join in ruby $:.unshift File.join(File.dirname(__FILE__),\
'vendor','addressable-2.1.0','lib','addressable','uri')

Does the code above access a file that has this path:
'vendor/addressable-2.1.0/lib/addressable/uri'

I'm trying to vendor the addressable gem into a Sinatra app to deploy it to my hosting provider but I keep receiving:
"no such file to load -- addressable/uri"

after putting the 'unshift' line in config.ru.

A: The above code adds the path "vendor/addressable-2.1.0/lib/addressable/uri" to the global variable used for looking up external files. The path will be relative to the directory that houses the file this code is placed in. So were {dir} is the directory config.ru is placed, it will add {dir}/vendor/addressable-2.1.0/lib/addressable/uri to the lookup path for includes.

A: What the line does is it puts the path 'vendor/addressable-2.1.0/lib/addressable/uri' (relative to the directory your ruby script is in) into the load path, which is the list of directories ruby looks through when looking for files you require.
By itself the line won't try to access any files.


text:
Q: How to implement Mozilla DeepSpeech into PHP web app to convert Speech-to-text? I have a PHP web application and am looking for an open source, high-accuracy speech-to-text recognition implementation that will take voice commands to open web pages from users. Examples: "Make Sales" (this will open Create Sales PHP page), "Make Purchase order", "Open END-OF-DAY reports", etc.
My Question :
I want to know if we can we use Mozilla DeepSpeech to take .wav audio from a Firefox browser and return speech to text. If yes, what will be the flow from recording voice from Firefox using mic TO convert text using the DeepSpeech engine?
How to make wakeup/launch call similar to OK-GOOGLE that will be ready to listen for commands?

A: You can achieve that by creating a server and sending requests back and forth using assinchronious requests/AJAX or web sockets.
You can find Server installation instructions using the link below:
https://pypi.org/project/deepspeech-server/
After you have installed the server you can start making requests from any browser that supports "WebRTC API: getUserMedia()". Generate audio Blob data and send it in base64 format to the backend server.
On the backend, save the blob to a temporary audio file:
$encodedData = base64_decode($data);

// write the data out to the file
$fp = fopen($full_file_path, 'wb');
      fwrite($fp, $encodedData);
      fclose($fp);

Then convert audio file to text by making CURL request to your own Mozzila DeepSpeech Node.js server:
curl -X POST --data-binary @testfile.wav http://localhost:8080/stt

Create methods on your backend to loop through generated text and try to identify keywords/commands. If triggered send it back to the front end. Perhaps you just want to grant users ability to write long messages using their speech? - Return the whole text back - every time. You do however still want to "listen" to the keywords, in order to give users ability to set punctuation, start and finish writing.
Happy coding everyone ;)

A: Please read:
https://github.com/mdn/web-speech-api/tree/master/speech-color-changer
The translation from speech to text is done in the browser, on the client side.
When the text is generated, it can be sent to the php server, using jquery.


text:
Q: Update column based on duplicate columns I have 2 tables:
account
+----+---------------------+
| Id |        Email        |
+----+---------------------+
|  1 | "test@example.com"  |
|  2 | "test2@example.com" |
|  3 | "test3@example.com" |
|  4 | "test@example.com"  |
+----+---------------------+

character
+----+-----------+
| Id | AccountId |
+----+-----------+
|  1 |         1 |
|  2 |         1 |
|  3 |         2 |
|  4 |         3 |
|  5 |         4 |
+----+-----------+

character.AccountId is a FK to account.Id. Both Id columns are PK's to their respective tables.
I need to update the character table such that the new AccountId matches a row in account with the lowest account's Id but with the same Email as the currently set AccountId.
For example, in the mock data presented above all accounts have unique emails except account Id 1 and 4, they both share test@example.com as email.
This means that after the update, the rows in the character table should stay the same except for the row with Id = 5, this row has an AccountId = 4 and this account shares an email with an account that has a lower account Id, namely Id 1. So the result output should be :
+----+-----------+
| Id | AccountId |
+----+-----------+
|  1 |         1 |
|  2 |         1 |
|  3 |         2 |
|  4 |         3 |
|  5 |         1 |
+----+-----------+

After the operation.
I've got this to work with a TRIGGER BEFORE INSERT on character to check if there are lower accountIds but can't get this to work with a simple UPDATE:
UPDATE `character` SET `AccountId` = (SELECT MIN(Id) FROM `account` WHERE ?);

I've thought of maybe making a temporary table to store the account Id and the email with a GROUP BY email but this also fails. It being MySQL I can't use MERGE either.

A: You can use a window function to get the minimum id per email.  Then just join that in:
UPDATE character c JOIN
       (SELECT a.*,
               MIN(id) OVER (PARTITION BY a.email) as min_id
        FROM account a
       ) a
       ON c.accountId = a.id
    SET c.accountId = a.min_id
    WHERE c.accountId <> a.min_id;

A: This is fairly straightforward without window functions, too; you want to find accounts with the same email and lower ids (the a2 join) and make sure you've got the lowest (the a3 join):
update `character` c
join account a on a.id=c.account_id
join account a2 on a2.email=a.email and a2.id < a.id
left join account a3 on a3.email=a2.email and a3.id < a2.id
set c.account_id=a2.id
where a3.id is null;

(As usual, the left join ... where ... is null could be replaced with a where not exists (...), if you prefer the query to show the intent more clearly instead of the probable query plan more clearly.)
fiddle


text:
Q: Javascript not working on some (not all) pages built on a Django backend, despite files being found by the site I am building a site with Django. I recently have been confronted with an odd issue. The javascript is working on some pages and not others. In fact the one page that does work looks and functions almost identically to one that doesn't.
my html for the page that doesn't work looks like:
 <!DOCTYPE html>

    <title>MetaScape</title>
    <meta name = "viewport" content="width=device-width, initial-scale=1.0">
    {% load static from staticfiles %}
    <link href="{% static 'bootstrap/css/bootstrap.min.css' %}"  rel="stylesheet" media="screen">
    <link href="{% static 'base.css' %}" rel="stylesheet" media="screen">
    <link href="{% static 'font-awesome/css/font-awesome.css' %}" rel="stylesheet" media="screen">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.6.0/bootstrap-table.min.css">
    <link href="{% static 'tipsy/src/stylesheets/tipsy.css' %}" rel="stylesheet" media="screen" >

Home

IAV

About

Contact

              Metascape

              advancing omics analysis

            Step1:

            Data Processing:
            Upload Excel file and Download Augmented File

        <form action= "{% url 'new_page' %}"  method="post" enctype="multipart/form-data">

            {% load widget_tweaks %}
            {{docform.docfile|attr:"class:filestyle"|attr:"data-classButton:btn btn-primary"|attr:'data-input:false'|attr:'data-classIcon:icon-plus'|attr:'data-buttonText:Upload Data'}}
            {% csrf_token %}

{{ docform.non_field_errors }}

              {{ docform.docfile.errors }}

            {{docform.is_multiple}}
            Multi Gene List

<input id = "process_button" class="btn btn-primary" type="submit" value="Process"/>

          {% block down %}
          {% endblock %}
        </form>

    {% block preview_data %}
    {% endblock %}

            Step2:

            GO enrichment:
            Upload Excel file and Download Augmented File

        <form action= "{%block go_action %}{%endblock%}"  method="post" enctype="multipart/form-data">

Min Overlay

            {{goform.overlap}}

P Value Cutoff

            {{goform.pvalue}}

Min Enrichment

            {{goform.min_enrichment}}

                  Select Enrichment Database

                    {{goform.select_DB}}

          {% if document %}

          {% endif %}

            {{goform.docfile}}
            {% csrf_token %}

{{ goform.non_field_errors }}

              {{ goform.docfile.errors }}

<input id = "enrich_button" class="btn btn-primary" type="submit" value="Enrich"/>

        </form>

the javascript file, that can even be found by clicking the link found by chrome is:
var main = function(){

  $("html, body").animate({ scrollTop: $('.scroll_d2').offset().top }, 2500);

  $('#flu_protein').tipsy({gravity: 'w'});

  $(".dropdown dt a").on('click', function () {
      $(".dropdown dd ul").slideToggle('fast');
  });

  $(".dropdown dd ul li a").on('click', function () {
      $(".dropdown dd ul").hide();
  });

  function getSelectedValue(id) {
       return $("#" + id).find("dt a span.value").html();
  }

  $(document).bind('click', function (e) {
      var $clicked = $(e.target);
      if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
  });

  $('.mutliSelect input[type="checkbox"]').on('click', function () {

      var title = $(this).closest('.mutliSelect').find('input[type="checkbox"]').val(),
          title = $(this).val() + ",";

      if ($(this).is(':checked')) {
          var html = '' + title + '';
          $('.multiSel').append(html);
          $(".hida").hide();
      }
      else {
          $('span[title="' + title + '"]').remove();
          var ret = $(".hida");
          $('.dropdown dt a').append(ret);

      }
  });

  $('li').click(function(){
    var current = $('li.active');
    var next = $(this);
    current.removeClass('active');
    next.addClass('active');
  });

};
$(document).ready(main)

A very similar page that does work has the HTML of:
<!DOCTYPE html>

    <title>MetaScape</title>
    <meta name = "viewport" content="width=device-width, initial-scale=1.0">
    {% load static from staticfiles %}
    <link href="{% static 'bootstrap/css/bootstrap.min.css' %}"  rel="stylesheet" media="screen">
    <link href="{% static 'base.css' %}" rel="stylesheet" media="screen">
    <link href="{% static 'font-awesome/css/font-awesome.css' %}" rel="stylesheet" media="screen">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.6.0/bootstrap-table.min.css">
    <link href="{% static 'tipsy/src/stylesheets/tipsy.css' %}" rel="stylesheet" media="screen" >

Home

IAV

About

Contact

              Metascape

              advancing omics analysis

            Step1:

            Data Processing:
            Upload Excel file and Download Augmented File

        <form action= "{% url 'new_page' %}"  method="post" enctype="multipart/form-data">

            {% load widget_tweaks %}
            {{docform.docfile|attr:"class:filestyle"|attr:"data-classButton:btn btn-primary"|attr:'data-input:false'|attr:'data-classIcon:icon-plus'|attr:'data-buttonText:Upload Data'}}
            {% csrf_token %}
            {% csrf_token %}

{{ docform.non_field_errors }}

              {{ docform.docfile.errors }}

            {{docform.is_multiple}}
            Multi Gene List

<input class="btn btn-primary" type="submit" value="Process"/>

        </form>

            Step2:

            GO enrichment:
            Upload Excel file and Download Augmented File

        <form action= "{% block go_action%}{%endblock%}"  method="post" enctype="multipart/form-data">

Min Overlay

            {{goform.overlap}}

P Value Cutoff

            {{goform.pvalue}}

Min Enrichment

            {{goform.min_enrichment}}

                  Select Enrichment Database

                          {{goform.select_DB}}

            {% csrf_token %}

{{ goform.non_field_errors }}

              {{ goform.docfile.errors }}

            {% if img %}

<input class="btn btn-primary disable_enrich enrich_button" type="submit" value="Enrich"/>

            {% else %}

<input class="btn btn-primary enrich_button" type="submit" value="Enrich"/>

            {% endif %}

        </form>

      {% block go_down %}
      {% endblock %}

and the javascript for this page looks like:
var main = function(){

  $("html, body").animate({ scrollTop: $('.scroll_d1').offset().top }, 2500);

  $('#flu_protein').tipsy({gravity: 'w'});

  $(".dropdown dt a").on('click', function () {
      $(".dropdown dd ul").slideToggle('fast');
  });

  $(".dropdown dd ul li a").on('click', function () {
      $(".dropdown dd ul").hide();
  });

  function getSelectedValue(id) {
       return $("#" + id).find("dt a span.value").html();
  }

  $(document).bind('click', function (e) {
      var $clicked = $(e.target);
      if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
  });

  $('.mutliSelect input[type="checkbox"]').on('click', function () {

      var title = $(this).closest('.mutliSelect').find('input[type="checkbox"]').val(),
          title = $(this).val() + ",";

      if ($(this).is(':checked')) {
          var html = '' + title + '';
          $('.multiSel').append(html);
          $(".hida").hide();
      }
      else {
          $('span[title="' + title + '"]').remove();
          var ret = $(".hida");
          $('.dropdown dt a').append(ret);

      }
  });

  $('li').click(function(){
    var current = $('li.active');
    var next = $(this);
    current.removeClass('active');
    next.addClass('active');
  });

};
$(document).ready(main)

I had even made the two javascript files as similar as possible to see if the problem was the javscript or not.


text:
Q: RecyclerView giving errors Hi i am new to android project so i am trying to use recycler view. but it is not working. i keep getting errors @ this line " RecyclerAdapter adapter = new RecyclerAdapter(this, getData());" it says RecyclerAdapter (android.content.context, List) in RecyclerAdapter cannot be applied to my package class please help
statement.java

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

import nnnnn.R;
import nnnnnn.RecyclerAdapter;
import nnnnnnnnnnnnn.Landscape;

public class Statements extends Fragment {
    Toolbar toolbar;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.statements,container,false);

        toolbar = (Toolbar) v.findViewById(R.id.toolbar);
        toolbar.setTitle("Statements");
        toolbar.inflateMenu(R.menu.menu_main);

        setUpRecyclerView();
        return v;}

    private void setUpRecyclerView() {

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        RecyclerAdapter adapter = new RecyclerAdapter(this.getActivity(),Landscape.getData());
        recyclerView.setAdapter(adapter);

       final LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(this.getActivity()); // (Context context, int spanCount)
        mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLinearLayoutManagerVertical);

        recyclerView.setItemAnimator(new DefaultItemAnimator()); // Even if we dont use it then also our items shows default animation. #Check Docs
    }

}

RecyclerAdapter code is below
 RecyclerAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import xx.xx.xx.xx.xx.R;
import xx.xx.xx.xx.model.Landscape;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {

    private static final String TAG = RecyclerAdapter.class.getSimpleName();

    private List<Landscape> mDataList;
    private LayoutInflater inflater;

    public RecyclerAdapter(Context context, List<Landscape> data) {
        this.mDataList = data;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.i(TAG, "onCreateViewHolder");

        View view = inflater.inflate(R.layout.statementlist, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Log.i(TAG, "onBindViewHolder" + position);

        Landscape current = mDataList.get(position);
        holder.setData(current, position);
        holder.setListeners();
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    public void removeItem(int position) {
        mDataList.remove(position);
        notifyItemRemoved(position);
//      notifyItemRangeChanged(position, mDataList.size());
//      notifyDataSetChanged();
    }

    public void addItem(int position, Landscape landscape) {
        mDataList.add(position, landscape);
        notifyItemInserted(position);
//      notifyItemRangeChanged(position, mDataList.size());
//      notifyDataSetChanged();
    }

    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView title;
        ImageView imgThumb, imgDelete, imgAdd;
        int position;
        Landscape current;

        public MyViewHolder(View itemView) {
            super(itemView);
            title       = (TextView)  itemView.findViewById(R.id.tvTitle);
            imgThumb    = (ImageView) itemView.findViewById(R.id.img_row);
            imgDelete   = (ImageView) itemView.findViewById(R.id.img_row_delete);
            imgAdd      = (ImageView) itemView.findViewById(R.id.img_row_add);
        }

        public void setData(Landscape current, int position) {
            this.title.setText(current.getTitle());
            imgThumb.setImageResource(current.getImageID());
            this.position = position;
            this.current = current;
        }

        public void setListeners() {
            imgDelete.setOnClickListener(MyViewHolder.this);
            imgAdd.setOnClickListener(MyViewHolder.this);
            imgThumb.setOnClickListener(MyViewHolder.this);
        }

        @Override
        public void onClick(View v) {
//          Log.i("onClick before operation", position + " " + mDataList.size());
            switch (v.getId()) {
                case R.id.img_row_delete:
                    removeItem(position);
                    break;

                case R.id.img_row_add:
                    addItem(position, current);
                    break;
            }
//          Log.i("onClick after operation", mDataList.size() + " \n\n" + mDataList.toString());
        }
    }
}

A: You're passing in "this" for the first argument to RecyclerAdapter.  "this" being a Fragment class.  The Fragment class does not extend from Context, so it cannot be used as such.
Try "this.getActivity()".  This may result in null, so ideally put this within the Fragment subclass's "onActivityCreated" method (instead of the "onCreateView" method)

A: You need to override OnActivitycreated in order to call getActivity. Call setUpRecyclerView in OnActivitycreated and add getActivity. before findViewById and it will work


text:
Q: How to share a folder (directory) with an Android device? Step by step, how does one share a folder (directory) that is on a Windows 7 system with an Android device?
I want a true networking share (over Wifi), not an FTP connection.
I would prefer not to install any software on the Windows 7 system, and to use ES File Explorer on the Android device, but am open to all solutions.
BTW, I think I am doing everything correctly, but I must be missing a step.  When I get to the "Connecting to" dialog box in ES File Explorer, no matter what I enter, it does not work.  I've even tried guest/guest to no avail.

A: Make a Windows Home Network and then use 3rd party app on the Android to access the Network via your router. Make sure to Enable file sharing on your windows 7 Network.
Try these links
http://www.howtogeek.com/191378/how-to-access-shared-windows-folders-on-android-ipad-and-iphone/
http://www.guidingtech.com/10885/access-shared-windows-folders-android-wifi/
I have done what you describe before, but my phone is so slow and I deleted that network. But I know I used one of these ways to do it.


text:
Q: Add custom SOAP headers to Service Reference in Windows Phone 7 in my windows phone 7 app i added a Web Service with "Add service reference". The webservice i want to use excepts some custom soap headers.
How can i add custom headers to to this Service reference?

A: The WCF Client API is limited on WP7 and I had to go the manual way: Create the HttpWebRequest by hand, set my headers and do all the SOAP stuff on my own.

A: Custom SOAP headers can be added using the OperationContextScope as follows:
var client = new MySerivceClient();
using (OperationContextScope contextScope = new OperationContextScope(client.InnerChannel))
{
    OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("MyHeader",
                            "", new MyHeader()
                                         {
                                             Value = "ABCDEFG"
                                          }));
    client.DoSomeAction();
}

See http://cisforcoder.wordpress.com/2010/12/01/how-to-implement-basic-http-authentication-in-wcf-on-windows-phone-7/ for an example.


text:
Q: Naming a default constraint I'm trying to create a default constraint here, but the system is generating a weird name for it. If I want to name it df_MY_TABLE_GUID or something, how could I specify that name be used?
ALTER TABLE MY_TABLE
    ADD MY_GUID uniqueidentifier NOT NULL
        CONSTRAINT uq_MY_TABLE_GUID UNIQUE (MY_TABLE_GUID)
        DEFAULT NEWID() WITH VALUES

A: Just specify the constraint name with the full syntax, like the UNIQUE in your example:
ALTER TABLE MY_TABLE ADD MY_GUID UNIQUEIDENTIFIER NOT NULL
    CONSTRAINT uq_MY_TABLE_GUID UNIQUE (MY_TABLE_GUID)
    CONSTRAINT df_MY_TABLE_GUID DEFAULT NEWID() WITH VALUES ;

As a matter of routine, I always prefer and encourage to always name every single constraint I create, for the sake of easy reference latter on.


text:
Q: How to share object tree with process fork? I don't have much experience with multithreading, and I'm trying to get something like the below working:
from multiprocessing import Process

class Node:

    def __init__(self):
        self.children = {}

class Test(Process):

    def __init__(self, tree):
        super().__init__()
        self.tree = tree

    def run(self):
        # infinite loop which does stuff to the tree
        self.tree.children[1] = Node()
        self.tree.children[2] = Node()

x = Node()
t = Test(x)
t.start()
print(x.children)  # random access to tree

I realize this shouldn't (and doesn't) work for a variety of very sensible reasons, but I'm not sure how to get it to work.  Referring to the documentation, it seems that I need to do something with Managers and Proxies, but I honestly have no idea where to start, or whether that is actually what I'm looking for.  Could someone provide an example of the above that works?

A: It seems to me that what you want is actual multithreading, rather than multiprocessing. With threads rather than processes, you can do precisely that, since threads run in the same process, sharing all memory and therefore data with each other.

A: multiprocessing has limited support for implicitly shared objects, which can even share lists and dicts.
In general, multiprocessing is shared-nothing (after the initial fork) and relies on explicit communication between the processes. This adds overhead (how much really depends on the kind of interaction between the processes), but neatly avoids a lot of the pitfalls of multithreaded programming. The high-level building blocks of multiprocessing favor master/slave models (esp. the Pool class), with masters handing out work items, and slaves operating on them, returning results.
Keeping state in sync across several processes may, depending how often they change, incur a prohibitive overhead.
TL;DR: It can be done, but probably shouldn't.
import time, multiprocessing

class Test(multiprocessing.Process):
    def __init__(self, manager):
        super().__init__()
        self.quit = manager.Event()
        self.dict = manager.dict()

    def stop(self):
        self.quit.set()
        self.join()

    def run(self):
        self.dict['item'] = 0
        while not self.quit.is_set():
            time.sleep(1)
            self.dict['item'] += 1

m = multiprocessing.Manager()
t = Test(m)
t.start()
for x in range(10):
    time.sleep(1.2)
    print(t.dict)
t.stop()

The multiprocessing examples show how to create proxies for more complicated objects, which should allow you to implement the tree structure in your question.


text:
Q: Prevent Visual Studio from opening a new Firefox window when pressing F1? I have Visual Studio 2013 (tested with Update 1, 2 and 3) installed on two completely seperate machines, one is Windows 7 SP1 and one is Windows 8.1. Both are running the latest version of Firefox and Firefox is set to be the default browser. The Firefox setting "Open tab instead of new window" is checked.
Almost every time I want to open the API help pages on MSDN by pressing F1 in the code, a new Firefox window is opened. This happens on both machines. But it only happens with Firefox, when IE is the default browser it correctly opens a new tab. And this is a new problem in Visual Studio 2013, I didn't have this problem with Visual Studio 2010.
Interestingly, this is not 100% consistent. Rarely, I'd say about 5% of the time, it correctly opens a new tab instead of a new window. And I have found one command that always correctly opens a tab, that is the Help - View Help command in the main menu bar (not very helpful).
Searching the internet revealed this Microsoft Connect issue entry which says that it was also a problem in Visual Studio 2012, but was apparently fixed in the latest build in May 2013. While I've never used Visual Studio 2012 myself, this date was before Visual Studio 2013 was released, and was far before Update 1 for it was released. Did they really forget to merge the fix to Visual Studio 2013?
Anyway, my question is if everyone experiences this problem and if not, if anyone knows a way to fix it.
Update with workaround
I've no idea how or why this works, but I've found a workaround. As long as the .NET Reflector (I'm using version 8.3.3.115) is running, the F1 key works correctly. This is 100% reproduceable and works on Windows 7 and Windows 8.1.
Can someone please explain that to me?
I'll leave this question open until a real answer is found.
Update 2
Visual Studio 2015 shows the same problem.

A: The problem is that Visual Studio launches Firefox with incorrect parameters. The correct settings can be found in the registry (HKEY_CLASSES_ROOT\FirefoxURL\shell\open\command). Now, to fix this, simply add Firefox as a web browser (with the correct startup parameters: -osint -url "%1") and assign it to the default.

A: I don't know when this was fixed, but it doesn't happen with Visual Studio 2017 on Windows 10.


text:
Q: FlutterFire Storage Put error : LOADING ERROR: Expected a value of type 'File', but got one of type 'File$' I am developing a WebApp in Flutter and attempting to load a picked file from my computer to Firebase Storage. Using the FlutterFire Firebase Storage plugin and instructions.
There seems to be an issue with the file. Though all are defined as type File in my code. I receive the error above. And am not able to use the Put command. I am noticing also that there seems to be a problem between Dart.io File type and Dart.html File type. That is maybe causing this.
This is the first time I have tried this, and don't seem to be able to solve the issue, so would appreciate some help. Thanks so much.
Here is my upload code:
Future<void> _uploadMedia(File file) async {
_onLoading(true);
try {
  await fbs.FirebaseStorage.instance
      .ref('uploads/file-to-upload.png')
      .putFile(file);
} catch (e) {
  // e.g, e.code == 'canceled'
}

And the code to select the file from the computer:
uploadMedia({required Function(File file) onSelected}) async {

var uploadInput = FileUploadInputElement()..accept = '*/*';
uploadInput.click();

uploadInput.onChange.listen(
  (changeEvent) {
    final file = uploadInput.files?.first;
    final reader = FileReader();

    reader.readAsDataUrl(file!);

    reader.onLoadEnd.listen(

    (loadEndEvent) async {
      onSelected(file);
    },
  );
 },
 );
 }

A: I'll take your idea and suggest a possible solution.

I am noticing also that there seems to be a problem between Dart.io
File type and Dart.html File type.

Try putting "as *name*;" at the end of the package import line and then using the word "io.YourType" when you need to declare something. Example:
import 'dart:async';
import 'my_library.dart' as myLib;

void main() {
  Stream stream = new Stream.fromIterable([1, 2]); // from async
  myLib.Stream myCustomStream = new myLib.Stream(); // from your library
}

Your situation: io.File


text:
Q: How can I call a base class's method via reflection?
Possible Duplicate:
Use reflection to invoke an overridden base method

Normally I can call my base class from within an overridden method like this:
public override void Foo(Bar b)
{
    base.Foo(b);
}

How can I make this same call with reflection?
Edit: to explain a bit, I'm trying to use AOP to guard my library's entry points from uninitialized operation (in my case there is no "initialize" call prior to the library's usage).  So the relevant calls will technically end up inside the class (by virtue of the AOP), but the pre-compiled code will be written in a separate class.  In other words, I want the following advice applied to all of my entry points:
if (!initialized)
    return base.<method>(<arguments>);

I suppose the IL trick shown in Use reflection to invoke an overridden base method will work for me - I was just hoping there was something cleaner in my case since it feels more legitimate.

A: EDIT: OK, so a bit of clarification; you're not trying to call the base class's implementation from outside either class. Instead, from within the overridden class, you want to reflectively call the parent method's implementation.
... Why? Your object statically knows what it is, and therefore statically knows what its base class is. You can't have two base classes, and you can't dynamically "assign" a base class to a pre-existing child class.
To answer your question, you can't. Any attempt to reflectively call "Foo" using the current instance will infinitely recurse, because the invocation of a MethodInfo makes the method call as if it were coming from outside ('cause it is), and so the runtime will obey inheritance/overriding behaviors. You would have to use the IL hack from the related question.


text:
Q: jquery apply context menu on all children I am using a jquery context menu plugin (http://www.trendskitchens.co.nz/jquery/contextmenu/) which works fine but I want to work for all children of a selector currently I have the below but it only applies to divs with class area and I need it to apply on div's with class area and all its children.
$('#container-area .area').contextMenu()

Any ideas on wildcard jquery selectors tried * with no luck
Lee

A: This should work, using .andSelf() (documentation):
$('#container-area .area').children("div").andSelf().contextMenu();

A: $('#container-area .area').contextMenu().find('*').contextMenu()


text:
Q: What is the positive real root of the equation $x^4-x-1=0$? I tried to solve the question on the graph and got two roots also I used Newton Raphson rule but a general proof is required. Any kind suggestions will be appreciated.
Also the root = √√(1+√√(1+√√(1+√√(1+... hence when I solved this on my calculator I got the root but I don't know whether there is a closed form for it or not

A: According to wolfram alpha, exact form of this solutions are

The former is positive solution.


text:
Q: How to get the geographic location using IP Address in asp.net mvc I know that this code:
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ipAddress))
        {
            ipAddress = Request.ServerVariables["REMOTE_ADDR"];
        }

will give me the IP Address of the user but I don't know how to get the location of the user
I want to know the location and related information on basis of IP Address.

A: This should help you - http://freegeoip.net/
freegeoip.net is a public REST API for searching geolocation of IP addresses and host names.
Send HTTP GET requests to: freegeoip.net/{format}/{ip_or_hostname}.  The API supports both HTTP and HTTPS and Supported formats are csv, xml or json.

A: Model to bind the user location details
public class IpInfo
{
    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region_name")]
    public string Region { get; set; }

    [JsonProperty("country_name")]
    public string Country { get; set; }

    [JsonProperty("time_zone")]
    public string TimeZone { get; set; }

    [JsonProperty("longitude")]
    public string Longitude { get; set; }

    [JsonProperty("latitude")]
    public string Latitude { get; set; }
}

Function
private  IpInfo GetUserLocationDetailsyByIp(string ip)
    {
        var ipInfo = new IpInfo();
        try
        {
            var info = new WebClient().DownloadString("http://freegeoip.net/json/" + ip);
            ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
        }
        catch (Exception ex)
        {
            //Exception Handling
        }

        return ipInfo;
    }

Calling function with IP value
var ipDetails = GetUserCountryByIp("8.8.8.8"); //IP value

A: This answer for people is searching in 2022 :).
You can use ip3country-dotnet. It is small library <500KB. This library is using ip2location the lite version, it is totally free!.
Way of usage:
Install IP3Country, then write this code
// Lookup using ip4 str
var country = CountryLookup.LookupIPStr("123.45.67.8"); // => 'KR'

// Lookup using numeric ip
country = CountryLookup.LookupIPNumber(2066563848); // => 'KR'


text:
Q: UITableViewCell layout with dynamic subviews I have a twitter like UITableViewCell that displays the user image, user name, tweet and buttons for reply, retweet and favourite. I went through a couple of sites that teach how to autolayout tables in ios. This one made sense Table Layout Blog, but I cannot get it to work. I know I need to work with two methods heightForRowAtIndexPath and cellForRowAtIndexPath. In addition I have a configureCell:cell that fills out the cell with the data. Here is my implementation based on the blog.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TweetCell";
    TweetCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    [self configureCell:cell forIndexPath:indexPath isForOffscreenUse:NO];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.prototypeCell)
    {
        self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"TweetCell"];
    }

    [self configureCell:self.prototypeCell forIndexPath:indexPath isForOffscreenUse:YES];

    [self.prototypeCell layoutIfNeeded];
    CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    NSLog(@"%f",size.height);
    return size.height;
}

-(void) configureCell:(TweetCell*)cell forIndexPath:(NSIndexPath*)indexPath isForOffscreenUse:(BOOL)isForOffscreenUse{
    Tweet *tweet = self.tweets[indexPath.row];
    cell.tweetText.text = tweet.text;
    NSURL *url = [NSURL URLWithString:[tweet imageURLFromTweet]];
    [cell.tweetImageView setImageWithURL:url];
    cell.tweetImageView.contentMode = UIViewContentModeScaleAspectFit;
    cell.tweetUserName.text = [tweet usernameFromTweet];
}

The problem is that heightForRowAtIndexPath size.height is 0. Can somebody please help out? Thanks.

A: At heightForRowAtIndexPath the cell will not be created.  You need to measure the height of your content independent of the cell.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Tweet *tweet = self.tweets[indexPath.row];
    CGFloat height = [tweet.text sizeWithFont:[Your Font] constrainedToSize:[CGSizeMake(Your Cell Width, CGFLOAT_MAX)];
    NSURL *url = [NSURL URLWithString:[tweet imageURLFromTweet]];
    UIImage *image = [Get your image and cache it so you can the set it during configureCell];
    height += image.size.height;

    return height;
}


text:
Q: why does memory address change in Ubuntu and not in Redhat I have this program:
double t;
main() {
}

On Ubuntu, I run:
% gdb a.out
(gdb) p &t
$1 = (double *) 0x4010 <t>
(gdb) run
Starting program: /home/phan/a.out
[Inferior 1 (process 95930) exited normally]
(gdb) p &t
$2 = (double *) 0x555555558010 <t>

Why did the address change from 0x4010 to 0x555555558010. Is there someway to prevent this?
On Redhat, it doesn't do that:
% gdb a.out
(gdb) p &t
$1 = (double *) 0x601038 <t>
(gdb) r
Starting program: /home/phan/a.out
[Inferior 1 (process 23337) exited normally]
(gdb) p &t
$2 = (double *) 0x601038 <t>

BTW, this only occurs in Ubuntu 18.04.  In Ubuntu 16.04, it works exactly as Redhat, for example the address is the same before and after.

A: You are presumably seeing pre and post-relocation addresses for the .bss segment.
You can avoid this by disabling position independent executables, thus making gcc choose the final address of the .bss register up front:
gcc -no-pie foo.c

-static would have the effect.
I don't know why there'd be a difference between Ubuntu and Redhat though.


text:
Q: Installing armitage in Ubuntu I'm trying to install armitage by following this procedure (video 6:51). Once I execute sudo ./armitage, I got the message :
The Parallel GC can not be combined with -XX:ParallelGCThreads=0.

What do I have to do to finalize the installation of this software?

A: This is a bug in Oracle Java 1.8u131 as explained in this blog post:

This recent update to Oracle's Java introduces a change that breaks the -XX:+AggressiveHeap command line option [...] The Java team is aware of this bug and it has a priority level 2. This is the level reserved for crashes, losses of data, and severe memory leaks. They're taking it seriously and I expect this problem to go away in a coming Java update.
On Linux, one way to work around this Oracle Java bug is to update the cobaltstrike and teamserver scripts to specify the -XX:ParallelGCThreads=8 option after the java command.
I advise that you stay away from Oracle Java 1.8u131. If you already updated to Java 1.8u131, then downgrade to Java 1.8u121.

A: Here is a step by step video to downgrade to version 121 by nizar Mhymyd.
https://www.youtube.com/watch?v=qItkpx61XQ0.


text:
Q: AJAX, jQuery - if $_GET['var'] is set, how to animate one container and fade in another that loaded new content? I have a <table id="pickups"> in /pages/home.php. index.php does include home.php by default, if no other page is set. If you click an element (logfile) in a certain column of that table, the .main-container that contains the #pickups-table will .animate() to a certain size and new content is being loaded into a .pickup-container and will fade in right under the .main-container.
Now I do want to support direct links, so if you link to website.tld/?pickup=name I want the #pickups-table to animate() just like when you click one logfile-element in #pickups-table.
You can try out the example here:

*

*Normal link (you have to click on a logfile): fortress.pwnz.it

*Direct link (I want the animation to automatically happen when $_GET['pickup'] is set, just like when you click on a logfile in the table's logfiles-column): fortress.pwnz.it/?pickup=CTFCL-20130816-0132-openfire_lowgrens
Here is what I got so far:
jQuery, the code below is located within $(document).ready(function() { <scope> }) scope.
    var mainIsCollapsed = 0;
    var mainLastHeight = 0;

    var $_GET = {};
    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function() {
        function decode(s) {
            return decodeURIComponent(s.split("+").join(" "));
        }
        $_GET[decode(arguments[1])] = decode(arguments[2]);
    });
    //if direct link was clicked
    if($_GET['pickup'] != null) {
        var pickup = $_GET['pickup'];
        alert('var pickup: ' + pickup);
        loadPickup(pickup);
    }

    //if td element is clicked
    $('#pickups td:first-child').click(function() {
        loadPickup($(this).attr('name'));
    });

    //fade out content and animate 'main' to its normal size
    $('div.main').click(function() {
        if($(':animated').length)
            return false;
        if(mainIsCollapsed == 1) {
            $('div.pickup').fadeOut(250);

            $(this).animate({
                height: mainLastHeight
            }, 600, function() {
                mainIsCollapsed = 0;
            });
        }
    });

    //animate table and fade in content
    var loadPickup = function(pickup) {
        alert(pickup);

        if($(':animated').length)
                return false;

        if(mainIsCollapsed == 0) {
            mainLastHeight = $('div.main').height();

            //collapse main frame
            $('div.main').animate({
                height:'50px'
            }, 600, function() {
                mainIsCollapsed = 1;
            });
            //load content
            $('div.pickup').load('/pages/pickup.php?pickup=' + pickup, function() {
                //fade in
                $('div.pickup').fadeIn(300);
                //some other code here for tooltips and such
            });
    }

The problem is that when using the direct link, the function loadPickup(pickup) is never executed (the alert(pickup) message box never pops up and it seems like all jQuery scripts stop working).
files:

*

*index.php loads the jQuery/javascript above

*index.php includes /pages/home.php

*index.php contains the div.pickup that will be displayed after new content was loaded

*/pages/pickup.php is the content that is loaded into div.pickup

*/pages/home.php contains the .main container (the one to be animated), within that container the #pickups table is located

EDIT
I have tried calling loadPickup('CTFCL-20130816-0132-openfire_lowgrens'); directly in the $(document).ready() function, it won't call it there either. Instead all jQuery appears to stop working.
What am I doing wrong?

A: The solution to the problem is fairly simple; I'm used to programming in obj-c and Java. If I move the loadPickup() function to the top of the $(document).ready() it works. If it is defined below its call, jQuery doesn't know the function yet when it is trying to execute it.


text:
Q: Rewrite /word/?q=term to /word/term I have this in my htaccess currently:
RewriteEngine on
RewriteRule ^/?word/(.*)$ /word.php?$1 [L]

Which lets me visit a url for example http://www.example.com/word/term and my php script will do some dataabse work for the keyword term
But I am trying to add a search form which currrently goes to http://www.example.com/word/?q=term and my php script is doing DB lookups on ?q=term rather than just term
My form action is going to /word/ and my method is get
Can I add a rewrite to rewrite /word/?q=term to /word/term?
thanks

A:
Can I add a rewrite to rewrite /word/?q=term to /word/term

You can add a rule before your other rule:
Options -MultiViews
RewriteEngine on

RewriteCond %{QUERY_STRING} ^q=([^&]+) [NC]
RewriteRule ^/?(word)/?$ /$1/%1? [L,R]

RewriteRule ^/?word/(.*)$ /word.php?$1 [L]


text:
Q: Display user's data from database on their profile pages In Drupal 7, is it possible to show a result of a DB query on each users' respective profile page, in some table? I need to do this programmatically within my existing module. So the input to the query would be the ID of a user whose profile is currently being viewed.
Only to show the queried data - no administration, no edits, nothing else.
something along the lines of.. (image)
Also the block or field or whatever would make this possible needs to be configurable through the _permission() hook as to who can or cannot view it.
I thought since this is basically just a query with no extra custom stuff there would be an easy way via the Drupal API.

A: you can create custom block for that and view it in current user profile
  /**
     * Implements hook_block_info().
     */
    function custom_block_block_info() {
      $blocks = array();
      $blocks['my_block'] = array(
        'info' => t('My Custom Block'),
        'status' => TRUE,
        'region' => 'Content',
        'visibility' => BLOCK_VISIBILITY_LISTED,
        'pages' => 'user/*',
      );

      return $blocks;
    }

 /**
 * Implements hook_block_view().
 */
    function custom_block_view($delta = '')
    {
        // The $delta parameter tells us which block is being requested.
        switch ($delta)
        {
            case 'my_block':
                // Create your block content here
                $block['subject'] = t('This is just a test block created programatically');
                  $block['content'] = _user_detail_list();
                break;
        }

        return $block;
    }
 /**
 * Implements costome code we want to print().
 */
    function _user_detail_list(){
        //enter your query and output in some variable
        $value = "
User Detail
"
        return $value;
    }

Note :- Here profile is extended with new block

A: There will be some coding to get what you want, but if you just want style/show the data that's already available with the "user" object then #1 below will do it.
Easy way(#1):
1. Create a view and choose the "user" info that you need shown and give it a path. Then in your sub-theme use the correct template -see the code snippets.
   https://www.drupal.org/forum/support/post-installation/2011-04-04/modify-the-default-profile-pagelayout
other ways:

*use the user-profile.tpl.php see
https://api.drupal.org/api/drupal/modules%21user%21user-profile.tpl.php/7.x

*in your module, you need to call and reach out to the hook_user_view.
https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook_user_view/7.x

A: Here you fetch user profile data from database then follow it
function modulename_menu() {
    $items['user-data'] = array(
    'title' => 'User data',
    'page callback' => 'user_data',
    'access callback' => ('user_is_logged_in'),
    '#type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function user_data(){
   global $user;
   $user_fields = user_load($user->uid);
   $output = "" //return those $user_fields values into table using theme('table',header,rows)
   return $output;
}

https://www.drupal.org/node/156863 (for create table view)
i.e
global $user;
$user_fields = user_load($user->uid);

$firstname = $user_fields->field_firstname['und']['0']['value'];
$lastname = $user_fields->field_lastname['und']['0']['value'];


text:
Q: Split using delimeter I have a column having data in format : "abc.def.ghi.jkl" i want to write a query to split this for example I want to fetch "abc" of this string,
  since the length is not fixed for every value in the column I need some way to split this string using "." delimeter. please suggest some way

A: you can use "regexp_substr" with "connect by" to get desired result as below:
select regexp_substr('abc.def.ghi.jkl','[^.]+', 1, level) as splitted_string
from dual
connect by regexp_substr('abc.def.ghi.jkl', '[^.]+', 1, level) is not null;


text:
Q: Kerberos SSO stopped working after Chrome update I'm running Alfresco site with Kerberos SSO and everything worked fine until last Chrome update (101.0.4951.54). Nothing changed in settings, IE still works, but in Chrome it prompts for credentials and doesn't accept them.
Does anyone know what has changed and how to make it work again?

A: In our case, it is because of Security Policy parameter name change in new Chrome browser. https://support.google.com/chrome/a/answer/7679408#noNonIncl
Chrome version 101 has removed the old policy name "AuthNegotiateDelegateWhitelist" and replaced with "AuthNegotiateDelegateAllowlist".
We had same issue with some other SAP web application and fixed the issue by replacing "AuthNegotiateDelegateWhitelist" with "AuthNegotiateDelegateAllowlist".
Example:
Key: \Software\Policies\Google\Chrome
Element Type: String (REG_SZ)
Element Name: AuthNegotiateDelegateAllowlist
Element Value: .mycompany.com,.trustedcompany.com


text:
Q: How to read and write bits to a byte array I have a unsigned char buffer, and I'm wondering how I would write and read signed and unsigned bits to this byte buffer.
In the Source Engine there is a class named bf_write, which two main methods (used by WriteString, WriteChar, WriteLong, etc.) use two functions named WriteUBitLong and WriteSBitLong.
Thanks in advance

A: If the number of bits is a compile-time constant:
#include <bitset>
...
std::bitset<100> b;
b[2]=true;

If it's not, use Boost.dynamic_bitset
Or, if you're desperate, std::vector, which is indeed a packed bit vector:
#include <vector>
...
std::vector<bool> b(100);
b[2]=true;

You seem to want to use a library that requires bit vectors packed in an array of bytes.  Without knowing exactly what order it places the bits in, I can only note that:
1) all of the above will probably use at least 32-bit ints with bits ordered least->most or most->least significant
2) on little endian (Intel/AMD) CPUs, this means that the memory occupied by the bytes an array of ints may not be consistent with the ordering of bits within the int.  if it's "bit 0 is the lsb of int 0, ... bit 32 is the lsb of int 1, ..." then that's the same in little endian as "bit 0 is the lsb of char 0, ... bit 32 is the lsb of char 4 ...", in which case you can just cast a pointer to the int array to a pointer to char array
3) supposing the native order of bytes in your bit set / vector isn't exactly what the library needs, then you have to either have to create your own that has the layout they want, or transcribe a copy into their layout.
a) if the order of bits within a byte is different, a 256 entry lookup table giving the byte with bits reversed would be efficient.  you could generate the table with a small routine.
b) to reverse bytes from little<->big endian:
inline void endian_swap(unsigned short& x)
{
    x = (x>>8) |
        (x<<8);
}

inline void endian_swap(unsigned int& x)
{
    x = (x>>24) |
        ((x<<8) & 0x00FF0000) |
        ((x>>8) & 0x0000FF00) |
        (x<<24);
}

inline void endian_swap(unsigned long long& x)
{
    x = (x>>56) |
        ((x<<40) & 0x00FF000000000000) |
        ((x<<24) & 0x0000FF0000000000) |
        ((x<<8)  & 0x000000FF00000000) |
        ((x>>8)  & 0x00000000FF000000) |
        ((x>>24) & 0x0000000000FF0000) |
        ((x>>40) & 0x000000000000FF00) |
        (x<<56);
}

To get/set a particular bit within a word, with bit #0 in the least significant bit of word 0:
typedef unsigned char block_t;
const unsigned block_bits=8;

inline void set_bit(block_t *d,unsigned i) {
  unsigned b=i/block_bits;
  unsigned bit=i-(block_bits*b); // same as i%b
  block_t &bl=d[b];
  bl|=(1<<bit); // or bit with 1 (others anded w/ 0)
}

inline void clear_bit(block_t *d,unsigned i) {
  unsigned b=i/block_bits;
  unsigned bit=i-(block_bits*b); // same as i%b
  block_t &bl=d[b];
  bl&=(~(1<<bit)); // and bit with 0 (other bits anded w/ 1)
}

inline void modify_bit(block_t *d,unsigned i,bool val) {
  if (val) set_bit(d,i) else clear_bit(d,i);
}

inline bool get_bit(block_t const* d,unsigned i) {
  unsigned b=i/block_bits;
  unsigned bit=i-(block_bits*b); // same as i%b
  return d[b]&(1<<bit);
}

Obviously if the rule for bit organization differs, you have to change the above.
Using the widest possible int your CPU processes efficiently as block_t is best (dont' forget to change block_bits), unless the endianness doesn't work out w/ the library you're using.

A: I think a few macros are enough:
#define set_bit0(buf, i) ((buf)[(i)/8]&=~(1u<<(i)%8))
#define set_bit1(buf, i) ((buf)[(i)/8]|=1<<(i)%8)
#define get_bit(buf, i) ((buf)[(i)/8]>>(i)%8&1)

In addition, swapping endianness can be done in a faster way. For example, for a 64-bit integer v, the following operations swap its endianness:
v = ((v & 0x00000000FFFFFFFFLLU) << 32) | (v >> 32);
v = ((v & 0x0000FFFF0000FFFFLLU) << 16) | ((v & 0xFFFF0000FFFF0000LLU) >> 16);
v = ((v & 0x00FF00FF00FF00FFLLU) << 8) | ((v & 0xFF00FF00FF00FF00LLU) >> 8);


text:
Q: Generate final release apk I'm trying to release the final apk from a react native project but I can't run this on any device.
It says:
Can't find variable __fbBatchedBridge

I try using gradlew assembleRelease and also downloading bundle to asset folder
Any ideas?

A: You can also check if you have react Gradle file in your Gradle files. Try bundling the asset manually if you do not have this file.


text:
Q: How to prompt feedback when User close browser? I know this must be done with javascript. But I am not sure how to do it.
Scenario:
When user close the browser, I will prompt a message whether he/she want to leave comment/feedback or not. If he/she clicks yes, then display(or maybe window.opn/popup), else just close the browser normally.
I tried using onload function, but it does not work in firefox
JS
<script type="text/javascript">

function unloadPage()
{
 alert("unload event detected!");
}
</script>

HTML
<body onunload="unload();">

I also tried the onbeforeunload
window.onbeforeunload = test;
function test() {
return "Submit your feedback to us :)";
}

But it appears that, it just prompt like a normal window.alert. It has "Ok" and "Cancel" button. I cant do much from there.
Can we do a check, if the user clicks "OK", we perform/redirect/popup new window, and if user clicks Cancel, we just close the browser?
I always have the compatibility problems, sometimes works in IE but not in FF

A:
Can we do a check, if the user clicks "OK", we perform/redirect/popup new window

Use a onbeforeunload and set a timeout just before returning the 'Do you want to blah blah' string. If the timeout fires, the user clicked 'Cancel' to stay on the page and you can take a further action such as adding a form or doing a redirect. Pop-ups will usually be blocked as normal.
This is highly unpleasant behaviour. If you do it, you risk prosecution under the Serious Web Crimes Act and are liable for punishment up to and including death or three months' imprisonment with only Netscape 4 as a browser. (I'd take the death.)


text:
Q: ExtJS: Change TreeLoader dataUrl How to change dataUrl of a TreeLoader?
Update: sorry for causing confusion!
dataUrl can be set only in the constructor, there is no public property or method to change it later, after the instance was initialized. Hence, is it even possible to change it?

A: Each request (that's not "direct") appears to use the dataUrl directly. You should be able to just change it as a property, even though it's not reported as being public.

A: Here is a solution to change the URL of the Treeloader dynamically from the controller.
var mystore = Ext.data.StoreManager.lookup('MyTreeStore');
        mystore.setProxy({
                             type: 'ajax',
                             url: 'app/searchid/'+searchText;
                         });

or
You can use the event beforeload to change the url.
mystore.on('beforeLoad',function(store, operation, eOpts){

        store.setProxy({
        type: 'ajax',
        url:"http://localhost/data/treegrid.json",
        actionMethods:{read:'GET'},
        timeout:9000000,
        noCache : false,
        reader: {
        type: 'json'
              }
        });
});


text:
Q: Restrict Sharepoint extension to be used on one specific list There is an extension (custom ribbon) button on top of the list, that is connected to third-party apps, updating the list where you run it.
It's needed to restrict the extension to be used only in the list that is required to use it. I couldn't find it in the configurations while creating the list. Should it be a template?
The main question would be - how to restrict other lists have the button on top of them?

A: You can get the list name in code using this.context.pageContext.list.title and compare it with your list title as given below:
public onListViewUpdated(event: IListViewCommandSetListViewUpdatedParameters): void {
    var Libraryurl = this.context.pageContext.list.title;

    const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
    if (compareOneCommand) {
      // This command should be hidden unless exactly one row is selected.
      compareOneCommand.visible = (event.selectedRows.length === 1 && Libraryurl == "BotFiles" );
    }
}

Source: SPFX Extension Apply List View Command Set to Specific List or Library


text:
Q: Why python raises exception on udp recvfrom I have realy simple python27 script on Windows10
It is just sends messages and waits for reply using udp socket
import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE

sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
sock.recvfrom(1200)

On Windows 10 it raises exception
Traceback (most recent call last):
File "simple.py", line 14, in <module>
print sock.recv(1200)
socket.error: [Errno 10054]

On Linux it works fine.
What i am doing wrong ?

A: The first several lines of your program are opening a socket to send data which all is fine. But the sock.recvfrom line doesn't have an associated bind with it.
In other words, when you send on UDP you shouldn't expect to receive anything back. If you want to send a message and then wait for a reply (which will not be automatic from a remote system) you need to bind the socket to a listening port.
This site: https://wiki.python.org/moin/UdpCommunication has some great references.

A: I found solution here Windows UDP sockets: recvfrom() fails with error 10054 Author made the same. He ignores this error. But maybe it is true way of solving this problem.
I just put recvfrom in while and wrapped it with try..except
And I ignore any errors. It worked for me


text:
Q: Dynamic menu tree using recursion and getting info from four others mysql tables I'm trying to make a menu, which will take information from four tables e.g. pages, categories, sub-categories and articles.
For example, I want to make a menu which will look something like this:
Home
Category 1
   Subcategory 1.2
   Subcategory 1.3
   Subcategory 1.1
Category 2
   Subcategory 2.3
   Subcategory 2.2
   Subcategory 2.1
Subcategory 4.1
   Article 4.1.2
   Article 4.1.3
   Article 4.1.1
Page 2 (Services)
   Page 3 (Service 1)
   Page 4 (Service 2)
   Page 4 (Service 3)
Page 1 (About us)

Database table menu:
+----+---------+---------------------+-----------+-------+--------+
| id | id_menu | type                | parent_id | order | active |
+----+---------+---------------------+-----------+-------+--------+
|  1 |       1 | pages               |         0 |     1 |      1 |
|  2 |       1 | sub_categories      |         0 |     2 |      1 |
|  3 |       2 | sub_categories      |         0 |     4 |      1 |
|  4 |       2 | categories          |         0 |     3 |      1 |
|  5 |       3 | sub_categories      |         4 |     1 |      1 |
|  6 |       2 | sub_categories      |         2 |     1 |      1 |
+----+---------+---------------------+-----------+-------+--------+

(id_menu stand for id of the type) | (parent_id == 0 stand for root of the menu)
Menu from the input database should look like this:
Page 1
Sub Category 1
   Sub Category 2
Category 2
   Sub Category 3
Sub Category 2

I choose to use type for the name of the table.
Basically, if I want to take category 1 (id == 1) for the second menu item, I'll do something like this:
INSERT INTO `menu` (`id_menu`, `type`, `parent_id`, `order`, `active`) VALUES (`1`, `categories`, `0`, `2`, `1`);

I tried a lot of options in PHP to make it, but I get an infinite loop or some crazy menu...
How can I make this? Because I've tried various ways and I've not found a relevant solution.
I tried something like this to get just a child of the menu. But then I get an infinite loop.
function GetMenuTree($ParentId){
    global $conn;
    $menu = "";
    $MenuData = $conn->prepare("SELECT * FROM menu where parent_id = ?");
    $MenuData->execute([ $ParentId ]);
    while ($row = $MenuData->fetch()) {
        $SQL = "SELECT * FROM " . $row[ 'type' ] . " WHERE id = " . $row[ 'id_menu' ];
        $DataForMenu = $conn->prepare($SQL);
        $DataForMenu->execute();
        foreach ($DataForMenu as $value) {
            $menu .= "\n
" . $value[ 'title' ] . "\n";

            $menu .= "\n
" . GetMenuTree($row[ 'id_menu' ]) . "
\n";

            $menu .= "\n
\n";
        }
    }
    return $menu;
}


text:
Q: Watson Conversation - Getting Dialog Context to Application I've connected my chatbot (Watson Conversation) to messenger. However,
I'm stuck on passing of context variable for my Google Map API.
Process Flow:

*

*User: I want to compute the distance

*Bot: Gets $var1 and $var2

*User: Inputs $var1 and $var2

*Bot: Provides the distance between $var1 and $var2
How will I be able to get the user's $var1 and $var2 on my Application Code?
Note: It is on Dialogue Node [2].

A: For java just simply use :
    Conversation service = new Conversation("2017-07-13");
    service.setUsernameAndPassword("", "");
    MessageOptions newMessage = new MessageOptions.Builder().workspaceId("")
            .input(new
    InputData.Builder(input).build()).context(context).build();
    MessageResponse response = service.message(newMessage).execute();
    int var1 = response.getContext().get("$var1");

Similarly for 2nd variable.


text:
Q: Rounding numbers in a dataframe with mixed values (string, date, number, etc.) I have been trying to round numbers in a dataframe with multiple values, but cannot figure out a way. Tried to set options(digits = 6), solutions offered in this topic, and some others. My dataframe looks like:
structure(list(X__1 = c("Start", "End", "EFM", "UTH", "PEU",
"HPX"), `TecM` = c("Mar-00", "Mar-01", "NA", "NA",
"-9.6432560109885879E-2", "-0.26834090581750103"), `TerA` = c("Sep-01",
"Sep-01", "NA", "NA", "0", "-0.11600490599886504"), `GloC` = c("Nov-07",
"Mar-09", "-0.62921737727223548", "NA", "-0.54549924666990268",
"-0.54518556256613238"), `ECis` = c("Jul-11",
"Sep-11", "-0.2912541254125412", "NA", "-0.21781440969547586",
"-0.18769305803934319"), `OSe` = c("Jul-14", "Dec-14",
"-0.10996326905417812", "-3.4236420002695674E-2", "-2.8281230134625412E-2",
"4.8566639665387892E-2")), .Names = c("X__1", "TecM",
"TerA", "GloC", "ECis",
"Oil Selloff"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L))

Are there any simple options?

A: I guess there is also a tibble solution, but I'm always getting confused on selecting columns etc in tibbles. That's why I changed it into a data.frame.
jnk1 <- as.data.frame(jnk)
numeric_values <- !is.na(apply(jnk1, 2, as.numeric))
jnk1[numeric_values] <- round(as.numeric(jnk1[numeric_values]),1)

Imagine your data is called ink. Save it as a data.frame. Check which values could be parsed into numeric and then overwrite them by the round value.
Since there might be warnings, u can suppress them with this line
numeric_values <- suppressWarnings(!is.na(apply(jnk1, 2, as.numeric)))

A: If it's just for easier viewing, the following line will round all numeric-looking values in the table to 2 digits:
# assume df is your original data frame
suppressWarnings(data.frame(lapply(df, function(y) ifelse(is.na(as.numeric(y)), y, round(as.numeric(y), 2)))))

# result
   X__1   TecM   TerA   GloC   ECis Oil.Selloff
1 Start Mar-00 Sep-01 Nov-07 Jul-11      Jul-14
2   End Mar-01 Sep-01 Mar-09 Sep-11      Dec-14
3   EFM     NA     NA  -0.63  -0.29       -0.11
4   UTH     NA     NA     NA     NA       -0.03
5   PEU   -0.1      0  -0.55  -0.22       -0.03
6   HPX  -0.27  -0.12  -0.55  -0.19        0.05

But a column with numeric / string / date in a data frame would still be a column of characters.


text:
Q: Are the strings in argv modifiable? I just wrote a small program that reads command line arguments in C, nothing too difficult. I was also modifying them, for example changing the first character of the parameter to uppercase.
I know that you shouldn't modify string literals as it can cause undefined behavior, so was just wondering if the strings in the *argv[] are literals that you shouldn't change.
int main(int argc, char *argv[])

A: The arrays that support the strings in argv are modifiable.
But you have no way to know their sizes.
I would frown upon seeing code that (tries to) increase the size of the strings.
#include <stdio.h>
#include <string.h>
// this program may behave erraticaly
int main(int argc, char **argv) {
    for (int k = 1; k < argc; k++) {
        printf("original argv[%d] is %s\n", k, argv[k]);
    }
    printf("\n");
    for (int k = 1; k < argc; k++) {
        strcat(argv[k], " foo"); // add foo to each argv string
        printf("first modification to argv[%d] is %s\n", k, argv[k]);
    }
    printf("\n");
    for (int k = argc; k > 1; k--) {
        strcat(argv[k - 1], " bar"); // add bar to each argv string
        printf("final argv[%d] is %s\n", k - 1, argv[k - 1]);
    }
    return 0;
}

On my machine, calling that program with one two three arguments produces

original argv[1] is one
original argv[2] is two
original argv[3] is three

first modification to argv[1] is one foo
first modification to argv[2] is foo foo
first modification to argv[3] is foo foo

final argv[3] is foo foo bar
final argv[2] is foo foo foo bar bar
final argv[1] is one foo foo foo bar bar bar

A: From the C11 standard draft N1570, §5.1.2.2.1/2:

The parameters argc and argv and the strings pointed to by the argv
  array shall be modifiable by the program, and retain their last-stored
  values between program startup and program termination.

They are modifiable. That means they are not string literals.
But be careful: the upper citation only refers to pointers to strings, excluding the obligatory null pointer at argv[argc]1.
From the C11 standard draft N1570, §5.1.2.2.1/2 (same as above)1:

argv[argc] shall be a null pointer

Notes:

*

*Something regarding this sentence:

I know that you shouldn't modify string literals as it can cause
  undefined behavior [...]

"can"? It does always. Undefined behavior includes expected, as if well-defined, and unexpected behavior.

1 Thanks to @black!


text:
Q: Call an override method in an abstract class i have a problem. I try to start the override Host method from Program.cs in the abstract class AbstractGenericClass.
public abstract class AbstractGenericClass<T>
{
    protected abstract void Host();

    public static void Start()
    {
        //add additional logic for all classes that use this

        try
        {
            ((AbstractGenericClass<T>) Activator.CreateInstance(typeof(T))).Host();

            Console.WriteLine("Works!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Don't Works!");
        }
    }
}

class AnotherClass
{
    public void DoSomething()
    {
        //NOP
    }
}

class Program
    : AbstractGenericClass<AnotherClass>
{
    static void Main(string[] args)
    {
        Program.Start();

        Console.ReadLine();
    }

    protected override void Host()
    {
        Console.WriteLine("Host running...");
    }
}

I add here all sample classes i create for showing what i mean. The line with ((AbstractGenericClass) Activator.CreateInstance(typeof(T))).Host();
crash the program because of InvalidCastException. It must be possible to call the Host method but i have no idea how i could this, if this dont operates.
Have you any other idea how this could operate? Or is this totally wrong what i try?

A: Replace
((AbstractGenericClass<T>) Activator.CreateInstance(typeof(T))).Host();

with
Host();

Because Host() is an abstract method, Program.Start() will call the implementation of this method in the derived class, so it will execute the implementation of Host() from Program.

A: You can't cast the result from CreateInstance as AbstractGenericClass because it is of type AnotherClass, which does not derive from AbstractGenericClass and doesn't have a Host method anyway.  Sounds like what you want is to get an object of type Program and call Host on that.


text:
Q: How to extract a json from a pandas dataframe? I have a pandas dataframe and in one of the columns there is a string that represents a json:
|-----------------------------|
|{"name": "John", "age": "32"}|
|None                         |
|{"name": "Mary", "age": "29"}|

I need to create new columns for name and age and extract the data from this json.
Note: It may be null values os missing keys.

A: If json strings are like below, try this:
import pandas as pd
import json

df = pd.DataFrame({'your_column_name':['{"name": "John", "age": 32}', None, '{"name": "Mary", "age": 29}']})
list_of_jsons = df.your_column_name.to_list()
list_of_jsons = [json.loads(s) if s else {"name": None, "name": None} for s in list_of_jsons]
df2 = pd.DataFrame(list_of_jsons)
df = pd.concat([df,df2], axis=1)

Otherwise what you have in each row is a set with a string in it. You need to parse that string with str.split() methods and create your own list of dictionaries (variable I named list_of_jsons) and create df2 and concatenate like above.

A: Create a couple of new columns named "name" and "age". Apply a function to the column dataframe and parse the content as json with a try/except block. If there is a value, assign it to the name/age columns, if there is no value or the value is null, set the values in the name/age columns to None, accordingly.
Applying a function to a column:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html
Parse json:
https://www.programiz.com/python-programming/json


text:
Q: What are the interpretations of these different types of stochastic convergences? Thanks for passing by!
I am studying an introduction to stocastic processes and I found 4 types of stocastic convergences with their definitions as follows:
Let $(X_n)_{n\geq0}$ be a sequence of $r.v.$ on $(\Omega,\mathcal{F},\mathcal{P})$ we say..

*

*Almost sure convergence

$(X_n)_{n\geq0}$ converges almost surely to the r.v. $X$ iff there exists an event $\tilde{\Omega} \in \mathcal{F}$ of probability one such that
\begin{equation}
\forall\, \omega \in \tilde{\Omega}\,,\quad \lim_{n\to\infty}X_n(\omega)=X(\omega)
\end{equation}

*Convergence in probability

$(X_n)_{n\geq0}$ converges in probability to the r.v. $X$ iff $\forall\,\epsilon \gt0$ :
\begin{equation}
\lim_{n\to\infty} P(|X_n - X|\gt\epsilon)=0
\end{equation}

*Convergence in $L^p$
$(X_n)_{n\geq0}$ converges in $L^p$ to the r.v. $X$ iff:
\begin{equation}
\lim_{n\to\infty} ||X_n - X||_p=0
\end{equation}

*Convergence in Law
$(X_n)_{n\geq0}$ converges in law to the r.v. $X$ iff:
\begin{equation}
\lim_{n\to\infty} E[f(X_n)] = E[f(X)]
\end{equation}
This last one having some other formulations in terms of $F_x$ and also the Characteristic Function of the distribution.
I have seen youtube videos with demonstrations and read some interesting sources on the internet, but I still can't really get it. I think I understand this theoretical formulations, but I do not arrive to imagine its applications in concrete cases.
Why do they always use "closed" formulas to define the values in the sequence of $X_n$? For me it's quite disturbing since I understood that $X_n$ is more a sequence of observations/realizations of a r.v. rather that something that is defined by a mathematical formula.
So any type of clarification on this would be extremely appreciated,
Thanks a lot in advance


text:
Q: How to pass a parameter to previous page? I am working on a JSP project.  I have a page that calls another JSP.
Now the problem is, how to pass or use a variable in the called JSP page in its calling page?

A: Your design should be

*

*take one input param on page1.jsp

*post it to some servlet , process it there, forward request to page1 jsp and pass param taken from page 1 as attribute

See Also

*

*why-business-logic-should-be-moved-out-of-jsp ?

A: You can save the variable in the HTTPSession or ServletContext object.
And in the calling JSP page, use or check session attribute for the variable.
session.setAttribute(objectId, Object); to set the variable.
session.getAttribute(objectId); to get the variable.

A:
I have a page that calls another jsp
  page

The problem lies here in this sentence.
Try to follow MVC. Use JSP just for rendering the View, and Servlet as a Controller.
Here, simple.souther.us, you find simple and awesome tutorials for newbies.