text:
Q: Can you copy a website? Can you copy a Composite C1 website? I would like to create a copy of an existing website as a new website.
I start by creating Site A. Then I want to copy it and create Site B.
For example: copy the pages, functions, data, content, layouts, css from website A to website B. The only difference between the two would be the name.

A: It would infringe copywrites and may get you sued, but yes, its possible with a scraper, which basicly get all of the site, and download it to you, such things are used by google and search engines for a cache of sites.
Some exaples:
http://www.grepsr.com/?adwords2&gclid=CIe4rrPF57cCFURcpQodASIAgg

http://info.kapowsoftware.com/WebScrapingDefinitiveGuide.html?pi_ad_id=11920224743&gclid=CPCfxbTF57cCFWNNpgodnCQAKQ

http://scrapy.org/

or just google "web scrapers"
If you own the site however, and have access to the ftp, just simply copy the files to a folder called /b and it can become www.a.com/b or you can set up an addon domain to point to /b and make the addon domain.... say www.b.com

A: The answer to your question "can you copy a website?"
Is Yes....you can.
Provided you have access to all the files/folders, its no different then copying a bunch of folders on your computer, to another folder.
So if you're using a shared host....and everything is in your public_html folder.
Just put the whole website in one folder, then copy it over to another folder.
And then just simply point your new domain to that folder, through your hosting platform.
The process to do this is different for different hosts, but the actual answer to your question is...
YES....YOU CAN COPY A WEBSITE FROM ONE FOLDER TO ANOTHER

A: IF you have access to the files on the server you can simply copy it to the other desired location...
But remember you have to update links and other paths (if they are absolute).
If you don't have the access you could maybe use the developer tools like firebug, or using F12 on chrome or IE and copy each file and source code you have by hand. This approach is a little more time consuming than the last one but at least it can be made.
Cheers

A: As far as I know the easiest way would be use use Internet Explorers save to offline webpage function (if it is still there) - this will copy all the resources of the currently open webpage and recode the HTML to use them, as for an entire website..I dont think it will be easy, for legal reasons.

A: If it's your own site, sure why not! Who is there to stop you?
But if it's someone elses site, of course you have to worry about copyright and most of the time the website uses server side scripts which are not downloabeable.

A: You can duplicate a Composite C1 website by copying the entire file structure to a new folder and then update the installation id in the folder ~/App_Data/Composite/Configuration/InstallationInformation.xml (put in a new random GUID). Then point a new IIS site into this new folder.
If your site is using SQL Server as a backend you also need to create a copy of your database, create a new user account with dbo access for this database and update the connection string in ~/web.config.
If you wish to duplicate an entire page structure inside the existing instance of the CMS and share media files, templates etc. this could be done, but no tooling is available. This would be a coding task.

A: Copy the the directory(website physical path) where the website is pointing to and paste it somewhere...create a new website and point it to that copied directory....


text:
Q: Javascript regex matching syntax not working I would like to test a string to ensure it has the following pattern:
asas/asas2/asas

The charatcers in between the slashes can be letters, digits or both.

I have a working example here, although i'm sure it could be improved.
Regex Example

But when tested in jsfiddle it doesn't work
Jsfiddle Example
var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);

The above code example always returns false.

A: Remove the quotes new RegExp(/(^\w+\/\w+\/\w+$)/g);

A: You just have to remove quotes.

var str = 'dfdfdf/dfdf/dfdf';
var patt = /(^\w+\/\w+\/\w+$)/g;
var res = patt.test(str);
alert(res);

A: Please try this code:
var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp(/(^\w+\/\w+\/\w+$)/g);
var res = patt.test(str);
alert(res);
console.log(res);

Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why System.getProperty("home.dir") returns null I cant figure out why System.getProperty("home.dir") is returning null instead of the current working directory.
I am using Eclipse Mars2.0 IDE on Ubuntu 16.04. I guess, this hardly matters which IDE I am using or the OS version.
package test;

public class testing {
    public static void main (String args[])
    {
        System.out.println(System.getProperty("home.dir"));
    }

}

I am expecting to get a return for this code as something like /home/[user]/Workspace/test

A: Home.dir is not a java property as specified here:
https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
If by working directory you mean the users working directory then user.home should work.
Example:
    System.out.println(System.getProperty("user.home"));

Outputted:
C:\Users\User

If you mean the .jars working directory then I do not believe such a property exists.
Instead use:
    your_class.class.getProtectionDomain().getCodeSource().getLocation().getPath();

This will return a string specifying where the jar is situated currently.
Example:
    System.out.println(new File(**TestLighting.class.getProtectionDomain().getCodeSource().getLocation().getPath()**));

(new File() is to get the correct formatting, it was /C:/...)
Outputted:
C:\Users\User\Documents\Java\Netbeans\Engine\build\test\classes

(This is the path of where the jar is being run from)
If home.dir is a system environment variable then you would use System.getenv()


text:
Q: What is the best way to organize your library Is it better to merge all your code into one dll file or is it better to create separate projects for each namespace, for instance? I don't think it'd harm code's readability in any way as the code is separated in namespaces.
My question is:
How does the size of a library harm performance?

A: It depends but generally it will affect your application at the initial load. In scenarios where you have dependency injection, the DLL loading will take longer as the dependency injection tool has to do a bit of work to figure things out.
In regard to explicit dependencies where your application directly references another project or component, performance is hurt on application load but shouldn't affect performance otherwise by its presence. All this of course doesn't account for what's actually in the DLLs as whatever work they do and their size will also increase load time.
There is also the possibility that your application has plug-ins which will decrease performance when they're loaded. When that happens is up to you application however.


text:
Q: Perform action on elements added by AJAX I have a page with a lightbox on it, using a lightbox plugin. The elements I want to turn into a lightbox are simply selected and altered like this:

$(".lightbox").find("a").live('click', function(e)
{
    e.preventDefault();

    $(".lightbox").find("a").fancybox({
        'transitionIn'  : 'elastic',
        'transitionOut' : 'elastic'
    });
});

I know it's not the cleanest way, but it works for now. My real question is, how can I run $(".lightbox").fancybox(...) on elements added to the page by AJAX? I could put the .fancybox() stuff inside the success: part of the AJAX call, but I'm looking for a cleaner, "fire and forget" solution; one piece of code I can write that applies to all future elements. .live() is perfect here, apart from the fact that you have to bind it to an event. I guess the even here is create, which doesn't exist.
So, how can I run a function on elements added to the page by AJAX now, or in the future without having to put lots of bits of code all over the place?
Thanks,
James

A: Just add another layer of abstraction above your jQuery ajax call.  This layer will make the ajax call for you and scan your result, adding the lightbox as necessary.  Here is what I have in mind:
1.
function lightBoxAjaxRequest(requestObj) {
    if (requestObj.success) {
        var requestObjCopy = $.clone(requestObj);  // clone request object

        requestObjCopy.success = function add$lightbox$to$response(html) {
             // Add "html" to the page...
             // Call lightbox code here, on newly added HTML
             requestObj.success(html); // Trigger original success handler
        };

        $.ajax(requestObjCopy);
    }
    else {
        $.ajax(requestObj);
    }
};

Something like that maybe?  I don't know how well that would work in practice though.  It seems like you want to always trigger some function after something has been added to the DOM.

Alternatively
You could also create a wrapper around innerHTML to do the work for you:
2.
function addHtmlToDomWithLightbox(domElement, html) {
    if (typeof domElement === "string") {
        domElement = $("#" + domElement);
    }

    domElement.html(html);

    // Add lightbox here
    domElement.find("a").fancyBox({});
};

You would call addHtmlToDomWithLightbox in all of your success functions (instead of adding the html via the jQuery html method).  Note that the method name is long and verbose, you could change it and place the method where ever you want.  I just made it verbose for illustrative purposes.


text:
Q: CLI command to fetch detail for one package from Nuget I need to get detail for one package from Nuget through CLI command. Below command returns me all packages which is unusable as it take alot of time to get executed.
nuget list -source http://nuget.org/api/v2

A: From Visual Studio:
Find-Package -Source "http://nuget.org/api/v2" -Id "SomeName"

(or to be depreciated)
Get-Package -ListAvailable -Source "http://nuget.org/api/v2" -Filter *SomeName*

From Powershell v5:
Find-Package -Source "http://nuget.org/api/v2" -Name "SomeName"

You might be promted smth like

Blockquote
  nuget may be manually downloaded from https://oneget.org/Microsoft.PackageManagement.NuGetProvider-2.8.5.207.dll and installed.
  Would you like PackageManagement to automatically download and install 'nuget' now?

In older versions of Powershell you might need to look into OneGet package manager (https://github.com/OneGet/oneget)


text:
Q: Running shell commands in parallel using dask distributed I have a folder with a lot of .sh scripts. How can I use an already set up dask distributed cluster to run them in parallel?
Currently, I am doing the following:
import dask, distributed, os

# list with shell commands that I want to run
commands = ['./script1.sh', './script2.sh', './script3.sh']

# delayed function used to execute a command on a worker
run_func = dask.delayed(os.system)

# connect to cluster
c = distributed.Client('my_server:8786')

# submit job
futures = c.compute( [run_func(c) for c in commands])

# keep connection alive, do not exit python
import time
while True:
    time.sleep(1)

This works, however for this scenario it would be ideal if the client could disconnect without causing the scheduler to cancel the job. I am looking for a way to compute my tasks that does not require an active client connection. How could this be done?

A: Have you seen http://distributed.readthedocs.io/en/latest/api.html#distributed.client.fire_and_forget ? That would be a way to ensure that some task runs on the cluster after the client has gone.
Note also that you have functions like wait() or even gather() so you don't need sleep-forever loops.
In general, though, subprocess.Popen will launch a child process and not wait for it to finish, so you don't even need anything complex from dask, since it doesn't appear you are interested in any output from the call.


text:
Q: Executing a Genetic Programming tree I am running GP algorithm using ECJ 26 during that I use describe() function to test the tree, however, currently I need to store and execute the tree outside ECJ framework.
Please, could you let me know if it is possible?
Thanks in advance.

A: The simplest approach to executing a tree (like an abstract syntax tree) would be traversing the tree using the visitor pattern and taking actions based on the current node and the current state of the executor (your "virtual machine"). This is how the so called tree walk interpreters work (a typical example is the Ruby interpreter prior to v1.9).
This is for sure a very generic answer, but hopefully it'll give you some ideas.


text:
Q: Oracle: How to do multiple counts with different where clauses the best way? I have requirement to count rows with different where clauses from the same table.  The following is the required output from me
Bu   #A   #B  #C  #D #E #F #G  #H  #J  #K  #L   #M  #N
GB01 267  284 84  45 35 32 458 801 111 899 892  56  99
NL01 132  844 65  28 26 12 627 321 56  681 1062 127 128

Each column has its own criteria, so far I have the following SQL but it already looks ugly and doesn't exactly return what I need
SELECT *  FROM (
  SELECT
    c_unit_code,
    COUNT(*) AS ADVICE_EXPORT,
    0 AS CONFIRMATION_EXPORT,
    0 AS ISSUANCE_STANDBY
  FROM EXIMTRX.EPLC_MASTER
  WHERE (CLS_FLG NOT LIKE 'YES' OR CLS_FLG IS NULL) AND (
    form_of_lc LIKE 'IRREVOCABLE' OR
    form_of_lc LIKE 'REVOCABLE' OR
    form_of_lc LIKE 'IRREVOCABLE TRANSFERABLE' OR
    form_of_lc LIKE 'REVOCABLE TRANSFERABLE') AND our_eng LIKE 'ADVICE'
    GROUP BY c_unit_code
UNION
  SELECT
    c_unit_code,
    0 AS ADVICE_EXPORT,
    COUNT(*) AS CONFIRMATION_EXPORT,
    0 AS ISSUANCE_STANDBY
  FROM EXIMTRX.EPLC_MASTER
  WHERE (CLS_FLG NOT LIKE 'YES' OR CLS_FLG IS NULL) AND (
    form_of_lc LIKE 'IRREVOCABLE' OR
    form_of_lc LIKE 'REVOCABLE' OR
    form_of_lc LIKE 'IRREVOCABLE TRANSFERABLE' OR
    form_of_lc LIKE 'REVOCABLE TRANSFERABLE') AND our_eng LIKE 'CONFIRMATION'
    GROUP BY c_unit_code
UNION
  SELECT
    c_unit_code,
    0 AS ADVICE_EXPORT,
    0 AS CONFIRMATION_EXPORT,
    COUNT(*) AS ISSUANCE_STANDBY
  FROM EXIMTRX.EPLC_MASTER
  WHERE (CLS_FLG NOT LIKE 'YES' OR CLS_FLG IS NULL) AND (
    form_of_lc LIKE 'IRREVOCABLE STANDBY' OR
    form_of_lc LIKE 'REVOCABLE STANDBY' OR
    form_of_lc LIKE 'IRREVOC TRANS STANDBY')
    GROUP BY c_unit_code
);

and this is what it returns
GB01    0   0   17
GB01    0   39  0
GB01    80  0   0
NL01    0   0   32
NL01    0   159 0
NL01    341 0   0

Any ideas, how can I achieve what I need?

A:   SELECT
    c_unit_code,
    COUNT(case when YOUR_CONDITIONS_FOR_ADVICE_EXPORT then 1 end) AS ADVICE_EXPORT,
    COUNT(case when YOUR_CONDITIONS_FOR_CONFIRMATION_EXPORT then 1 end) AS CONFIRMATION_EXPORT,
    COUNT(case when YOUR_CONDITIONS_FOR_ISSUANCE_STANDBY then 1 end) AS ISSUANCE_STANDBY
  FROM EXIMTRX.EPLC_MASTER
  GROUP BY c_unit_code


text:
Q: Combine Multiple string-array from array.xml to one single List I have some string-array defined in the array.xml, and want to combine them in to a single List. I have try like this:
List<String> name_list;
name_list = Arrays.asList(getResources().getStringArray(R.array.name1));
name_list.addAll(Arrays.asList(getResources().getStringArray(R.array.name2)));

But error Caused by: java.lang.UnsupportedOperationException
array.xml
<string-array name="name1">
    <item>Peter</item>
    <item>Phooenix</item>
    <item>Ebele</item>
    <item>Alice</item>
</string-array>

<string-array name="name2">
    <item>Olivia</item>
    <item>Tai</item>
</string-array>

A: When you look at the Javadoc of Arrays you can see that the List returned by Arrays.asList(...) is only a Bridge to use an Array as a List and therefore is fixed size.
To solve your problem you can use something like this:
List<String> name_list = new ArrayList<>();
name_list.addAll(Arrays.asList(getResources().getStringArray(R.array.name1)));
name_list.addAll(Arrays.asList(getResources().getStringArray(R.array.name2)));

A: Read the javadocs on Arrays.asList:
Returns a fixed-size list backed by the specified array.
So you're not allowed to call addAll in the second line of your code. Instead, you need to create your own List, and use addAll for both arrays on your own list.


text:
Q: What type of math is summing repeated rational results? I am working on a problem crop harvesting/sowing problem. A beet seed will yield 1 beet. Beets left in the ground will produce 3 seeds per beet to be replanted in the next season.  I'm curious if there's a direct way to solve this like you can for an arithmetic series or something?  What would this math area be called so that I can study further?
The problem is that if I want to sow enough seeds so that I can harvest $d$ beets, then I won't have any beets in the ground to produce seeds for the next season. I now need to plant enough beets to account for the extra beets needed to seed the next season.  I played with this and got $d + d/3$. This gets me closer but now I have to account for the beets that result from $d/3$.  This keeps getting closer but doesn't solve the problem since now I have to account for the beets, the additional beets for seeds and now the beets for that addition, and so on.
I noticed that this is really just repeatedly dividing the result of the previous result.  This is where I started going with the math but I don't know what branch/topic of math this would be called to learn more about it.  I simply can't stop accumulating partial results at hard coded amount of attempts as illustrated here:
$$
d + {{d + {{d + {d\over 3}}\over 3}}\over 3}
$$
Depending on the size of $d$ this will start to lose seeds.
I didn't give up entirely though! I don't know how to continue the with the math so I came up with a recursive solution in code:
def seeds_needed need
  seeds = need / 3.0

  if seeds < 1
    return 1   # because I can't use a partial seed :)
  else
    return seeds + seeds_needed(seeds)
  end
en

This function gets me as close as I can.  I pass it the number of beets I wish to harvest each year and it will return to me the number of seeds that I need to plant so that I can leave the extra beats in the ground to become seeds and start the process all over again.
Note: I do normalize the results later to account for the seeds being multiples of 3 per plant.

A: It's 2am, I want sleep, my Mathjax is really bad. So I tried handwriting it. Sorry. I do hope I understood correctly and that my math holds.
Second line, I rearranged the given equation, equal to total seeds needed.  Second to third line, I expanded the brackets. It was a bit brief the working. One could easily jump straight to the $d + d/3 + d/3^2...$ bit just by looking at the given equation, but it is what it is, this might help you see/understand it better maybe.
I think the topic you are interested in is geometric progressions and sums. https://www.varsitytutors.com/hotmath/hotmath_help/topics/geometric-series Something like this. Common ratio is $T_2/T_1 $in a series, to see a sort of relationship, or more generally $T_n / T_{n-1}$, to see the relationship between a term and the next. Hopefully this helps, and again sorry for the sloppy work.
Edit: It has occurred to me that T.S = $ d + d/3 + d/3^2 ... + d/3^{y-1}$ not T.S = $d + d/3 + d/3^2 ... + d/3^y$ as I wrote. As y—> infinity, this shouldn't affect it, but if you're looking at a specific year, that isn't too large it might have an impact.

A: Try let $u = d + (d + (d + \cdots)/3)/3$, then because this series is infinite, $u = d + u/3$ and you should get $u$ quickly.


text:
Q: How to install mysql-connector via pip I use sqlalchemy to access MySQL in my Python project. sqlalchemy's conf is like this:
dialect=mysql
driver=mysqlconnector

So I need to install the Python module mysql connector via pip. Any help?

A: execute following command from your terminal
sudo pip install --allow-external mysql-connector-python mysql-connector-python

A: If loading via pip install mysql-connector and leads an error Unable to find Protobuf include directory then this would be useful pip install mysql-connector==2.1.4
mysql-connector is obsolete, so use pip install mysql-connector-python. Same here

A: To install the official MySQL Connector for Python, please use the name mysql-connector-python:
pip install mysql-connector-python

Some further discussion, when we pip search for mysql-connector at this time (Nov, 2018), the most related results shown as follow:
$ pip search mysql-connector | grep ^mysql-connector
mysql-connector (2.1.6)                  - MySQL driver written in Python
mysql-connector-python (8.0.13)          - MySQL driver written in Python
mysql-connector-repackaged (0.3.1)       - MySQL driver written in Python
mysql-connector-async-dd (2.0.2)         - mysql async connection
mysql-connector-python-rf (2.2.2)        - MySQL driver written in Python
mysql-connector-python-dd (2.0.2)        - MySQL driver written in Python

*

*mysql-connector (2.1.6) is provided on PyPI when MySQL didn't provide their official pip install on PyPI at beginning (which was inconvenient). But it is a fork, and is stopped updating, so
pip install mysql-connector

will install this obsolete version.

*And now mysql-connector-python (8.0.13) on PyPI is the official package maintained by MySQL, so this is the one we should install.

A: pip install mysql-connector

Last but not least,You can also install mysql-connector via source code
Download source code from:
https://dev.mysql.com/downloads/connector/python/

A: For Windows
pip install mysql-connector
For Ubuntu /Linux
sudo apt-get install python3-pymysql

A: First install setuptools
sudo pip install setuptools

Then install mysql-connector
sudo pip install mysql-connector

If using Python3, then replace pip by pip3


text:
Q: Spring JPA query using specification and projection I used spring jpa specification to build dynamically an entity query.
It's working perfect but the query returns all entity fields which makes the performance slower.
I want to fetch specific entity fields only and not fetching all entity fields and dependencies which I don't want and I will not use.
I search on the web, I tried some scenarios but without any lack.
Can anyone suggest any solution on this?
Thanks in advance
Here is what I have.I'm using spring boot 2.2.4
public class Concert {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;

    @Column
    private String code;

    @Column
    private double totalIncome;

    @Column
    private double totalExpenses;

    @Column
    private double totalBudget;

    @ManyToOne(targetEntity = Orchestra.class, fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "orchestra_id")
    private Orchestra orchestra;

    @ManyToOne(targetEntity = ConcertStatus.class, fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "concert_status_id")
    private ConcertStatus status;

    /* other fields */

}

Specification:
public class ConcertSpecification implements Specification<Concert> {

    @Override
    public Predicate toPredicate(Root<Concert> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
        List<Predicate> predicates = new ArrayList<>();

        //add add criteria to predicates
        for (Criterion criteria : criteriaList) {

            /* predicates builder here */
        }

        return builder.and(predicates.toArray(new Predicate[0]));
    }
}

Repository:
public interface ConcertDao extends JpaRepository<Concert, Long>, JpaSpecificationExecutor<Concert>, PagingAndSortingRepository<Concert, Long> { }

ConcertService:
public interface ConcertService {
    Page<Concert> findAll(@Nullable Specification<Concert> spec, Pageable pageable);
}

ConcertServiceImpl:
@Service(value = "concertService")
public class ConcertServiceImpl implements ConcertService {

    public Page<Concert> findAll(@Nullable Specification<Concert> spec, Pageable pageable){
        List<Concert> list = new ArrayList<>();
        concertDao.findAll(spec).iterator().forEachRemaining(list::add);
        return new PageImpl<Concert>(list);
    }
}

A: Usage of projections with specifications are not supported and there is a PR for it that has been hanging for over five years.


text:
Q: Shutting down computer from terminal in debian buster What is the command for shutting down the computer and rebooting it using terminal in Debian buster?
I am using KDE version.

A: It is simple. As user root:
# reboot

The reboot command is only available for the root user. If you are logged in as a normal user try it with sudo:
$ sudo reboot

A: Linux documentation says:
halt, poweroff, reboot - Halt, power-off or reboot the machine

These are legacy commands available for compatibility only.

The approved method is currently shutdown
For those crisis moments, google Raising Elephants

A: The reboot, and shutdown commands (shutdown -r) are in /usr/sbin (admin commands that usually require root privs/sudo and may not be in your regular path, if you are a plain user.
On modern system they are aliases for systemctl [verb]: sudo systemctl reboot.


text:
Q: Question about Android invisible socket connection with Burp When i see logcat below i see socket connection to server
D/cocos2d-x debug info(22591): Connect m_pTcpMainSock IP:147.139.198.147 Port:26013
D/cocos2d-x debug info(22591): send authen  IP:147.139.198.147 Port:26013
D/NuPlayerDriver( 1415): start(0xb613d040)
I/GenericSource( 1415): start
D/AudioTrack( 1415): use orig AudioTrack! mIsTimed=0 transferType=0 flags=0
D/cocos2d-x debug info(22591): Connect m_pTcpMainSock IP:147.139.197.250 Port:50004
D/cocos2d-x debug info(22591): send authen  IP:147.139.197.250 Port:50004
D/cocos2d-x debug info(22591): Connect m_pTcpAllSock IP:147.139.197.250 Port:50005
D/cocos2d-x debug info(22591): MainSocket pHead->iMsgType=[FFB2]

when i intercept through Burp suite the IP noticed before never appeared and cannot logged, any suggestion what's wrong?


text:
Q: Заполнение массива числами с плавающей точкой (Python) Нужно заполнить массив числами (допустим, десятью) с плавающей точкой, оставив два знака после запятой.
Пробовал следующее:
import random
from array import *
nums=array('f',[])
for i in range(0,10):
    nums.append(round(random.uniform(10,100),2))
for x in nums:
    print(x)

Вывод получается все равно неокруглённый:
49.16999816894531
36.060001373291016
80.7300033569336
31.809999465942383
99.93000030517578
52.029998779296875
90.86000061035156
68.77999877929688
83.80999755859375
34.470001220703125
Как исправить и почему это происходит?


text:
Q: @dynamic properties and its usage? Can anyone give me clear picture about dynamic property and its usage? y not use the usual @property everywhere?

A: Dynamic properties are used when you don't provide an implementation at compile time, but ensure that one exists at runtime. Being a dynamic language, Objective-C can respond to messages at runtime, even if the class doesn't have an implementation at compile time.
Here's a contrived example: Let's say you have a Book class, backed by an NSMutableDictionary that contains the keys title and author. However, you want Book to respond to title and author as well, and have them as properties; title and author will grab the appropriate value from the dictionary, and setTitle: and setAuthor: will change the value stored in the dictionary. You could do so with this code:
#import <Foundation/Foundation.h>

@interface Book : NSObject
{
    NSMutableDictionary *data;
}
@property (retain) NSString *title;
@property (retain) NSString *author;
@end

@implementation Book
@dynamic title, author;

- (id)init
{
    if ((self = [super init])) {
        data = [[NSMutableDictionary alloc] init];
        [data setObject:@"Tom Sawyer" forKey:@"title"];
        [data setObject:@"Mark Twain" forKey:@"author"];
    }
    return self;
}

- (void)dealloc
{
    [data release];
    [super dealloc];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
    NSString *sel = NSStringFromSelector(selector);
    if ([sel rangeOfString:@"set"].location == 0) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
    } else {
        return [NSMethodSignature signatureWithObjCTypes:"@@:"];
    }
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    NSString *key = NSStringFromSelector([invocation selector]);
    if ([key rangeOfString:@"set"].location == 0) {
        key = [[key substringWithRange:NSMakeRange(3, [key length]-4)] lowercaseString];
        NSString *obj;
        [invocation getArgument:&obj atIndex:2];
        [data setObject:obj forKey:key];
    } else {
        NSString *obj = [data objectForKey:key];
        [invocation setReturnValue:&obj];
    }
}

@end

int main(int argc, char **argv)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Book *book = [[Book alloc] init];
    printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
    book.title = @"1984";
    book.author = @"George Orwell";
    printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);

    [book release];
    [pool release];
    return 0;
}

Note the the methods are "created" at runtime via forwardInvocation:; hence, title and author are dynamic properties.
(This isn't the best example, but I think it gets the point across.)

A: @dynamic thing; is merely a way to inform the system not to generate getters/setters for the thing, that you (or someone else) will provide them for you—As in, they'll be there at runtime.
This is in contrast to @synthesize which tells the compiler to generate the getter/setter (as appropriate) for you.

A: @dynamic is (in my experience) used primarily in conjunction with Core Data and subclasses of NSManagedObject. To quote Marcus Zarra's Core Data,

By declaring them
  [attributes/relationships], we are
  telling the compiler to ignore any
  warnings associated with there
  properties because we "promise" to
  generate them at runtime. Naturally,
  if the turn up missing at runtime,
  then our application is going to
  crash.


text:
Q: Meta-annotations for JPA? I am not finding any meta-annotation facility for JPA. Any way to define a custom annotation that works as an sterotype (something like):
@MyCustomAnnotation on a field, equaling:
@ElementCollection
@CollectionTable(name="foo",joinColumns=@JoinColumn(name="foobar", referencedColumnName = "bar", nullable = true, insertable = false, updatable = false) )
@MapKeyColumn(name = "bla")
@Column(name = "bla")


text:
Q: UDP client bug - Unable to send data bytes I am writting a C# P2P Video Chat (Part of my exam on Faculty),a i am little stuck at send Data via udp. So here how it works. I have a Web_Capture library, and every time image is captured it sets PictureBox image to the captured one
 private void webCamCapture_ImageCaptured(object source, WebCam_Capture.WebcamEventArgs e)
        {
            myCamera.Image = e.WebCamImage;
            sendData(ref ipep2);   // send it immediately
        }

So then the sendData method starts sending...
private void sendData(ref IPEndPoint sender)
        {
            byte[] data;

            if (friendsClient == null)
            {
                friendsClient = new UdpClient();

            }

            MemoryStream myStream = new MemoryStream();
            myCamera.Image.Save(myStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            data = myStream.GetBuffer();
            friendsClient.Send(data, data.Length,sender);

        }

When i debug, the socket exception pops out:
 System.Net.Sockets.SocketException was unhandled by user code
  Message=The requested address is not valid in its context
  Source=System
  ErrorCode=10049
  NativeErrorCode=10049

So, does anyone have any idea, i will be thankfull if he support that idea with code, because i am nooby at c# :) thanks in advance. Marjan

A: You should specify reciever's ip and port, Here is a complete example
so you should change your implementation to
private void sendData(ref IPEndPoint reciever)
{
  byte[] data;

  Socket sending_socket = new Socket(AddressFamily.InterNetwork, ocketType.Dgram, ProtocolType.Udp);

  MemoryStream myStream = new MemoryStream();
  myCamera.Image.Save(myStream, System.Drawing.Imaging.ImageFormat.Jpeg);
  data = myStream.GetBuffer();
  sending_socket.SendTo(data, reciever);
}


text:
Q: .net core - Passing an unknown number of IProgress to class library I have a console app which uses a class library to execute some long running tasks. This is a .net core console app and uses the .net core Generic Host. I also use the ShellProgressBar library to display some progress bars.
My Hosted service looks like this
internal class MyHostedService : IHostedService, IDisposable
{
    private readonly ILogger _logger;
    private readonly IMyService _myService;
    private readonly IProgress<MyCustomProgress> _progress;
    private readonly IApplicationLifetime _appLifetime;
    private readonly ProgressBar _progressBar;
    private readonly IProgressBarFactory _progressBarFactory;

    public MyHostedService(
        ILogger<MyHostedService> logger,
        IMyService myService,
        IProgressBarFactory progressBarFactory,
        IApplicationLifetime appLifetime)
    {
        _logger = logger;
        _myService = myService;
        _appLifetime = appLifetime;
        _progressBarFactory = progressBarFactory;

        _progressBar = _progressBarFactory.GetProgressBar();        // this just returns an instance of ShellProgressBar

        _progress = new Progress<MyCustomProgress>(progress =>
        {
            _progressBar.Tick(progress.Current);
        });
    }

    public void Dispose()
    {
        _progressBar.Dispose();
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _myService.RunJobs(_progress);
        _appLifetime.StopApplication();

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

Where MyCustomProgress looks like this
public class MyCustomProgress
{
    public int Current {get; set;}
    public int Total {get; set;}
}

and MyService looks something like so (Job1, Job2, Job3 implement IJob)
public class MyService : IMyService
{
    private void List<IJob> _jobsToRun;

    public MyService()
    {
        _jobsToRun.Add(new Job1());
        _jobsToRun.Add(new Job2());
        _jobsToRun.Add(new Job3());
    }

    public void RunJobs(IProgress<MyCustomProgress> progress)
    {
        _jobsToRun.ForEach(job =>
        {
            job.Execute();

            progress.Report(new MyCustomProgress { Current = _jobsToRun.IndexOf(job) + 1, Total = _jobsToRun.Count() });
        });
    }

}

And IJob is
public interface IJob
{
    void Execute();
}

This setup works well and I'm able to display the progress bar from my HostedService by creating a ShellProgressBar instance and using the one IProgress instance I have to update it.
However, I have another implementation of IMyService that I also need to run that looks something like this
public class MyService2 : IMyService
{
    private void List<IJob> _sequentialJobsToRun;
    private void List<IJob> _parallelJobsToRun;

    public MyService()
    {
        _sequentialJobsToRun.Add(new Job1());
        _sequentialJobsToRun.Add(new Job2());
        _sequentialJobsToRun.Add(new Job3());

        _parallelJobsToRun.Add(new Job4());
        _parallelJobsToRun.Add(new Job5());
        _parallelJobsToRun.Add(new Job6());
    }

    public void RunJobs(IProgress<MyCustomProgress> progress)
    {
        _sequentialJobsToRun.ForEach(job =>
        {
            job.Execute();

            progress.Report(new MyCustomProgress { Current = _jobsToRun.IndexOf(job) + 1, Total = _jobsToRun.Count() });
        });

        Parallel.ForEach(_parallelJobsToRun, job =>
        {
            job.Execute();

            // Report progress here
        });
    }

}

This is the one I'm struggling with. when _parallelJobsToRun is executed, I need to be able to create a new child ShellProgressBar (ShellProgressBar.Spawn) and display them as child progress bars of let's say 'Parallel Jobs'.
This is where I'm looking for some help as to how I can achieve this.
Note: I don't want to take a dependency on ShellProgressBar in my class library containing MyService
Any help much appreciated.

A: I am a little confused by your description, but let's see if I understand what you are up to.  So if you wrap all of this in a class, then taskList1 and taskList2 could be class variables.  (By the way taskList1/2 should be named better: say parallelTaskList and whatever . . . anyway.)  Then you could write a new method on the class CheckTaskStatus() and just iterate over the two class variables.  Does that help or have I completely missed your question?

A: Can you modify it like this?

public Task<ICollection<IProgress<int>>> StartAsync(CancellationToken cancellationToken)
{
    var progressList = _myServiceFromLibrary.RunTasks();

    return Task.FromResult(progressList);
}

public ICollection<IProgress<int>> RunTasks()
{
    var taskList1 = new List<ITask> { Task1, Task2 };
    var plist1 = taskList1.Select(t => t.Progress).ToList();
    var taskList2 = new List<ITask> { Task3, Task4, Task5 }:
    var plist2 = taskList2.Select(t => t.Progress).ToList();

    taskList1.foreach( task => task.Run() );

    Parallel.Foreach(taskList2, task => { task.Run() });

    return plist1.Concat(plist2).ToList();
}

Task.Progress there is probably a progress getter. realistically IProgress should probably be injected via Tasks constructors. But the point is your public interface doesn't accept list of tasks, thus it should just return collection of progress reports.
How to inject progress reporters into your tasks is a different story that depends on tasks implementations and it may or may not be supported. out of the box.
However what you probably should do is to supply progress callback or progress factory so that progress reporters of your choice are created:

public Task StartAsync(CancellationToken cancellationToken, Action<Task,int> onprogress)
{
    _myServiceFromLibrary.RunTasks(onprogress);

    return Task.CompletedTask;
}

public class SimpleProgress : IProgress<int>
{
    private readonly Task task;
    private readonly Action<Task,int> action;
    public SimpleProgress(Task task, Action<Task,int> action)
    {
        this.task = task;
        this.action = action;
    }

    public void Report(int progress)
    {
        action(task, progress);
    }
}

public ICollection<IProgress<int>> RunTasks(Action<Task,int> onprogress)
{
    var taskList1 = new List<ITask> { Task1, Task2 };
    taskList1.foreach(t => t.Progress = new SimpleProgress(t, onprogress));
    var taskList2 = new List<ITask> { Task3, Task4, Task5 }:
    taskList2.foreach(t => t.Progress = new SimpleProgress(t, onprogress));

    taskList1.foreach( task => task.Run() );

    Parallel.Foreach(taskList2, task => { task.Run() });
}

you may see here, that it really is mostly question about how your tasks are going to call IProgress<T>.Report(T value) method.

A: Honestly I would just use an event in your task prototype.
It's not really clear exactly what you want because the code you posted doesn't match the names you then reference in your question text... It would be helpful to have all the code (the RunTasks function for example, your IProgress prototype, etc).
Nevertheless, an event exists specifically to signal calling code. Let's go back to the basics. Let's say you have library called MyLib, with a method DoThings().
Create a new class that inherits from EventArgs, and that will carry your task's progress reports...
public class ProgressEventArgs : EventArgs
{
    private int _taskId;
    private int _percent;
    private string _message;

    public int TaskId => _taskId;
    public int Percent => _percent;
    public string Message => _message;

    public ProgressEventArgs(int taskId, int percent, string message)
    {
        _taskId = taskId;
        _percent = percent;
        _message = message;
    }
}

Then on your library's class definition, add an event like so:
public event EventHandler<ProgressEventArgs> Progress;

And in your console application, create a handler for progress events:
void ProgressHandler(object sender, ProgressEventArgs e)
{
    // Do whatever you want with your progress report here, all your
    // info is in the e variable
}

And subscribe to your class library's event:
var lib = new MyLib();
lib.Progress += ProgressHandler;
lib.DoThings();

When you are done, unsubscribe from the event:
lib.Progress -= ProgressHandler;

In your class library, now you can send back progress reports by raising the event in your code. First create a stub method to invoke the event:
protected virtual void OnProgress(ProgressEventArgs e)
{
    var handler = Progress;
    if (handler != null)
    {
        handler(this, e);
    }
}

And then add this to your task's code where you want it:
OnProgress(new ProgressEventArgs(2452343, 10, "Reindexing google..."));

The only thing to be careful about is to report progress sparingly, because each time your event fires it interrupts your console application, and you can really bog it down hard if you send 10 million events all at once. Be logical about it.

A: Alternate way; If you own the code IProgress<T> and Progress
IProgress<T>
{
   IProgress<T> CreateNew();
   Report(T progress);
}

Progress<T> : IProgress<T>
{
  Progress(ShellProgressClass)
  {
    // initialize progressBar or span new
  }
  ....
   IProgress<T> CreateNew()
   {
     return new Progress();
   }
}

you can later improvise to have one big progressBar (collection of Sequential or Parallel) and what not

A: Your MyService could have a dependency similar to:
public interface IJobContainer
{
    void Add(IJob job);

    void RunJobs(IProgress<MyProgress> progress, Action<IJob>? callback = null); // Using an action for extra work you may want to do
}

This way you don't have to worry about reporting progress in MyService (which doesn't feel like it should be MyService's job anyway. The implementation could look something like this for the parallel job container:
public class MyParallelJobContainer
{
    private readonly IList<IJob> parallelJobs = new List<IJob>();

    public MyParallelJobContainer()
    {
        this.progress = progress;
    }

    public void Add(IJob job) { ... }

    void RunJobs(IProgress<MyProgress> progress, Action<IJob>? callback = null)
    {
        using (var progressBar = new ProgressBar(options...))
        {
            Parallel.ForEach(parallelJobs, job =>
            {
                callback?.Invoke(job);
                job.Execute();
                progressBar.Tick();
            })
        }
    }
}

MyService would then look like this:
public class MyService : IMyService
{
    private readonly IJobContainer sequentialJobs;
    private readonly IJobContainer parallelJobs;

    public MyService(
        IJobContainer sequentialJobs,
        IJobContainer parallelJobs)
    {
        this.sequentialJobs = sequentialJobs;
        this.parallelJobs = parallelJobs;

        this.sequentialJobs.Add(new DoSequentialJob1());
        this.sequentialJobs.Add(new DoSequentialJob2());
        this.sequentialJobs.Add(new DoSequentialJob3));

        this.parallelJobs.Add(new DoParallelJobA());
        this.parallelJobs.Add(new DoParallelJobB());
        this.parallelJobs.Add(new DoParallelJobC());
    }

    public void RunJobs(IProgress<MyCustomProgress> progress)
    {
        sequentialJobs.RunJobs(progress, job =>
        {
             // do something with the job if necessary
        });

        parallelJobs.RunJobs(progress, job =>
        {
             // do something with the job if necessary
        });
    }

The advantage of this way is that MyService only has one job and doesn't have to worry about what you do once the job is completed.

A: From my understanding of your issue the question is how do you display progress across both completion of the synchronous jobs and parallelized jobs.
In theory the parallel jobs could start and finish at the same time, so you could treat the parallel jobs as a single job. Instead of using the count of sequential jobs as your total, increase that number by one. This might be satisfactory for a small number of parallel jobs.
If you want to add progress between the parallel jobs, you will need to handle multi-threading in your code because the parallel jobs will be running concurrently.
object pJobLock = new object();
int numProcessed = 0;
foreach(var parallelJob in parallelJobs)
{
    parallelJob.DoWork();
    lock (pJobLock)
    {
        numProcessed++;
        progress.Report(new MyCustomProgress { Current = numProcessed, Total = parallelJobs.Count() });
    }
}


text:
Q: Spring data: i can't save my relation model in my db I have some problem with JPA in my Spring Boot API REST.
I have a model Panier, and inside, a model LignePanier.
When i try to save my panier with panierRepository.save() without lignePanier, no problem, my panier is persisted in my db.
But if i have some lignePanier in my model Panier, JPA doesnt persisted the LignePanier and throw an exception:
"ERROR: relation "panier_lignes_panier" does not exist".
If i creat directly the relation in my db, if i try to persist, it say that i the panier_id of the relation is null (but not in my code if i use a breakpoint).
@Entity
public class Panier {

    /**
     * Id unique référençant le panier
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    /**
     * UUID du client permettant de référencer son panier de manière unique.
     */
    @NotNull
    private String clientUuid;

    /**
     * Liste des évenements enregistrés dans le panier de l'utilisateur.
     */
    @OneToMany(cascade = {CascadeType.ALL})
    List<LignePanier> lignesPanier;

    public Panier () {
        this.lignesPanier = new ArrayList<LignePanier>();
    }

    public Panier (String clientUuid, List<LignePanier> lignesPanier) { this.clientUuid = clientUuid; this.lignesPanier = lignesPanier; }

    public Integer getId() { return this.id; }

    public void setId(Integer id) { this.id = id; }

    public String getClientUuid() {
        return clientUuid;
    }

    public void setClientUuid(String clientUuid) {
        this.clientUuid = clientUuid;
    }

    public List<LignePanier> getLignesPanier() {
        return lignesPanier;
    }

    public void setLignesPanier(List<LignePanier> lignesPanier) {
        this.lignesPanier = lignesPanier;
    }

    public void addLignePanier(LignePanier lignePanier) {
        if(!this.lignesPanier.contains(lignePanier))
            this.lignesPanier.add(lignePanier);
    }

    @Override
    public String toString() {
        return "Panier{" +
                "id=" + id +
                ", clientUuid='" + clientUuid + '\'' +
                ", lignesPanier=" + lignesPanier +
                '}';
    }
}

    package com.wildadventures.mscommande.models;

import javax.persistence.*;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * Model représentant les lignes d'un panier utilisateur
 */
@Entity
public class LignePanier {

    /**
     * id référençant la ligne de panier.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    /**
     * Référence de l'évenement ajouté au panier
     */
    @NotNull
    private Integer evenementId;

    /**
     * Nombre de place à réserver pour l'évenement
     */
    @NotNull
    @Min(value = 1, message = "Le nombre de participant minimum et de 1")
    private Integer nbPersonne;

    /**
     * Nom de l'évenement référencé.
     */
    @NotNull
    private String aventureNom;

    /**
     * Nombre de places réservées pour l'évenement.
     */
    @NotNull
    @Min(value = 0, message = "La valeur unitaire hors taxe ne peux être inferieure à Zero.")
    private Float prixUnitaireHt;

    /**
     * Date de début de l'évenement
     */
    @NotNull
    private Date dateDebut;

    /**
     * Date de fin de l'évenement
     */
    @NotNull
    private Date dateFin;

    public LignePanier () {}

    public LignePanier(int id, int evenementId, int nbPersonne, String aventureNom, float prixUnitaireHt, Date dateDebut, Date dateFin) {
        this.id = id;
        this.evenementId = evenementId;
        this.nbPersonne = nbPersonne;
        this.aventureNom = aventureNom;
        this.prixUnitaireHt = prixUnitaireHt;
        this.dateDebut = dateDebut;
        this.dateFin = dateFin;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getEvenementId() {
        return evenementId;
    }

    public void setEvenementId(Integer evenementId) {
        this.evenementId = evenementId;
    }

    public Integer getNbPersonne() {
        return nbPersonne;
    }

    public void setNbPersonne(Integer nbPersonne) {
        this.nbPersonne = nbPersonne;
    }

    public String getAventureNom() {
        return aventureNom;
    }

    public void setAventureNom(String aventureNom) {
        this.aventureNom = aventureNom;
    }

    public Float getPrixUnitaireHt() {
        return prixUnitaireHt;
    }

    public void setPrixUnitaireHt(Float prixUnitaireHt) {
        this.prixUnitaireHt = prixUnitaireHt;
    }

    public Date getDateDebut() {
        return dateDebut;
    }

    public void setDateDebut(Date dateDebut) {
        this.dateDebut = dateDebut;
    }

    public Date getDateFin() {
        return dateFin;
    }

    public void setDateFin(Date dateFin) {
        this.dateFin = dateFin;
    }
}

    package com.wildadventures.mscommande.managers;

import com.wildadventures.mscommande.models.LignePanier;
import com.wildadventures.mscommande.models.Panier;
import com.wildadventures.mscommande.repositories.LignePanierRepository;
import com.wildadventures.mscommande.repositories.PanierRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class PanierManager {

    @Autowired
    private PanierRepository panierRepository;

    @Autowired LignePanierRepository lignePanierRepository;

    /**
     * Ajoute une nouvelle ligne de panier au panier de l'utilisateur.
     */
    public void ajouterLignePanier(Panier panier, LignePanier lignePanier){

        panier.getLignesPanier().add(lignePanier);
        this.savePanier(panier);
    }

    /**
     * Enregistre le panier pour l'utilisateur ayant comme uuid clientUuid.
     *
     * @param panier le panier de l'utilisateur à créer
     *
     * @return le panier créé
     */
    private Panier savePanier(Panier panier){

        return panierRepository.saveAndFlush(panier);
    }

    /**
     * Récuperer un panier en fonction de son clientUuid
     *
     * @param clientUuid l'uuid du client
     *
     * @return le panier si il existe
     */
    public Panier recupererPanier(String clientUuid) {
        return this.panierRepository.findByClientUuid(clientUuid);
    }

    /**
     * Créer un nouveau panier pour l'utilisateur
     *
     * @param clientUuid l'uuid de l'utilisateur
     *
     * @return le panier créé
     */
    public Panier creerPanier(String clientUuid) {
        Panier panier = new Panier(clientUuid, new ArrayList<LignePanier>());
        return this.savePanier(panier);
    }
}

Thx for your responses.

A: If you want to model the 1-N unidirectional relation as a FK in the element (rather than using a join table) then you add
@JoinColumn

to the lignesPanier field (and optionally define what the FK column name is if you don't want the default JPA FK column naming). As per these docs.
Since you don't define what schema you have then not much more to add


text:
Q: How can you load a page fragment with jQuery in Laravel 4? I like to load a page fragment using jQuery like this:
$(".title" + nid ).click(function() {

   $('.loadNest').load("{{ View::make('postDetails') }}");

});

Is this possible? I have a list of post titles on the left of my page. When a user clicks on a post title I want to load a page fragment on the right with all the details of the post. The author, the comments, etc...all on the same page.

A: jQuery's load method is actually an AJAX call, so you'd have to set up a route that would output the view. Something like this:
Route::get('ajax/postDetails', array(
    'as' => 'postDetailsView', // This is the name of your route
    'do' => function () {
        return View::make('postDetails');
    }
));

Then, in your code, you'd have:
$('.title' + nid).click(function() { // Use the route's name you setup
    $('.loadNest').load('{{ URL::route('postDetailsView') }}');
});

A: I solved this issue by using this jQuery code:
$(".nestTitle").click(function(e){
    $.ajax({
      url: "getNest",
      context: document.body
    }).done(function(fragment) {
      $(".loadNest").html(fragment);
    });
});

Which called my route like this:
Route::get('getNest', array('as' => 'getNest', 'uses' => 'NestsController@getNest'));

Then in my controller I did this:
    $nid = 105;
    $uid = Auth::user()->id;
    $nests = Nest::with('user')
    ->where('user_id', '=', $uid)
    ->where("id", $nid)
    ->get();

    return View::make('nestItems', compact('nests'));

I just need to pass the parameters around and I should be good. Thanks for your help Raphael.

A: A clean solution that I use is to use asset in your javascript
$(".title" + nid ).click(function() {

   $('.loadNest').load("{{ asset('postDetails') }}");

});

and setup the Route as
Route::get('/postDetails', function() {
    return View::make('postDetails');
});


text:
Q: How to handle functions that return a Result<(), E>? What is the best way to call a function is when it returns a Result with a Unit Type in Rust?
For example I have this function to copy some text to clipboard:
use anyhow::Result;
use cli_clipboard::{ClipboardContext, ClipboardProvider};

fn copy_to_clipboard(text:&String) -> Result<()>{
    let mut ctx = ClipboardContext::new()?;
    ctx.set_contents(text.to_owned())?;
    Ok(())
}

Then when I call this function I'd like to do this, but it creates a compiler warning "unused Result that must be used":
copy_to_clipboard(selected_value);

So I've ended up using the following instead which removes the warning:
_ = copy_to_clipboard(selected_value);

Just wondering if there is a better/more idiomatic way to do this?

A:
Just wondering if there is a better/more idiomatic way to do this?

Well Depends.
Since the function returns a Result, it's signaling that it can fail. The () means it has no useful return value if it succeeds (this is common for functions with only side-effects).
So the question is really what you want to do if (when?) the function fails. What you've said here is "I don't care and I want to ignore it", which is perfectly valid (though you may want to document the reasoning via a comment).
Other possibilities are handling the error (e.g. recovering, displaying an error message, ...), bubbling the error up to your own caller, panic-ing (using unwrap or expect), ...


text:
Q: QRadar CE on Google Cloud Platform (GCP) network issue I've installed QRadar Community Edition on a Google Cloud VM but I can't figure out how to make the internal networking works.
Here's my issue: I got some VMs on the same subnet as QRadar, one of them is a firewall connected via VPN to another infrastructure, every machine is able to ping the others but QRadar's one. GCP gives you IPs with a /32 mask and, obviously, the gateway is outside that subnet. Before installing QRadar the VM is able to ping and being pinged but after the installation it is unable to ping anything, but it's pingable from the other VMs.
I've tried to change network settings before the installation, changing the mask to /24. The result is that after the installation the machine is able to ping only the gateway, internet, but it's unable to ping the other VMs on the subnet, and it isn't pingable from the other VMs.
I've also tried to use the command qchange_netsetup but it doesn't work on GCP serial console because the screen goes to black and I can't see anything.


text:
Q: Draggable and customize DIV's In my web page, rumonet.pt/index2.php  I have the 3 'tabs', they are DIV's, and they can be moved with jquery. If u want to try it, just select the title, and move them arround...
What i needed to do, is to when you move it to top of another, the other DIV gets to the side, allowing people to order them at their will...
i know i have to use
   $('#noticias #titulo').bind('mousemove mousedown', function(){

);

and the offset() vars...
But i've been trying around for a long time to make this to work, but nothing...
can anyone give me a hint, or some lights about the problem? :ss

A: Have you had a look at dragable() and sortable() ? Might just do the trick you're after
http://jsfiddle.net/rniemeyer/QWgRF/


text:
Q: Trying to pass GregorianDate to constructor in Java I'm new to java and having a really hard time understanding what I am doing wrong here. I'm still having a hard time fully understanding abstract classes, and interfaces so I think that's where my problem is coming from.
I'm trying to create a class that will allow me to create party objects, I'm able to instantiate all variables except for the date. Here is what I have so far:
public class Main {

    public static void main(String[] args) {

         ...

         Party joes = new Party("Joes party", "Joe", "Joe's Place",
                        new GregorianCalendar(2012,10,10));
         joes.printParty();
    }
}

public class Party {

    //attributes of party
    private String partyName;
    private String partyHost;
    private String location;
    private GregorianCalendar partyTime;

      public Party(String partyName, String partyHost, String location, GregorianCalendar partyTime){
        this.partyName = partyName;
        this.partyHost = partyHost;
        this.location = location;
        this.partyTime = partyTime;
      }
}

When I print this out I get:
"Joes party is going to be hosted by Joe at Joe's Place on:
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true..."

A: What is being displayed is the result of the toString() method defined in the class Calendar.  This is almost never what someone wants to display when converting a date to a string, but this is how the Calendar class was defined.
Luckily, there are facilities in the Java Platform library that allow you to format your dates in exactly the form which you'd like to display ... so that's what you'll need to do.  Instead of passing a reference to your GregorianCalendar instance to the print method, you'll create your own formatted String instance, using the SimpleDateFormat class for example, and then pass the reference to that string to the print method.


text:
Q: How to achieve eclipse Progress bar with Details button like eclipse workspace job I am working on Eclipse RCP application, I want to achieve the eclipse workspace job with a Dialog with the buttons like "Run in Background", "Cancel" and "Details". I tried all the options but all my efforts did not bear fruit. However I am able to create ProgressBar with ProgressMonitor dialog with cancel button. I want to achieve like the image given below. Please help me in this regard. I also went through the following link along with other links. I also tried with IProgressService but it did not work. Currently I am working in Eclipse Photon version.
https://www.eclipse.org/articles/Article-Concurrency/jobs-api.html

I provide below the code for workspace job
public void show11() {
Job job =
    new WorkspaceJob("name") {
      @Override
      public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {

        for (int i = 0; i < 10; i++) {
          System.out.println("This is a MYJob");
          try {
            TimeUnit.SECONDS.sleep(1);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          monitor.subTask("Copying file " + (i + 1) + " of " + "workload" + "...");
        }

        return Status.OK_STATUS;
      }
    };

  job.setUser(true);
  job.schedule();

  try
   {
     job.join();
   }
  catch (InterruptedException e)
   {
     //
   }

}

A: Finally I solved this problem. It is assumed that "Run in Background" is set by default for eclipse RCP application. In my case I had to switch of this option from Eclipse, still it did not work. I have done manually to make it false in my eclipse rcp. I provide below. the code.
WorkbenchPlugin.getDefault().getPreferenceStore().setValue("RUN_IN_BACKGROUND", false);

Those who are facing this kind of problem, they can set this value programmatically while developing eclipse rcp application.
I would like to thank Greg Sir (greg-449) for providing some tips and information.


text:
Q: How i can merge or concatenate array of arrays? I have the following array of arrays:
var array = [
[[1, 1, 1],[11, 11, 11],[111,111,111]],
[[2, 2, 2],[22, 22, 22],[222,222,222]]
]

How i can achieve a new array as below:
var newArray = [[1,1,1,2,2,2],[11,11,11,22,22,22],[111,111,111,222,222,222]]

What i have tried so far:
var sub= [];
var sub2= [];

for(i=0; i<array.length; i++){
var val1= array[i][0]
sub.push(val1)

        for(k=0; k<array[i].length; k++){
            var val2 = val1.concat(array[i][k])
            sub2.push(sub)
    }
}

With console error: [[[1, 1, 1], [2, 2, 2]], [circular object Array], [circular object Array], [circular object Array],
Any solution will be appreciated!
Thank you!

A: You could reduce the array by mapping the inner arrays.

const
    array = [[[1, 1, 1], [11, 11, 11], [111, 111, 111]], [[2, 2, 2], [22, 22, 22], [222, 222, 222]]],
    result = array.reduce((a, b) => a.map((v, i) => [...v, ...b[i]]));

console.log(result);


text:
Q: declare/initialize big array as global/static/local I figure there are 3 parameters that affect the executable size when defining big data-structures, for example arrays.
1. scope where it is defined: global/local
2. static or not
3. initialized or not
so for example,
A. - image size: 77KB
int main (void) {

    /*static*/int array[100000] = {0};
    printf("%d", array[100]); return 0;
}

B. - 77KB
int main (void) {

    static int array[100000] = {0};
    printf("%d", array[100]); return 0;
}

C. - 467KB
int main (void) {
    static int array[100000] = {1};
    printf("%d", array[100]); return 0;
}

D. - 77KB
int main (void) {
    /*static*/ int array[100000] = {1};
    printf("%d", array[100]); return 0;
}

E. - 77KB
static int array[100000] = {0};

int main (void) {
    printf("%d", array[100]); return 0;
}

F. - 467KB
static int array[100000] = {1};

int main (void) {
    printf("%d", array[100]); return 0;
}

G. - 467KB
/*static*/ int array[100000] = {1};

int main (void) {
    printf("%d", array[100]); return 0;
}

H. - 77KB
/*static*/ int array[100000] = {0};

int main (void) {
    printf("%d", array[100]); return 0;
}

It's easy to see why local array (initialize or not) is 77KB as long as it's not static. (case A. and B.)
However, static and local, even if not initialized is still 467KB (case B).
how come?
regarding the global definition:
static, and un-initialized is 77KB (case E) . how come?
I hope you can put some order and explain what happens behind the scenes...


text:
Q: how to put different sizes of images inside carousel in Bootstrap 4? I'm having trouble putting different size of images inside carrousel in Bootstrap 4. How can I put different sizes of images inside this carousel.
For an example, I want to put different sizes of images as in the below code. In the current situation, when I do that it just takes that images size.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

      Previous

      Next

A: Reason behind this
Let's have a look at what you're doing here first:

Have a close look at the classes you added on the image element, d-block means the image display will be set to block and w-100 means the width will be 100%. Read more here.
Now that your second (dog) image is way too big in height compared to width, and there is no max-height set, it will expand the carousel.
Solution:
Firstly let's remove the w-100 class from the dog image item.

Now let's add a little css:
.carousel-item img {
  margin: 0 auto; /* this will align the image to center. */
  width: auto; /* for those images which don't have a width specified, but has a max-height will be auto adjusted */
}

As commented above, you already understand which property is going to handle what values.
It's time to check the height of the carousel at the initial time of page load, So, whenever the document is ready, we check the height of the carousel with the #carouselwithIndicators selector. and then we apply this height value to all the images in the carousel.
Here is the JS:
$(document).ready(function(){
  console.log($('#carouselwithIndicators').css('height')); // check the initial height of the carousel;

  // now apply this height as a max-height on all the image items; css will handle the rest;
  $('#carouselwithIndicators').find('.carousel-item img').css('max-height', $('#carouselwithIndicators').css('height'))
});

Snippet
Have a look at the snippet now:

$(document).ready(function(){
  console.log($('#carouselwithIndicators').css('height')); // check the initial height of the carousel;

  // now apply this height as a max-height on all the image items; css will handle the rest;
  $('#carouselwithIndicators').find('.carousel-item img').css('max-height', $('#carouselwithIndicators').css('height'))
});
.carousel-item img {
  margin: 0 auto;
  width: auto;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

      Previous

      Next


text:
Q: Pasando múltiples parámetros de la expresión regular de una URL a la definición de la vista en Django Tengo el siguiente modelo llamado LodgingOffer, mediante el cual es posible crear una oferta de alojamiento y detallar sus datos:
class LodgingOffer(models.Model):

    # Foreign Key to my User model
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    ad_title = models.CharField(null=False, blank=False,
        max_length=255, verbose_name='Título de la oferta')

    slug = models.SlugField(max_length=100, blank=True)

    country = CountryField(blank_label='(Seleccionar país)', verbose_name='Pais')

    city = models.CharField(max_length=255, blank = False, verbose_name='Ciudad')

    def __str__(self):
        return "%s" % self.ad_title

    pub_date = models.DateTimeField(auto_now_add=True,)

    def get_absolute_url(self):
        return reverse('host:detail', kwargs = {'slug' : self.slug })

# I assign slug to offer based in ad_title field,checking if slug exist
def create_slug(instance, new_slug=None):
    slug = slugify(instance.ad_title)
    if new_slug is not None:
        slug = new_slug
    qs = LodgingOffer.objects.filter(slug=slug).order_by("-id")
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" % (slug, qs.first().id)
        return create_slug(instance, new_slug=new_slug)
    return slug

# Brefore to save, assign slug to offer created above.
def pre_save_article_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = create_slug(instance)

pre_save.connect(pre_save_article_receiver, sender=LodgingOffer)

Para este modelo, tengo una vista de detalle llamada HostingOfferDetailView en la cual muestro los datos de una oferta de un objeto LodgingOffer
Un importante objetivo que quiero perseguir y por el cual formulo esta pregunta es que en la vista de detalle de un objeto LodgingOffer yo debo poder contactar al dueño de esa oferta (objeto LodgingOffer - usuario quien lo creó-) para que otro usuario interesado pueda aplicar a ella.
Para este propósito, tengo la función contact_owner_offer() la cual es una función en donde envío un correo electrónico al dueño de esta oferta.
Todo esto lo estoy haciendo en la vista de detalle HostingOfferDetailView de esta manera:
class HostingOfferDetailView(UserProfileDataMixin, LoginRequiredMixin, DetailView):
    model = LodgingOffer
    template_name = 'lodgingoffer_detail.html'
    context_object_name = 'lodgingofferdetail'

    def get_context_data(self, **kwargs):
        context = super(HostingOfferDetailView, self).get_context_data(**kwargs)
        user = self.request.user

        # LodgingOffer object
        #lodging_offer_owner = self.get_object()

        # Get the full name of the lodging offer owner
        lodging_offer_owner_full_name = self.get_object().created_by.get_long_name()

        # Get the lodging offer email owner
        lodging_offer_owner_email = self.get_object().created_by.email

        # Get the lodging offer title
        lodging_offer_title = self.get_object().ad_title

        # Get the user interested email in lodging offer
        user_interested_email = user.email

        # Get the user interested full name
        user_interested_full_name = user.get_long_name()

        context['user_interested_email'] = user_interested_email
        context['lodging_offer_owner_email'] = lodging_offer_owner_email

        # Send the data (lodging_offer_owner_email
        # user_interested_email and lodging_offer_title) presented
        # above to the contact_owner_offer function
        contact_owner_offer(self.request, lodging_offer_owner_email,
                    user_interested_email, lodging_offer_title)

        return context

Mi función contact_owner_offer recibe estos parámetros de oferta y envia el correo al dueño de la oferta o quien la publicó, de la siguiente manera:
def contact_owner_offer(request, lodging_offer_owner_email, user_interested_email, lodging_offer_title):
    user = request.user
    print("a", lodging_offer_owner_email, user_interested_email)
    if user.is_authenticated:
        print('Send email')
        mail_subject = 'Interesados en tu oferta'

        context = {
            'lodging_offer_owner_email': lodging_offer_owner_email,
            # usuario dueño de la oferta  TO

            'offer': lodging_offer_title,
            # oferta por la que se pregunta

            'user_interested_email': user_interested_email,
            # usuario interesado en la oferta

            'domain': settings.SITE_URL,
            'request': request
        }

        message = render_to_string('contact_user_own_offer.html', context)
        #to_email = lodging_offer_owner.email,

        send_mail(mail_subject, message, settings.DEFAULT_FROM_EMAIL,
              [lodging_offer_owner_email], fail_silently=True)

        # email = EmailMessage(mail_subject, message, to=[to_email])
        # email.send()
    # return redirect('articles:article_list')

Esto lo he hecho a modo de prueba y hasta aquí todo resulta como he querido, y el resultado es que cuando entro al URL de detalle de una oferta objeto LodgingOffer, se envía un correo electrónico al dueño de dicha oferta.
Lo que deseo es que en mi template de detalle de oferta, tener un botón el cual diga "Contactar al dueño de la oferta" y que cualquier usuario que lo presione, acto seguido se envíe un correo electrónico al dueño de la oferta.
Para esto, he procedido a definir un URL que llame a la función contact_owner_offer() y que sea llamado desde el atributo href de un boton en mi template:
El URL, (acorde a mi entendimiento y es aquí en donde reside la duda y el motivo de mi pregunta) lo he definido acorde al número de parámetros que recibe la función contact_owner_offer()
Esto significa que mi URL debe recibir:

*

*El email del propietario de la oferta

*El email del usuario interesado en la oferta

*El titulo de la oferta, aunque para esto estoy enviándole el slug de ese título, no se si eso sea correcto
Entoces, acorde a lo anterior, he creado este URL:
url(r'^contact-to-owner/(?P<email>[\w.@+-]+)/from/'
    r'(?P<interested_email>[\w.@+-]+)/(?P<slug>[\w-]+)/$',
    contact_owner_offer, name='contact_owner_offer'),

Seguidamente, en mi template, genero un boton html en donde llamo a esta URL enviándole sus respectivos parámetros:

        Contactar

Lo que me sucede es que cuando entro al template de detalle de oferta y hago clic en el boton de Contactar referenciando inmediatamente anterior, tengo el siguiente mensaje de error:
TypeError: contact_owner_offer() got an unexpected keyword argument 'email'
[10/Oct/2017 01:04:06] "GET /host/contact-to-owner/botibagl@gmail.com/from/ces@ces.edu.co/apartacho/ HTTP/1.1" 500 77979

Lo que no comprendo, es porque me dice que mi URL no espera un argumento llamado email que es en donde le paso el parámetro email=lodging_offer_owner_email a través del boton en el template.
Agradezco cualquier orientación
ACTUALIZACIÓN
Acorde a las recomendaciones dadas he cambiado ligeramente la definición de mi URL especificando el nombre del argumento o keyword argument que estoy pasando.
Mi función es:
def contact_owner_offer(request, lodging_offer_owner_email, user_interested_email, slug):
    user = request.user
    print("a", lodging_offer_owner_email, user_interested_email, slug)
    if user.is_authenticated:
        print('Send email')
        mail_subject = 'Interesados en tu oferta'

        context = {
            'lodging_offer_owner_email': lodging_offer_owner_email,
            # usuario dueño de la oferta  TO

            'offer': slug,
            # oferta por la que se pregunta

            'user_interested_email': user_interested_email,
            # usuario interesado en la oferta

            'domain': settings.SITE_URL,
            'request': request
        }

        message = render_to_string('contact_user_own_offer.html', context)
        #to_email = lodging_offer_owner.email,

        send_mail(mail_subject, message, settings.DEFAULT_FROM_EMAIL,
                  [lodging_offer_owner_email], fail_silently=True)

La definición de mi URL ha quedado así:
url(r'^contact-to-owner/(?P<lodging_offer_owner_email>[\w.@+-]+)/from/'
    r'(?P<interested_email>[\w.@+-]+)/(?P<slug>[\w-]+)/$',
    contact_owner_offer,
    name='contact_owner_offer'
),

En mi template html ha quedado asi, el valor del parámetro slug, lo tomo a través del context_object_name que defino en la clase HostingOfferDetailView por lo cual queda lodgingofferdetail.slug:

        Contactar

Y al posicionarme sobre el botón obtengo en el url el valor de los parámetros que estoy manejando

Solo que cuando le doy clic a ese botón, vuelvo al mismo error:
Traceback:

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/bgarcial/.virtualenvs/hostayni/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

Exception Type: TypeError at /host/contact-to-owner/botibagl@gmail.com/from/fabiola.quimica@gmail.com/apartacho/
Exception Value: contact_owner_offer() got an unexpected keyword argument 'interested_email'

A: Me parece que el problema aquí es similar a tu pregunta anterior. Tienes que usar los mismos parámetros en la definición de la vista:
def contact_owner_offer(request, email, interested_email, slug):
    ....

No te compliques, es como crear una función cualquiera y le pases los parámetros equivocados:
>>> def foo(bar):
...     print bar
...
>>> foo(bar=10)
10
>>> foo(bar2=10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'bar2'

Y eso es lo que hace {% url %}, simplemente le pasa los parámetros a la función, pero estos parámetros deben llamarse igual.


text:
Q: Searching an array for a course Here is the algorithm but I am having difficulty with the decipher process
:
set flag equal to false
set index equal to 0

WHILE(index is less than number of courses in array AND flag == false)
    extract substring
    IF(string1.equals(string2) == true) THEN //course found
        set flag to true
    ELSE
        increment index
    END IF
END WHILE

IF flag == false THEN
    display message the course name was not found
ELSE
    course name found at position index
END IF

And here is my code:
public void searchCourse(String courseName)
{
    int index;
    String extract;
    boolean notFound = false;
    index = 0;
    while(index < SIZE)
    {
        extract = schedule[index].charAt(0,6);
        if (courseName == extract){

        }
        else {
            index ++;
        }
        if ( notFound == false){
            System.out.println("Course Not Found");
        }
        else{
            System.out.println("Course Found at: " + index);
        }
    }
}

A: The pseudo code seems needlessly complex.
This will suffice:
public void searchCourse(String courseName) {
    for(int i = 0; i < schedule.length; i++) {
        if(courseName.equals(schedule[i].substring(0, 6))) {
            System.out.println("Course Found at: " + i);
            return;
        }
    }

    System.out.println("Course Not Found");
}

Regardless, a correct translation would look like this:
public void searchCourse(String courseName) {
    boolean flag = false;
    int index = 0;

    while(index < schedule.length && !flag) {
        String extract = schedule[index].substring(0,6);
        if (courseName.equals(extract)){
            flag = true;
        } else {
            index++;
        }
    }

    if (!flag){
        System.out.println("Course Not Found");
    } else {
        System.out.println("Course Found at: " + index);
    }
}

A: Your code has to be similar as the pseudo-code.

*

*In the pseudo-code, the while loop has two conditions, your code only has one. You use && in java to make a AND, so it becomes && ! notFound

*In your first if condition, you have to set the flag to true. It's a simple affectation notFound = true
Btw, the flag should be found instead of notFound, but it does not change anything, except maybe the readability.

A: Here correct code
 public void searchCourse(String courseName)
 {
    int index;
    String extract;
    boolean notFound = false;
    index = 0;
    while(index < SIZE)
    {
        notFound = false;
        extract = schedule[index].charAt(0,6);
        if (courseName == extract){
               notFound = true;
        }
        if ( notFound == false){
            System.out.println("Course Not Found");
        }
        else{
            System.out.println("Course Found at: " + index);
        }
        index ++;
    }
}


text:
Q: jQuery - Hide show not working properly in Chrome (Works only once) Just wrote a jquery to show a comment button, when click on the textarea. Hide comment button clicking on somewhere else in the screen. Its working fine in Firefox. But in Chrome it working only once. When I click on textarea again the submit button is not showing, its still hidden.
$(document).on('click', ".comment_txt, .comment_btn", function() {
  var post_id = $(this).attr("post-id");
  $("#comment_btn_div_"+post_id).show();
});
$('body').click(function() {
  $(".comment_btn").hide()
});

<form class="comment_submit" action="http://localhost:3000/api/v2/posts/48774/comment" data-post-id="48774" id="comment_form_48774">
    <textarea post-id="48774" id="comment_txt_48774" placeholder="Comment" cols="40" rows="1" class="width100 comment_txt"></textarea>
    <div id="comment_btn_div_48774" class="right comment_btn" post-id="48774" style="display:none">
      <button onclick="$(this).text('commenting...')" class="btn btn-small btn-info right" id="comment_btn_48774" type="submit">Comment</button>
    </div>
</form>

Not sure why this is not working in Chrome. There are many form in my page. So I have did  $(".comment_btn").hide() on body click. In order to show a particular comment button i'm using this code $("#comment_btn_div_"+post_id).show();
Update:
After the comment button is hidden, Even when i do a $("#comment_btn_div_23232").show() from firebug console. Its not showing the div.
Update 2 (testing with alert):
$(document).on('click', ".comment_txt, .comment_btn", function() {
  alert("commenttext area clicked");
  $(".comment_btn").show()
});
$('body').click(function() {
  alert("body clicked");
  $(".comment_btn").hide()
});

*

*Clicked textarea, got alert a. body clicked b. commenttext area clicked. Now comment button is shown

*Clicked body got alert a. body clicked. Now Comment button is hidden

*Clicked textarea, got alert a. body clicked b. commenttext area clicked. Now comment button is not shown.

Thanks!

A: Try it with blur
$(document).on('click', ".comment_txt, .comment_btn", function () {
    var post_id = $(this).attr("post-id");
    $("#comment_btn_div_" + post_id).show();
});

$('.comment_txt').blur(function () {
    $(".comment_btn").hide()
});

FIDDLE

A: I run into this every once in a while. Have yet to figure out why it happens; it befuddles me. I solve it by using one of the other ways of "showing" divs. Most recently, I changed the css display property:
$("#comment_btn_div_"+post_id).css('display','block');

A: var post_id=null;
$(document).on('click', ".comment_txt, .comment_btn", function(event) {
  post_id = $(this).attr("post-id");
   $("#comment_btn_div_"+post_id).show();
   event.stopPropagation();

   $('body').bind("click",function() {
        $("#comment_btn_div_"+post_id).hide()
        $(this).unbind();
   });
});

I hope it will work for you


text:
Q: Get XML element declaration from imported ("xsd:import") schema in a WSDL file by using XPath I have a problem that's been getting into my nerves for a week.
I programmed a dummy web service as a stateless EJB using Netbeans 7.2.1:
@WebService(serviceName = "WSPersonLookup")
@Stateless()
public class WSPersonData {

  @PersistenceContext(unitName="PUWSPersonData")
  private EntityManager em;

 /**
  * Web service operation
  */
  @WebMethod(operationName = "getPersonData")
  public Person getPersonData(@WebParam(name = "personId") final String personId) {
    return em.find(Person.class, personId);
  }
}

The class "Person" is just a JPA Entity mapped to this table (I used PostgreSQL as DBMS):
CREATE TABLE person
(
  id character varying(10) NOT NULL DEFAULT ''::character varying,
  nit text NOT NULL DEFAULT ''::text,
  name text NOT NULL DEFAULT ''::text,
  address text NOT NULL DEFAULT ''::text,
  phone integer NOT NULL DEFAULT 0,
  creation_date timestamp with time zone NOT NULL DEFAULT now(),
  CONSTRAINT pk_person PRIMARY KEY (id)
)

The resulting WSDL is this:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://ws.i2b.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://ws.i2b.com/" name="WSPersonLookup">
  <types>
    <xsd:schema>
      <xsd:import namespace="http://ws.i2b.com/" schemaLocation="http://pc-i2b:8080/WSPersonLookup/WSPersonData?xsd=1" />
    </xsd:schema>
  </types>
  <message name="getPersonData">
    <part name="parameters" element="tns:getPersonData" />
  </message>
  <message name="getPersonDataResponse">
    <part name="parameters" element="tns:getPersonDataResponse" />
  </message>
  <portType name="WSPersonData">
    <operation name="getPersonData">
      <input wsam:Action="http://ws.i2b.com/WSPersonData/getPersonDataRequest" message="tns:getPersonData" />
      <output wsam:Action="http://ws.i2b.com/WSPersonData/getPersonDataResponse" message="tns:getPersonDataResponse" />
    </operation>
  </portType>
  <binding name="WSPersonDataPortBinding" type="tns:WSPersonData">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
    <operation name="getPersonData">
      <soap:operation soapAction="" />
      <input>
        <soap:body use="literal" />
      </input>
      <output>
        <soap:body use="literal" />
      </output>
    </operation>
  </binding>
  <service name="WSPersonLookup">
    <port name="WSPersonDataPort" binding="tns:WSPersonDataPortBinding">
      <soap:address location="http://pc-i2b:8080/WSPersonLookup/WSPersonData" />
    </port>
  </service>
</definitions>

XSD declarations:
<?xml version='1.0' encoding='UTF-8'?>
<xs:schema xmlns:tns="http://ws.i2b.com/" xmlns:xs="http://www.w3.org/2001/XMLSchema"
           version="1.0" targetNamespace="http://ws.i2b.com/">
  <xs:element name="getPersonData" type="tns:getPersonData"/>
  <xs:element name="getPersonDataResponse" type="tns:getPersonDataResponse"/>
  <xs:element name="person" type="tns:person"/>
  <xs:complexType name="getPersonData">
    <xs:sequence>
      <xs:element name="personId" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getPersonDataResponse">
    <xs:sequence>
      <xs:element name="return" type="tns:person" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="person">
    <xs:sequence>
      <xs:element name="address" type="xs:string" minOccurs="0"/>
      <xs:element name="creationDate" type="xs:dateTime" minOccurs="0"/>
      <xs:element name="id" type="xs:string" minOccurs="0"/>
      <xs:element name="name" type="xs:string" minOccurs="0"/>
      <xs:element name="nit" type="xs:string" minOccurs="0"/>
      <xs:element name="phone" type="xs:int"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

The problem is: I need to access the schema declarations above, imported in the WSDL:
 <types>
    <xsd:schema>
      <xsd:import namespace="http://ws.i2b.com/" schemaLocation="http://pc-i2b:8080/WSPersonLookup/WSPersonData?xsd=1" />
    </xsd:schema>
  </types>

by using XPath. I'm not allowed to access the schema directly.
Is there a way to do that? If not, does anyone know a workaround for this?
Kind regards.

A: You cannot fetch a secondary XML document (the schema in this case) referenced by a primary XML document (the WSDL) using just XPaths.
Using XSLT you can do it with the document() function:
<xsl:variable name="schema" select="document(/soap:definitions/soap:types/xsd:schema/xsd:import/@schemaLocation)"/>

Alternatively, instead than trying to fetch the imported schema, just get the schema fragment inside the WSDL - using an XPath like /soap:definitions/soap:types/xsd:schema. This IS a valid schema, importing the one at http://pc-i2b:8080/WSPersonLookup/WSPersonData?xsd=1 - and you should be able to use it directly.


text:
Q: How to open google drive public link I have uploaded a file on google drive, i have made it public. i am able to access this on browser but not with my android app.
I need to access this public link on MY ANDROID APP.
PFB the link of file:
https://drive.google.com/file/d/0B56C1LC3IVXCV055WFIyVTZjTTA/edit?usp=docslist_api
Is this possible to access a publicly shared GD file on android app?
Code snippet is
URL url = new URL("https://drive.google.com/file/d/0B56C1LC3IVXCV055WFIyVTZjTTA/edit?usp=docslist_api");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;

A: The solution is to format the address of the document you have shared.
Check this :
URL = "https://docs.google.com/uc?id=" + IDFile + "&export=download";

A: How about scaling the picture down to a reasonable size, it may just be that the image is too large for your heap to load
Bitmap.createScaledBitmap(Bitmap src, int Width, int Height, boolean filter)

A: Your link is not to image but to Google Drive App with this image opened, real URL to image is this
Consider using Google Drive API

A: There one other way to access file's public link By adding :
https://googledrive.com/host/[folderId]/fileName.extension

As you have provide file url
You can use that url like this for public access
https://googledrive.com/host/0B56C1LC3IVXCV055WFIyVTZjTTA

A: You simply need to grab the webContentLink of the newly created file.
From the documentation ...
webContentLink  string
A link for downloading the content of the file in a browser using cookie based authentication. In cases where the content is shared publicly, the content can be downloaded without any credentials.


text:
Q: Print output matching pattern till other pattern match I am trying to print text after a pattern match till it matches other pattern several times in a file. I have tried to modify the script given here but failed to do it.
eg.
The content of file1.txt
example text
more example
pattern1
important text
very important
need this too
pattern2
i dont require this
junk text
more junk
pattern1
important text
very important
need this too
pattern2
junk

Expected Output
pattern1
important text
very important
need this too
pattern1
important text
very important
need this too

can anyone suggest the edit?
Thanks.

A: Matching between lines between patterns, including either boundary, is a standard range selector in sed:
sed -n -e '/pattern1/,/pattern2/p' example.txt

Depending on how efficiency-critical you are (how big the files are), I'd probably be lazy and use a second pass to delete the pattern2 markers:
cat example.txt \
| sed -n -e '/pattern1/,/pattern2/p' \
| sed    -e '/pattern2/d'

(Yes, this is a useless use of cat, because I prefer the readability of chaining several piping filters over the performance loss, and I'm not sure right now if < example.txt | sed ... | sed ... is mandated by POSIX or just an extension that happens to be present in bash and zsh.)


text:
Q: PHP Lost value of foreach after if I lost my value in foreach after if
foreach ($etc_uloziste as  $id => $etc_id) {
    foreach ($etc_id as  $id2 => $etc_id2) {
        if($rodic1==$id) {
            if( ! in_array( $etc_id2, $etc_mn) ) {
                //Check if the season already is displayed

                $sql.= ",\n"." ".$etc_id2."_id"." INT";

                $etc_mn[] = $etc_id2; //Store the season in the array
            }
        }
    }
}

before if I have value like:
[book] => Array
        (
            [0] => library
            [1] => room
        )

but after if is have only
[book] => Array
        (
            [0] => library
        )

the $etc_id2 is like library or room and $id is book

A: I lost the value in 2. echo
 foreach ($result2 as  $rodic1 => $rodic_hodnot1)
            {
             foreach ($etc_uloziste as  $id => $etc_id)
                    {
                                    foreach ($etc_id as  $id2 => $etc_id2)
                                     {
                                        //echo $etc_id2."\n";
                                        if($rodic1 ==$id)
                                           {
                                             //echo $etc_id2."\n";
                                            }
                                    }
                    }
            }


text:
Q: Functions imported from another file can't call the variables from main file here's my main.py
text = "hello"

def print_text() :

    print(text)

print_text()

it gives the desired output hello , now i want to split my code into two files like this
main.py
import functions

text = "hello"

functions.print_text()

functions.py
def print_text() :

    print(text)

It gives an error as - NameError: name 'text' is not defined
Please Note that if possible i would like to call the variable from main.py not defining it on functions.py .
Thanks in advance and sorry if i did something on explaining my issue

A: functions.py
def print_text(text) :      <-- this is the change

    print(text)

main.py
import functions

text = "hello"

functions.print_text(text)   <-- change here.

So now you have defined the variable in main.py and still able to call functions method.


text:
Q: Cache terminology - generalization of a "cache line"? When discussion CPU hardware cache, the atomic unit of cached data is a "cache line" - a sequence of the (byte) values at consecutive memory addresses, starting from some base address. This likely named after the geometric arrangement of the cache, with consecutive bytes located along a "line".
A CPU cache has a certain number of "lines" - that's its capacity. But - the memory, i.e. the pool of data that gets cached - is not made up of "cache lines". One cannot even say it is made up of "lines" at all (or if you will - it's a huge single "line").
Now, suppose I have an abstract cache of objects which are not lines of anything; call the Foo's. What term would I use for the parts of the cache which correspond to cache lines? i.e. what do I call the component of the cache which can hold a single Foo? It's not a "line", since Foo is not necessarily something linear like memory cells. Is there a commonly-used term for that?


text:
Q: How to create a counter example of a matrix with non orthogonal eigenvector? I am trying to understand this
orthogonal eigenvectors
$$T =  \begin{pmatrix}
        1 & 0 & 0 \\
        0 & 1 & 0 \\
        0 & 0 & 1 \\
        \end{pmatrix}$$
let
$$u =  \begin{pmatrix}
        1 \\
        0 \\
        1 \\
        \end{pmatrix}$$
$$v =  \begin{pmatrix}
        0 \\
        1 \\
        1 \\
        \end{pmatrix}$$
They are all linearly independent. $u$ and $v$ are eigen vectors of $T$ right?
I just want to make sure I am correct. So those are samples of eigen vectors that not orthogonal. The catch is the eigen value are the same. Namely 1. How can I create eigen vectors that are not orthogonal and have different eigen value?
I want a counter example of a matrix (doesn't have to be symmetric or diagonal) that have non orthogonal eigen vectors with different eigen value.

A: For a non-symmetric matrix take:
$$A=\begin{pmatrix} 1& 1 \\ 2& 2 \end{pmatrix}. $$
Then $(1,2)^T$ is a eigenvector to eigenvalue $3$ and $(1,-1)^T$ is a eigenvector to eigenvalue $0$ but they are not orthogonal.


text:
Q: AttributeError: 'Concatenate' object has no attribute 'compile' model_1 = Sequential()
model_1.add(Conv2D(3,kernel_size=(3,3), strides=(1),activation='relu',input_shape=(48,48,3),padding='same'))
model_1.add(Conv2D(3,kernel_size=(7,1), strides=(1), activation='relu',padding='same'))
model_1.add(Conv2D(3,kernel_size=(1,7), strides=(1), activation='relu',padding='same'))
model_1.add(BatchNormalization())
model_1.add(MaxPool2D(pool_size=(2, 2), strides=(2)))
model_1.add(Dropout(rate=0.2))

model_2 = Sequential()
model_2.add(Conv2D(64,kernel_size=(3,1), strides=(1), activation='relu',padding='same'))
model_2.add(Conv2D(64,kernel_size=(1,3), strides=(1), activation='relu',padding='same'))
model_2.add(Conv2D(64,kernel_size=(1,7), strides=(1), activation='relu',padding='same'))
model_2.add(Conv2D(64,kernel_size=(7,1), strides=(1), activation='relu',padding='same'))
model_2.add(BatchNormalization())

model_3 = Sequential()
model_3.add(BatchNormalization())
model_3.add(MaxPool2D(pool_size=(2, 2), strides=(2)))
model_3.add(Dropout(rate=0.2))
model_3.add(Conv2D(128,kernel_size=(3,3), strides=(1), activation='relu'))
model_3.add(Conv2D(128,kernel_size=(3,3), strides=(1), activation='relu'))
model_3.add(MaxPool2D(pool_size=(2, 2), strides=(2)))
model_3.add(Dropout(rate=0.3))
model_3.add(Dense(NUM_CLASS))
model_3.add(Dropout(rate=0.4))
model_3.add(Dense(NUM_CLASS, activation='softmax'))

#Concatenate
merged = Concatenate([model_1,model_2])
result =  Concatenate([merged,model_3])

result.compile(optimizer="adam",metrics=["accuracy"])
result.summary()

I am trying to concatenate the feature maps outputted by the inception module.

It shows this error message.
AttributeError: 'Concatenate' object has no attribute 'compile'

Paper from IEEE

A: The problem is that, you can't concatenate tf.keras.models.Model objects together. It's not something defined for models, but only for tf.keras.layers.Layer objects.
When such operations are involved in a model (e.g. concatenation of outputs), it's best to use the Functional API. For example, your code can be rewritten the following way using the Funcational API.
from tensorflow.keras.layers import Conv2D, BatchNormalization, MaxPool2D, Dropout, Dense, Input, Concatenate

input_img = Input(shape=(48,48,3))

out_1_1 = Conv2D(3,kernel_size=(3,3), strides=(1),activation='relu',input_shape=(48,48,3),padding='same')(input_img)
out_1_2 = Conv2D(3,kernel_size=(7,1), strides=(1), activation='relu',padding='same')(out_1_1)
out_1_3 = Conv2D(3,kernel_size=(1,7), strides=(1), activation='relu',padding='same')(out_1_2)
out_1_4 = BatchNormalization()(out_1_3)
out_1_5 = MaxPool2D(pool_size=(2, 2), strides=(2))(out_1_4)
out_1_6 = Dropout(rate=0.2)(out_1_5)

out_2_1 = Conv2D(64,kernel_size=(3,1), strides=(1), activation='relu',padding='same')(out_1_6)
out_2_2 = Conv2D(64,kernel_size=(1,3), strides=(1), activation='relu',padding='same')(out_2_1)
out_2_3 = Conv2D(64,kernel_size=(1,7), strides=(1), activation='relu',padding='same')(out_2_2)
out_2_4 = Conv2D(64,kernel_size=(7,1), strides=(1), activation='relu',padding='same')(out_2_3)
out_2_5 = BatchNormalization()(out_2_4)

merged = Concatenate()([out_1_6,out_2_5])

Then you define your model_3 outputs similarly and you can get your final output from model_3. Assume the output of model_3 is out_3_x. Then you define your final model as.
result =  Concatenate()([merged,out_3_x])

full_model = tf.keras.layers.Model(inputs=input_img, outputs=result)

full_model.compile(optimizer="adam",metrics=["accuracy"])
full_model.summary()


text:
Q: The length of the vocabulary of Spacy 'en_core_web_sm' I am using a macbook and trying to learn NLP from a udemy course. The length of my space library is len(doc.vocab)=532 , however in the video same length is around 57000. I downloaded the larger version as well nothing changed.

A: len(doc.vocab) is the number of cached lexemes, which can therefore vary when you use the model on some words.
len(doc.vocab.strings) maps strings to hash values, and vice versa. It can give you the number of different strings. For the model en_core_web_md, this would give you 701800 for example.