text:
Q: how to add double quotation character in PHP string using str_replace I have String in PHP like:
[x,y,z]

and I want to change it to
["x", "y", "z"]

I used str_replace but I can't represent the double quotation mark " in it like this
$modified = str_replace("[", "["", $NodeIDs);

I also used \ before it like java but it appears in the output. how can I do this?

A: You can use double quotes " inside single quotes ':
$modified = str_replace("[", '["', $NodeIDs);

Or escape them:
$modified = str_replace("[", "[\"", $NodeIDs);

Or this might be a better approach to get the desired result:
$letters = explode(',', trim($NodeIDs, '[]'));
$NodeIDs = '["' . implode('","', $letters) . '"]';

A: Another option is using trim, explode and json_encode:
$output = json_encode(explode(',', trim('[x,y,z]', "[]")));
print_r($output);
//["x","y","z"]

Ideone Demo

A: Simply do this
Use trim for removing the [, ] from the string, then use explode function to get the exploded string and then implode them.
$str = '[x,y,z]';
$arr = explode(",", trim($str, "[]"));
echo $str = '["'.implode('","', $arr).'"]'; //["x","y","z"]

A: Single quotes should do the trick:
$modified = str_replace("[", '["', $NodeIDs);

Good luck to you on your project!


text:
Q: How to find all lower and upper values for a given value in a list
*

*I have an array that looks like this: [1,2,4,1,2,5,1,2,6]

*Given a value of 3

*I want to find all value-pairs in the list above that encapsulate that given value.
i.e; [2,4];[2,5];[2,6]
I can find the [2,6] values by using bisect, but how can I find all the values?
x = np.array([1,2,4,1,2,5])
xL = bisect_left(x,start)-1
xU = bisect_left(x,start)
print(xL ," ", xU)
lower = x[xL]
upper = x[xU]
print(lower, upper)

P.S.
My actual data is quite large, so I do not think writing the code by myself with for loops etc. is a valid approach, so I want to mainly use build in libraries like pandas etc.

A: You could do something like this:
import numpy as np

x = np.array([1, 2, 4, 1, 2, 5, 1, 2, 6])

x_left = x[:-1]
x_right = x[1:]

encapsulation = np.where((x_left < 3) & (x_right > 3))
left_encapsulation_values = x_left[encapsulation]
right_encapsulation_values = x_right[encapsulation]

You have one array for the left values (doesn't contain the last element, because it doesn't have a right neighbor) and an array for the right values (without the first element, same idea). Then you mask those arrays with the condition that you defined and voila you have the left and right values that do encapsulate 3.
left_encapsulation_values=array([2, 2, 2])
right_encapsulation_values=array([4, 5, 6])

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I compare elements of an array with a string powershell I am new to Powershell and I have a question.
$status = @(qlist job -jt backup -co s)
Write-Host $status[3]
$status[3] -ceq "Suspended"

The answer is
 Suspended
False

My question is: Why is this comparison false?

A: Looks like you have an extra space in $status[3]
" Suspended" -eq "Suspended"
False

you may try:
" Suspended" -like "*Suspended*"
True

Parameter -ceq means case sensitive equal, so use only if really needed.
Equivalent for case sensitivity like is -clike
P.S. Also another option would be to use the trim method, which will remove the empty spaces: $status[3].trim() -eq "Suspended"


text:
Q: Creating new users in Tortoise SVN? How to add new users for Tortoise SVN. I am using Windows server 2000.

A: New users are added on SVN server, your SVN admin should do that and provide authentication mechanism details (svn+ssh etc) to you, so that you can use Tortoise SVN to access the repository. Think of Tortoise as a front end to SVN repo, used to access your code.


text:
Q: Using fields from models in django-form-utils fieldsets Sorry if I have overlooked something in docs of django-forms-utils by Carl Meyer. We're using it for the getting fieldset in non-admin pages in django. Here is my code in forms.py:
class MentorApplicationForm(ApplicationForm):
        email = forms.EmailField(label='Email', error_messages={'email_exists': 'This email id has already been used. Please use a different email id to submit a new application. Or write to applications@mentortogether.org for clarifications.'},)
        dob = forms.DateField(label=u'Date of Birth',
                      help_text=u'Format dd/mm/yyyy',
                      required=True,
                      input_formats=("%d/%m/%Y",))
        class Meta:
           model = MentorApplication
           fieldsets = [('Personal Information', {'fields': ['email','dob'],})]

What I want is something like this:
class MentorApplicationForm(ApplicationForm):
        email = forms.EmailField(label='Email', error_messages={'email_exists': 'This email id has already been used. Please use a different email id to submit a new application. Or write to applications@mentortogether.org for clarifications.'},)
        dob = forms.DateField(label=u'Date of Birth',
                      help_text=u'Format dd/mm/yyyy',
                      required=True,
                      input_formats=("%d/%m/%Y",))
        class Meta:
           model = MentorApplication
           fieldsets = [('Personal Information', {'fields': ['first_name', 'last_name', 'email','dob',],})]

where I have defined 'first_name' and 'last_name' in the MentorApplication models and I don't want to redefine them in forms.py. Here is the doc where it says that it extends from ModelForm and that's where I expected that it would take the fields from the MentorApplication model(mentioned in Meta). Can some one help me out finding the reason and also suggest me a workaround(I am quite resistant on redefining it in form, since I'll have to repeat myself). Thanks in advance.

A: I was extending ApplicationForm (super of MentorApplicationForm) from the BetterForm. I should have instead extended it from the 'BetterModelForm'.


text:
Q: Using SQLXML Bulk Import with complicated schema I'm trying to figure out how to use SQLXML bulk load for a rather complicated XML schema I have no control over (It's nominally a "standard"). A small example would be:
<RootElement>
    <id root="e5404218-250a-4454-98d5-f9feee8a3589" />
    <code code="93000" />
    <time>
        <low value="20140221095400.000" />
        <high value="20140221095410.000" />
    </time>
</RootElement>

With an AXSD schema of:
<?xml version="1.0"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
    <xs:element name="RootElement" sql:relation="re" >
        <xs:complexType>
            <xs:sequence>
                <xs:element name="id" maxOccurs="1" minOccurs="1">
                    <xs:complexType>
                        <xs:attribute name="root" type="xs:ID" sql:field="id" sql:identity="useValue"/>
                    </xs:complexType>
                </xs:element>
                <xs:element name="code" minOccurs="1" maxOccurs="1">
                    <xs:complexType>
                        <xs:attribute name="code" type="xs:long"/>
                    </xs:complexType>
                </xs:element>
                <xs:element name="time" type="timeRange"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="timeRange">
        <xs:choice>
            <xs:sequence>
                <xs:element name="low">
                    <xs:complexType>
                        <xs:attribute name="value" type="xs:string"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
            <xs:sequence>
                <xs:element name="high">
                    <xs:complexType>
                        <xs:attribute name="value" type="xs:string"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:choice>
    </xs:complexType>
</xs:schema>

My sticking point seems to come from the ID being attached to an attribute on an element, instead of an element value, as no matter what tweaks I use, I get the error Schema: relationship expected on 'id'.. There really is no relationship there, it's just a container, since the committee that designed this schema seems to have really taken a liking to attributes.
All examples I find deal with the values being element content instead of attributes. This includes decorating the element with sql:is-constant (Constant element cannot have attributes), and various permutations of the sql:relation element.
The only option I could think of is to have a pre-processing step that makes attributes child elements, and base the schema on that, but that seems kind of hacky.
Any suggestions on how to convince SQLXML to do my bidding?


text:
Q: What are the exact assumptions of Mood's Median Test? I have checked with various sources, but I'm still puzzled:
1) What are the exact assumptions of Mood's Median Test?
2) Is homogeneity of variance needed for both groups or is the same shape criterion sufficient?


text:
Q: How to get first name and profile picture from id token google sign in so I'm making the integration with google sign in from a web-site, so basically the flow here is:
google sign in -> get the token id and send to an auth rest api -> rest api get the user Name, profile picture and email then signup the user.
My problem is that I'm not beeing able to discover how to get the user name and profile picture. Even with the userinfo.email & userinfo.profile scopes, the token id only stores in the payload the UserId and the email. Here is what my token id payload is looking now:
{
  "iss": "accounts.google.com",
  "azp": "######",
  "aud": "######",
  "sub": "######",
  "email": "gsalomaoc@gmail.com",
  "email_verified": true,
  "iat": 1639009337,
  "exp": 1639012937,
  "jti": "######"
}

I was expecting the profile picture and the first&last name to bee sent at the payload. Can any one give me a hand to figure out how to get this fields?
Appreciate any help.

A: You can use this:
www.googleapis.com/oauth2/v1/userinfo
instead of:
oauth2.googleapis.com/tokeninfo
Try it out: https://developers.google.com/oauthplayground/
Source: How to get user profile picture from Google Chat Bot using Google App Script?


text:
Q: Do certain PDEs guarantee analytic solutions at $t>0$ even if the initial condition at $t=0$ is not analytic? Are there theorems that guarantee that applying a PDE on a function that is not necessarily analytic at time $t=0$, creates an analytic function at $t>0$?
For example, consider the PDE
$$
\frac{\partial f}{\partial t} = \frac{\triangle f}{2},
$$
where $f=f(x,t)$, $f\colon \mathbb{R}^n\times \mathbb{R}\to \mathbb{R}$, $f$ is integrable as a function of $x$ for any fixed $t$ and $\triangle f$ is its Laplacian. The solution at $t=1$ is
$$
f(x,1) = \int f(a,0)\frac{1}{\sqrt{2\pi}}\exp(-(x-a)^2/2)da
$$
To see this, $f(x,t)$ can be viewed as the density of the diffusion process $dx_t = dB_t$ with the initial condition that $x_0$ has density $f(x,0)$.
Notice that $f$ is analytic.
If we take the PDE that corresponds to the gradient of the logarithm of $f$, call it $s$, we get the following PDE:
$$
\frac{\partial s}{\partial t} = J_s s + \frac{\triangle s}{2}
$$
where $J_s$ is the Jacobian of $s$ and $\triangle s$ is a vector whose $i$'th entry is the Laplacian of that $i$th entry of $s$.
Notice that if $s$ is the gradient of the logarithm of some integrable function $f$ then the solution of $s$ at $t=1$ is also analytic: indeed, one could obtain its formula by differentiating the logarithm of the the solution for $f$ and see that it is analytic. It seems plausible that $s(x,1)$ is analytic also if $s$ is not the gradient of some function, however, I am not sure how to prove this.


text:
Q: Timeout hashtable Java I'm still learning programming and came across an interesting  task I must do. Your help will be much appreciated as i have no idea how to implement such task and i have been battling with it for a couple of days now...
A class which stores elements in a Hashtable for a defined amount of time. After the time runs out, the value and key must be deleted. Accessing or manipulating a value, resets the timer for that value. All i managed to figure out was use a timer, but I have no idea where to start from . I can't use anything else like Guava MapMaker suggested in other answers.
I'd appreciate your ideas and help guys!

A: Create a class with a concurrent Hashmap with methods like put, get and remove.
When putting a element, add it to the map and schedule a runnable to remove it after a amount of time. See the SchedulerExecutorService class to do that.
The submit() method of the executor service returns a Future which lets you to cancel the removing process if necessary.

A: If rolling-your-own solution this will likely involve storing entries in a ConcurrentMap which have a timestamp. You'll then likely have a scheduled job (see ScheduledExecutorService) which removes stale entries.
This problem has been solved many times by many cache implementations. See Guava's CacheBuilder for one such implementation.


text:
Q: Como converter dd/MM/yyyy HH:mm:ss para yyyy-MM-dd HH:mm:ss Se tento converter a data desta forma no Visual Studio funciona, mas quando faço deploy a API (esta já publicada) responde erro 500.
string added = "10/09/2018 10:20:11";
added = DateTime.ParseExact(added, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                .ToString("yyyy-MM-dd HH:mm:ss");

Será que tem haver com o .net core?
Basta remover que funciona novamente no deploy
Deixa de funcionar assim que publico no Linux Ubuntu usando apache.
Fiquei sem saber o que causa o problema mas resolvi fazendo a conversão manualmente da seguinte forma
private string ConverterData(string added)
{
    string datahora = added;
    var splitdatahora = datahora.Split(' ');
    string data = splitdatahora[0];
    string hora = splitdatahora[1];
    var splitdata = data.Split('/');
    var dia = splitdata[0];
    var mes = splitdata[1];
    var ano = splitdata[2];
    string novoFormato = ano + "-" + mes + "-" + dia + " " + hora;
    return novoFormato;
}

A: O problema provavelmente é por causa que o CultureInfo na máquina onde você fez o deploy é diferente da sua máquina local (que deve ser pt-br). Tente colocar o seguinte trecho de código abaixo colocando o CultureInfo como pt-br. Eu testei aqui e funcionou.
var culture = new CultureInfo("pt-BR", false);
string added = "10/09/2018 10:20:11";
added = DateTime.ParseExact(added, "dd/MM/yyyy HH:mm:ss", culture)
                            .ToString("yyyy-MM-dd HH:mm:ss");

A: Tive um problema parecido corrigi fazendo assim:
string added = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");


text:
Q: Sequelize: How to add 12 hours from now I want to set my date end default value to the currentDate + 12 hours
i try some stuff but that's not work, if someone could help me
 dateEnd: {
            type: Sequelize.DataTypes.DATE,
            defaultValue: sequelize.fn('NOW') + 'INTERVAL 12 HOUR',

            allowNull: false
        }

thanks

A: You can use sequelize.literal to define a default value that uses DB functions:
dateEnd: {
            type: Sequelize.DataTypes.DATE,
            defaultValue: sequelize.literal('NOW() + INTERVAL 12 hour'),
            allowNull: false
        }


text:
Q: Cloned a WP site which had https:// and now can't access wp-admin I coned a wordpress site which had https:// and SSL to another domain.
This domain has no SSL.
The site works okay except the /wp-admin login says page not found. Tired changing SITE URL back to http:// in wp-config and functions.php but now even on http:// it says page not found. Any ideas?

A: In your database check the table options, There are two options calld siteurl and home, update these to the new URL.
If that is fixed, check your .htaccess. This could contain rewrite rules and redirects regarding wp-admin.
In the config.php set the following to false:
define('FORCE_SSL_ADMIN', false);

There might be other causes, but the ones I've listed above are quite common.


text:
Q: Angular ui-router not calling child controller in nested routes I have my routes set up as below. Its too frustrating that the view in view.tab is loaded but its controller isn't called. I tried without the paramaters, but it still doesn't work as expected. Does anyone have any idea on how to solve this?
    $stateProvider
    .state('index', {
        url: '/',
        templateUrl: viewsRoot + 'restaurants/index.htm',
        controller: 'RestaurantsCtrl'
    })
    .state('view', {
        url: '/view',
        controller: 'RestaurantsViewCtrl',
        templateUrl: viewsRoot + '/restaurants/view.htm'
    })
    .state('view.tab', {
        url: '/orders',
        // controller: 'OrdersIndexCtrl',
        controller: function ($scope) {
            alert('This does not run');
        },
        views: {
            "view": {
                templateUrl: viewsRoot + '/restaurants/orders.htm'
            }
        }
    });

$urlRouterProvider.otherwise("/");

A: You need to declare the controller along side the template:
views: {
            "view": {
                templateUrl: viewsRoot + '/restaurants/orders.htm',
                controller: 'MyController' // (or a function, etc.)
        }

The UI-Router wiki sort of alludes to this:

If you define a views object, your state's templateUrl, template and templateProvider will be ignored. So in the case that you need a parent layout of these views, you can define an abstract state that contains a template, and a child state under the layout state that contains the 'views' object.

Controllers are paired with a view. So if it ignores the "template" properties defined on the state, it seems to imply that it will ignore the controller too.
If you want all of your named views to share a controller, define an abstract parent state as the wiki suggests.


text:
Q: Java Date Conversion In the following code
input:
Enter Date: 3/2/2011

Output:
Entered Date is February 3, 2011
Entered Month is 02

Problem is , when i input this date 3/14/2012, the date format function automatically changes month to 12+2(February). If I put 13/15/2011, it will change month to 3(12+3).
It should give an error on 14 that "invalid month"
package lesson4;

import java.util.*;

import java.text.*;
public class ConvertDate {
static String Month;
static String fulldate;
static int month;
static  int[] montharray={1,2,3,4,5,6,7,8,9,10,11,12};
public static void main(String[] args){

Scanner sc = new Scanner(System.in);
System.out.print("Enter Date: ");
String ind = sc.nextLine();
//Date now = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat f = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");

Date d = null;
    Date e=null;
Date g=null;

try {
d=df.parse(ind);
e=df.parse(ind);
g=df.parse(ind);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);

 fulldate = df3.format(d);
 Month=m.format(g);
month =Integer.parseInt(Month);

String date  =f.format(e);
 } catch (ParseException e1) {
// TODO Auto-generated catch block

e1.printStackTrace();
}

System.out.println("The entered date is: " + fulldate);
System.out.println("The entered month is: " + Month);

}
}

A: For each of your DateFormat instance, you need to invoke setLenient with false argument:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
DateFormat f = new SimpleDateFormat("dd");
f.setLenient(false);
DateFormat m = new SimpleDateFormat("MM");
m.setLenient(false);

From DateFormat#setLenient(boolean) documentation:

With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

A: Reference these formats Java Date Format Docs:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

you are expecting Month at second place while input is placing it on first.
try:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");

A: Have you tried using "setLenient(false)" on your DateFormat to force the DateFormat to be strict about the parsed input?
I haven't tried it yet, but stumbled across this feature recently.


text:
Q: Custom Email Marketing from Django on Slicehost Server I have a Slicehost slice running django through nginx and apache. This is for a project in which email marketing is a key component. We will need to be able to send up to 10,000 emails in a day from this Django app. We need to recieve email as well, however, that can simply be a forwarder.
What would be your recommended solution? would you setup a postfix mail server on the slice or try to use some 3rd party mail service with an API like MailChimp or constant contact?

A: Sending thousands of emails from your own machine in a reliable way is very hard.
I would recommend you to use SendGrid. You can use them as a smtp server, so there's no need to code against APIs. They can also receive email and POST the data to a URL on your server.


text:
Q: Как с помощью QMediaPlayer запустить mp3 с определенной секунды PyQt5 Пишу MP3-Player. Научился запускать песню, приостанавливать, находить ее длительность, но метода в QMediaPlayer по включению mp3 с определенной секунды так и не нашел. Есть ли такой метод?

A: В QMediaPlayer вроде бы нету, а вот в Pygame есть, попробуйте, ответ скопировал с question-it
Вот рабочий фрагмент, протестированный как на Windows 10, так и на Android. Обратите внимание, что музыкальный файл представляет собой mp3!
import pygame.mixer

#SOUND_FILE = 'c:/temp/JMJ.mp3'
SOUND_FILE = '/storage/emulated/0/music/JMJ.mp3'

pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()

pygame.mixer.music.load(SOUND_FILE)
pygame.mixer.music.play(loops=0, start=1626) # 1626 seconds from beginning

while pygame.mixer.music.get_busy():
    pygame.event.wait()

Конечно, работа с двумя и более модулями не очень, но хотя-бы как-то...


text:
Q: Spring Rest exception handler return XML format I'm handling an exception in my project
This is my GET endpoint:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<V6SubnetRec> get(@RequestBody V6SubnetRequest requestBody) throws QIPException {
    Site site = getSite(requestBody.getOrganization());
    V6SubnetRec wsSubnet = (V6SubnetRec) requestBody.getV6Subnet();
    V6SubnetRec v6SubnetRec = null;
    try {
        v6SubnetRec = getQipService1().getV6Subnets(wsSubnet, site);
    } catch (Exception e) {
        log.error(Keys.QIP_CALLOUT_ERROR, e);
        throw new RestException(e);
    }
    return new ResponseEntity<V6SubnetRec>(v6SubnetRec, HttpStatus.OK);
}

@ExceptionHandler(RestException.class)
public ResponseEntity rulesForRestException(RestException restEx){
    return new ResponseEntity(restEx.getResponse().getContent(), restEx.getResponse().getStatus());
}

RestException.java
@XmlRootElement(name = "RestException")
@XmlAccessorType(XmlAccessType.FIELD)
public class RestException extends RuntimeException{

   @XmlElement
   RestResponse response;

   public RestException(Exception e){
     //...
   }
}

When I request with URL http://localhost/api/v1/v6subnet.json (return with JSON format), it will return HTTP status code 404 and include the content. It's OK.

But when I request with URL http://localhost/api/v1/v6subnet.xml (return with XML format) with the same request, it return HTTP status code 500 like a normal exception which is not handled as JSON format

I want to have results like when I request to JSON format.
Thanks.

A: I've fixed my issue. It's only change from
restEx.getResponse().getContent()

into
restEx.getResponse().getContent().toString()


text:
Q: Can list an array from database but can't list any specific column of it So.. I am trying to get some data out of my database.
function my_posts(PDO $dbh, $username) {
global $dbh;
$stmt = $dbh->prepare("
    SELECT      *
    FROM        users u
    WHERE       u.user_username = :username
");

$stmt->bindParam(":username", $username);
$stmt->execute();
return $stmt->fetchAll();
}
my_posts($dbh, $username);
$my_posts = my_posts($dbh, $username);

var_dump($my_posts);
var_dump($my_posts['restaurant']);

When I > var_dump($my_posts); I can see everything in my database.
But when I am trying to get a specific column, the result is null > var_dump($my_posts['restaurant']);

How come?
array(1) { [0]=> array(18) { ["user_id"]=> string(1) "1" ["user_username"]=> string(5) "admin" ["restaurant"]=> string(21) "zzNabilss Steakhousez" ["logotype"]=> string(91) "http://tipsafilm.se/portfolio-n/projects2013/dinmeny/library/img/restaurants/grillhouse.png" ["category"]=> string(9) "Pizzerior" ["phone"]=> string(11) "0520-213328" ["address"]=> string(20) "Lantmannavägen, 137" ["postal"]=> string(5) "46161" ["city"]=> string(12) "Trollhättan" ["url"]=> string(16) "http://nworks.nu" ["opentimes"]=> string(87) "Mån-Tors 11.00-21.30, Fre 11.00-22.30, Lör 12.00-22.30, Sönd och helgdag 12.00-21.30" ["pickup"]=> string(1) "1" ["todays"]=> string(1) "0" ["delivery"]=> string(1) "1" ["catering"]=> string(1) "1" ["hidden"]=> string(1) "0" ["user_created"]=> string(19) "2013-05-25 00:00:00" } }

A: Your results are an array of arrays; the first array is for the rows, the second for the columns.  So to get the first row you use $my_posts[0] and to get the restaurant column of the first row $my_posts[0]['restaurant'].


text:
Q: Flask with css doesnt seem to be working properly Sorry if this is a little vague. I have been attempting to use build a simple table. I have been following this tutorial, though when I run the site, the css doesnt seem to work. some parts do, for example the row colouring, but nothing else. Rather odd, hopefully one of you can help me out.
Html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Mankey Activity</title>
    <link rel="stylesheet" href="/static/styles.css"/>

        {% for header in headings %}
        ">{{ header }}
        {% endfor %}

      {% for row in data %}

        {% for cell in row %}
        {{ cell }}
        {% endfor %}

      {% endfor %}

CSS:
.table {
  border-spacing: 0;
  border-radius: 4;
  margin: 1rem;
  background-color: #f5f5f5;
}

.table__row:nth-child(even) {
  background-color: #e5e5e5;
}

.table__header {
  text-align: left;
}

.table__cell {
  padding: 8px;
  text-align: left;
}

Site:

Sorry if i am being stupid.

A: Try replacing this line: <link rel="stylesheet" href="/static/styles.css"/> with this <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">


text:
Q: Is it okay for a mixed-framework NuGet package to have a dependency on a .NET 4-only NuGet package? Background:
I maintain several "framework" DLLs used by various apps and web services in my organization, and I deploy them as a NuGet package.  Some of the consumers are at .NET 4, others are at .NET 3.5 so most of these framework DLLs are .NET 3.5 for maximum compatibility.  However, there are some that require .NET 4.0, so I only include them in the lib/net40 folder of my NuGet package.
I recently added some code related to Entity Framework to one of the .NET 4 libraries, so in theory I should add a NuGet dependency to the Entity Framework package.  However, the Entity Framework NuGet package is only available for .NET 4.0, so I suspect if I do this then I'm breaking my .NET 3.5 consumers.  What should I do here?

A: There isn't a way to do this today without making multiple packages. We (the NuGet team) plan to add target framework-specific dependencies in 1.8, which would allow you to specify EF be installed as a dependency only when the target framework is .NET 4.

A: As far as I know, your only real choice is to break it into two packages, one for EF and one without.
I would suggest adding version aware dependencies as a suggestion over at http://nuget.codeplex.com/


text:
Q: How to draw the bar graph on both side of x-axis in android I am working on the application which measures the data usage of application/process running in the android device.
I want represent this data usage in terms bar graph which will draw along the x-axis. Upper side of the x-axis (Red bar) will show the data which transmitted, and lower side (Green bar) will show the data which received.
Attached screenshot may clear your doubts.

I also checked with the popular graph drawing libraries Ex: AChartEngine , AndroidPlot and afreechart but it not having support to draw such type of graph.
Is it possible to draw a such type of graph? Any suggestion always welcome..

A: try making 2 XYSeries add them on the same index and set the type to
TYPE.STACKED
if i'm correct that will stack them togheter and if you change the color of them it should be possible


text:
Q: ActiveModel: dangerous use of send()? In RailsCast 219, the following code is offered for creating a class for ferrying data back and forth from forms, but without any ActiveRecord persistence:
class Message
  include ActiveModel::Validations

  attr_accessor :name, :email, :content

  validates_presence_of :name
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
  validates_length_of :content, :maximum => 500

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end
end

I'm new to Ruby, but the send("#{name}=", value) seems like an invitation for an attacker to
assign arbitrary values to arbitrary fields. Is this an issue? A few commenters asked similar questions, but no response.

A: send is a common way of calling methods dynamically (when you don't know in advance what you will call).
If you're concerned about security, you should definitely do some validations. Here's a simple restricting check:
def initialize(attributes = {})
  attributes.each do |name, value|
    if [:name, :email, :content].include?(name)
      send("#{name}=", value)
    end
  end
end

A: When I asked a question related to the same RailsCast recently and was told that the initialiser was dangerous, but sadly no justification was given.
Having delved a little deeper I now believe that the method does not introduce any security weakness for the reasons that jdoe eluded to in his comment to your question. The send method does not circumvent accessor methods, therefore the security of attributes is controlled by accessor declarations as normal.
However, I would recommend a validation check to improve robustness against an attempt to assign inaccessible or non-existant attributes. Similar to Sergio's suggestion but more general:
attributes.each do |name, value|
  send("#{name}=", value) if respond_to?("#{name}=")
end


text:
Q: How to convert duration to seconds in Google Sheets which uses IMPORTRANGE I have copied the data from Googlesheet1 to Googlesheet2 using the below query
=IMPORTRANGE("url","!A2:H")

Which has copied the data from Googlesheet1 to Googlesheet2.
In that sheet, I am having a duration column like the below image

When i used the app script to copy the data to the firestore instead of saving the duration it saves the data in DateTime format like below.

Is there any way to convert the given duration to seconds in Google sheet.
I have tried using =value(G2*24*3600) but it didn't work in the Googlesheet2 since that sheet is a clone of Googlesheet1
App script Logic:
function firestore() {
   // Firestore setup
   const email = "//client-email";
   const key = "//client-key";
   const projectId = "timesheet-aog";
   var firestore = FirestoreApp.getFirestore (email, key, projectId);

   // get document data from ther spreadsheet
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheetname = "timesheet";
   var sheet = ss.getSheetByName(sheetname);
   // get the last row and column in order to define range
   var sheetLR = sheet.getLastRow(); // get the last row
   var sheetLC = sheet.getLastColumn(); // get the last column

   var dataSR = 2; // the first row of data
   // define the data range
   var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);

   // get the data
   var sourceData = sourceRange.getValues();
   // get the number of length of the object in order to establish a loop value
   var sourceLen = sourceData.length;

   console.log('sourceLen is', sourceLen);
   // Loop through the rows
   for (var i=0;i<sourceLen;i++){

     var data = {};

     console.log('data is', sourceData);

     data.date = sourceData[i][0];
     data.name = sourceData[i][1];
     data.workFrom = sourceData[i][2];
     data.project = sourceData[i][3];
     data.phase = sourceData[i][4];
     data.task = sourceData[i][5];
     data.totalHrs = sourceData[i][6];
     data.comments = sourceData[i][7];

   firestore.createDocument("timesheet",data);

  }

}

A: Here is the formula for A1 cell of the second sheet:
={
  IMPORTRANGE("url","!A2:F"),
  ARRAYFORMULA(
    IF(
      IMPORTRANGE("url","!G2:G") = "",
        "",
        N(IMPORTRANGE("url","!G2:G")) * 24 * 3600
    )
  ),
  IMPORTRANGE("url","!H2:H")
}

Try using named ranges for columns (A2:F, G2:G, H2:H) in the original sheet, and import them by those names so you won't need to adjust the formula where exact column names are used.


text:
Q: Why doesn't the UIAlertView work? I am testing this piece of code but when I run it, it does not trigger the UIAlertView. When the code hits If (ongoingGame = YES) and NSLog it jumps directly to the 'otherButtonTitles:nil' without executing the UIAlertView.
Can someone please explain to me why it does not trigger it?
    -(IBAction)continueGame_button:(id)sender {
    //=====CHECK IF THERE IS AN ON-GOING GAME, IF SO CONTINUE=====//
    AccessCurrentGameData *isThereAnOngoingGameFunction = [AccessCurrentGameData new];
    BOOL ongoingGame = [isThereAnOngoingGameFunction checkIfGameOngoing];
    [isThereAnOngoingGameFunction release];
    NSLog(@"+ + +continueGame_button+ + +");
    NSLog(@"ongoingGame = %@\n", (ongoingGame ? @"YES" : @"NO"));

    if (ongoingGame == YES) {
        NSLog(@"++++++++++++++++++");
        NSLog(@"++++++++++++++++++");
        NSLog(@"++++++++++++++++++");
        NSLog(@"++++++++++++++++++");
        NSLog(@"++++++++++++++++++");

        //
        UIAlertView *continueGame = [[UIAlertView alloc] initWithTitle:@"Fortsätta spel"
                                                              message:@"Det finns ett aktivt spel, klicka Spela eller Tillbaka"
                                                             delegate:self
                                                    cancelButtonTitle:@"Tillbaka"
                                                    otherButtonTitles:nil];

        [continueGame show];
        [continueGame release];

    }

    exit(0);
}

A: You are assigning onGoingGame to YES, not comparing it to YES.  Use == instead of =.

A: Your alert code is just fine I use that form (three lines - init, show, release) all of the time to do alerts.
I suggest that the exit(0) is the root of the problem. If you want to exit after the user closes the alert, you should assign a delegate which will close the app when the user taps on the close button. Use your code, but remove the exit(0). Then implement the UIAlertViewDelegate as follows:
-(IBAction)continueGame_button:(id)sender {
    //=====CHECK IF THERE IS AN ON-GOING GAME, IF SO CONTINUE=====//
    AccessCurrentGameData *isThereAnOngoingGameFunction = [AccessCurrentGameData new];
    BOOL ongoingGame = [isThereAnOngoingGameFunction checkIfGameOngoing];
    [isThereAnOngoingGameFunction release];
    NSLog(@"+ + +continueGame_button+ + +");
    NSLog(@"ongoingGame = %@\n", (ongoingGame ? @"YES" : @"NO"));

    if (ongoingGame == YES) {
        NSLog(@"+++++++++ ONGOING GAME +++++++++");

        //
        UIAlertView *continueGame = [[UIAlertView alloc] initWithTitle:@"Fortsätta spel"
                                                              message:@"Det finns ett aktivt spel, klicka Spela eller Tillbaka"
                                                             delegate:self
                                                    cancelButtonTitle:@"Tillbaka"
                                                    otherButtonTitles:nil];

        [continueGame show];
        [continueGame release];
    }
}

- (void) alertViewCancel:(UIAlertView *)alertView{
  //If you have other alerts, you may want to check the title of the alert to
  //make sure that you only exit when THIS alert is dismissed
  exit(0);
}

Dont' forget to add the <UIAlertViewDelegate> code to your header (.h) file.
You can also use - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex, if you want multiple buttons, with one of them being a specific "Quit" button.
Please note that Apple discourages using exit() in apps that are released to the App Store, and using it might get your app rejected.

A: You should not release it immediately. And you exit the app even before the alert view gets a chance to display itself. :)
Your code will continue to run even when the alert view is visible.

Fixage

*

*Remove the exit call

*Don't release the alertview. Release it in it's owner's dealloc method.

*Make the alert view an instance variable and add a retain property to it.

*Initialize the alertview in its getter if it's not yet available.

*Set it's attributes in the IBAction and show it.

*Add the appropriate delegate methods.

If I wasn't writing this answer on an iPod touch I'd post some example code. You can find lots of such code with Google.

Also, if your app isn't English-only you should always use localization provided by Foundation. Otherwise you can get English text with default error messages and other UI elements.

A: You can try this line instead.
[[[[UIAlertView alloc] initWithTitle:@"this is my message" message:nil delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil] autorelease] show];

Also, I believe Apple does not advice using exit() within your application. They always want the user to use the "Home" button to exit an app. The exit() call is a hard exit and this might be the reason you are not seeing the Alert.


text:
Q: Calculate $I_m = \int_{-\infty}^\infty \frac{dx}{1+x+x^2+\cdots+x^{2m}}$ using complex variables I have come as far as deducing that the denominator can be written as a geometric series. Hence, for $m=2$,
\begin{align*}
\int_{-\infty}^\infty \frac{1-x}{1-x^5} dx &= 2 \pi i ( B_1 + B_2 ) - \int_{C_R} \frac{1-z}{1-z^5} dz \\
&= 2 \pi i \left( \frac{1 - \exp(i \frac{2 \pi}{5})}{-5 \exp(i\frac{8 \pi}{5})} + \frac{1 - \exp(i \frac{4 \pi}{5})}{-5 \exp(i\frac{16 \pi}{5})} \right) - 0\\
&\overset{*}{=} \frac{\pi}{5} \cot\left( \frac{\pi}{10} \right) \sec \left( \frac{\pi}{5} \right).
\end{align*}
where $B_1$ and $B_2$ denote the residues in the upper-half plane.
However, I can't work out why the equality $\overset{*}{=}$ should hold. I'm sure it's the result of some clever manipulation but I've been staring at it for a while without much progress. Is my solution wrong?

A: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\dsc}[1]{\displaystyle{\color{red}{#1}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,{\rm Li}_{#1}}
 \newcommand{\norm}[1]{\left\vert\left\vert\, #1\,\right\vert\right\vert}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}&\color{#66f}{\large\int_{-\infty}^{\infty}
{\dd x \over 1 + x + x^{2} + \cdots + x^{2m}}}
=\int_{-\infty}^{\infty}{1 - x \over 1 - x^{2m + 1}}\,\dd x
\\[5mm]&=\int_{0}^{\infty}
\pars{{1 - x \over 1 - x^{2m + 1}} + {1 + x \over 1 + x^{2m + 1}}}\,\dd x
=2\int_{0}^{\infty}{1 - x^{2m + 2} \over 1 - x^{4m + 2}}\,\dd x
\\[5mm]&=2\bracks{\int_{0}^{1}{1 - x^{2m + 2} \over 1 - x^{4m + 2}}\,\dd x
+ \int_{1}^{0}{1 - x^{-2m - 2} \over 1 - x^{-4m - 2}}
\,\pars{-\,{\dd x \over x^{2}}}}
\\[5mm]&=2\bracks{\int_{0}^{1}{1 - x^{2m + 2} \over 1 - x^{4m + 2}}\,\dd x
+ \int_{0}^{1}{x^{2m - 2} - x^{4m} \over 1 - x^{4m + 2}}\,\dd x}
\\[5mm]&=2\bracks{\int_{0}^{1}{1 - x^{2m + 2} \over 1 - x^{4m + 2}}\,\dd x
+ \int_{0}^{1}{1 - x^{4m} \over 1 - x^{4m + 2}}\,\dd x
- \int_{0}^{1}{1 - x^{2m - 2} \over 1 - x^{4m + 2}}\,\dd x}\tag{1}
\end{align}

However,
  \begin{align}&\dsc{\int_{0}^{1}{1 - x^{\mu} \over 1 - x^{\nu}}\,\dd x}
=\int_{0}^{1}{1 - x^{\mu/\nu} \over 1 - x}\,{1 \over \nu}\,x^{1/\nu - 1}\dd x
={1 \over \nu}\int_{0}^{1}{x^{1/\nu - 1} - x^{\pars{\mu - \nu + 1}/\nu}
\over 1 - x}\,\dd x
\\[5mm]&={1 \over \nu}\bracks{%
\int_{0}^{1}{1 - x^{\pars{\mu - \nu + 1}/\nu} \over 1 - x}\,\dd x
-\int_{0}^{1}{1 - x^{1/\nu - 1} \over 1 - x}\,\dd x}
\\[5mm]&={1 \over \nu}\braces{\Psi\pars{1 + {\mu - \nu + 1 \over \nu}}
-\Psi\pars{1 + \bracks{{1 \over \nu} - 1}}}
=\dsc{{1 \over \nu}\bracks{\Psi\pars{\mu + 1 \over \nu}
-\Psi\pars{1 \over \nu}}}
\end{align}
  where $\ds{\Psi}$ is the
  Digamma Function.

Expression $\pars{1}$ is reduced to:
\begin{align}&\color{#66f}{\large\int_{-\infty}^{\infty}
{\dd x \over 1 + x + x^{2} + \cdots + x^{2m}}}
\\[5mm]&={1 \over 2m + 1}\braces{%
\bracks{\Psi\pars{2m + 3 \over 4m + 2} -\Psi\pars{2m - 1 \over 4m + 2}}+ \bracks{\Psi\pars{4m + 1 \over 4m + 2} - \Psi\pars{1 \over 4m + 2}}}
\end{align}

With
  Euler Reflection Formula
  $\ds{\Psi\pars{1 - z} - \Psi\pars{z} = \pi\cot\pars{\pi z}}$:

\begin{align}&\color{#66f}{\large\int_{-\infty}^{\infty}
{\dd x \over 1 + x + x^{2} + \cdots + x^{2m}}}
={\pi \over 2m + 1}\bracks{%
\cot\pars{{2m - 1 \over 4m + 2}\,\pi} + \cot\pars{{1 \over 4m + 2}\,\pi}}
\\[5mm]&=\color{#66f}{\large{\pi \over 2m + 1}\bracks{\cot\pars{\pi \over 4m + 2} + \tan\pars{\pi \over 2m + 1}}}\,,\qquad m = 1,2,3,\ldots
\end{align}

For $\ds{m = 2}$ the result becomes:
  $$
{\pi \over 5}\bracks{\cot\pars{\pi \over 10} + \tan\pars{\pi \over 5}}
={\root{10 + 2\root{5}} \over 5}\,\pi \approx {\tt 2.3903}
$$

A: There seems to be a tiny error in the last step, otherwise your solution is perfect.
You have that
\begin{align}
2\pi i \left(\frac{1-e^{i2\pi/5}}{-5e^{i8\pi/5}}+ \frac{1-e^{i4\pi/5}}{-5e^{i16\pi/5}} \right)
& = -\frac{2\pi i}{5}\left(e^{-i8\pi/5} - e^{-i6\pi/5} + e^{-i16\pi/5} - e^{-i12\pi/5}\right)\\
& = -\frac{2\pi i}{5}\left(e^{i2\pi/5} - e^{i4\pi/5} + e^{i4\pi/5} - e^{-i2\pi/5}\right)\\
& = \frac{4\pi}{5}\frac{e^{i2\pi/5} - e^{-i2\pi/5}}{2i}\\
& = \frac{4\pi}{5} \sin\left(\frac{2\pi}5\right).
\end{align}


text:
Q: Virtual link in ASP.NET gives 404 error I noticed something weird.
So normally in ASP.NET if you place a ~ in the beginning of a url, this symbol represents the root directory of the web site.
It works for all links I have on my .aspx page, except one for some reason, that points to a page located in the Account folder, where Identity's template pages are located.
So clicking this link gives me a 404 error, and asp.net informs me that the requested url was

/~/Account/Login.aspx

Obviously it doesn't work in this case, as there is no folder named ~ in the file system. But why it doesn't work ?
Now if I remove the ~/ symbols, the link will work ONCE, but then if clicked twice, the browser will try to navigate to /Account/Account/Login.aspx, which will of course throw yet another 404 error.

What can I do to make it so each time the user clicks that link, it takes him to the Login.aspx page ?

A: According to a screen shot of code you provided in a comment, your actual code is:
Login

As far as URLs are concerned, there is no ~ path here.  There is a ~Account path.  All as one word.  Which of course doesn't exist.
You can use the ~ path to indicate the root of the application, but you need to keep it as its own path:
Login

Additionally, you probably need to explicitly tell the framework to apply server-side processing for this:
Login

Because if it sends the content to the browser as-is then the browser won't know what to do with the ~ path, that's only meaningful server-side.


text:
Q: Qt как осуществить перехват пакетов по сети? Изучаю Qt, прочитал разделы книги Шлее М. по работе сетью в частности работы tcp и udp протоколов, созданию простых приложений по передаче и приёму информации по данным протоколам.
Но не могу понять, как осуществить приём любых пакетов, с любых портов при работе с конкретной сетью.
Подскажите в каком направлении идти дальше.

A: Вспоминаем матчасть. Для получения "всех" пакетов вам нужно опуститься до транспортного уровня минуя протокольные слои, в понятиях модели OSI. Qt таких возможностей не предоставляет и врядли будет предоставлять в будущем, так как это не его задача.
Если Qt отбросить, то вам нужно смотреть в сторону т. н. сырых сокетов (raw socket). Они плохо стандартизированы, точнее еще хуже чем обычные сокеты, каждый лепит как хочет. Однако подразумевается что пакеты вы получаете без обработки. Ну и соотвественно всю обработку, разбор по протоколам, придется самому делать.
Если нужен совсем хардкор, то посмотрите libpcap.


text:
Q: Slick slider with tilt.js I'm trying to have a vertical slider with slick slider and tilt.js. The last one give mouseover animation but the slider didn't work. Is there a way to make these two library work together ?

$(document).ready(function() {
  $('.slider').slick({
    vertical: true,
    slidesToShow: 1,
    slidesToScroll: 1,
  });

  const tilt = $('.js-tilt').tilt();
});

A: Please check it.

$(document).ready(function() {
  $('.slider').slick({
    vertical: true,
    slidesToShow: 1,
    slidesToScroll: 1,
  });

  const tilt = $('.js-tilt').tilt();
});
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.css"/>


text:
Q: How to change PhpStorm SCSS File Watcher Settings to Compile / Export css into different folder I have SCSS and CSS folder into a project. I am writing my code into SCSS file which is located into SCSS folder. Now i want to output this code into CSS file and this file location will be CSS folder.
My project folder tree

A: |-CSS
|-SCSS
Arguments: --no-cache --update $FileName$:$FileParentDir$/css/$FileNameWithoutExtension$.css Working directory: $FileDir$ Output paths to refresh: $FileParentDir$/css/$FileNameWithoutExtension$.css
NOTE: add --style compressed to Arguments for minified output


text:
Q: Are there any differences in how Python handles Unicode on different platforms? This is not a specific but rather a general question: are there any differences in how Python handles Unicode on different platforms?
I use Python 3 to read a text file. The following code opens a file and skips the first row:
fin = open(filename, 'rt')
next(fin)

I run the same code on a Linux computer and on Mac. I use conda environment that was created using the same environment.yml file. I also verified that I use the same Python version on both the computers (Python 3.6.3 :: Anaconda, Inc.). The data file is fetched from the same Git repository. For some reason, the Linux version raises an exception:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 139: ordinal not in range(128)

A: From the python3 docs for the open() builtin:

... In text mode ... the contents of the file are returned as str, the bytes having been first decocded using a platform-dependent encoding or using the specified encoding if given ... The default encoding is platform dependent (whatever locale.getpreferredencoding() returns)...

Are you sure that the preferred encoding reported by the locale lib is the same on both platforms? You can enforce the encoding for reading from text files like this:
fin = open(filename, 'r', encoding='utf-8')
next(fin)

Note that you don't need the file mode rt, as the t is assumed for basic file read modes; in fact, you don't need r either, as it's the default mode. So you can just do this, if you like:
fin = open(filename, encoding='utf-8')

A: The encoding doesn't depend on python but on your LOCALE variables.
It is likely that you are not using a UTF-8 locale. You can check which locale python is using with
import locale
print(locale.getpreferredencoding(False))'

which on your Mac should return UTF-8, while on your linux system something like US-ASCII
How to fix it?
On Most system, the locale is taken from environment variables (see the POSIX locale documentation
Adding LC_ALL=en.UTF-8 to your .bash_profile or equivalent will fix the problem.


text:
Q: Wireless not working on XP with new Zyxel router

I just got a new router with build in WiFi. I can connect to it with a Vista based computer, so the wireless part on the router works.
However I cannot get my old Toshiba Satellite laptop (with windows XP) to connect to it, no matter if I use old WPA-PSK or ancient WEP.
When I go connect and put in credentials the dialog stays up for a few minutes then disappears with no message and no connection is established.
Here's the spec of router and wireless card in the XP laptop:

*

*Wireless card: Intel® PRO/Wireless 2200BG Network Connection

*Router: Zyxel P-660-HW-T1 v3

Any help appreciated!

A: Not much of a solution but ... I parked the new router and went back to the old one.

A: Windows XP and WPA are not great buddies,had the same router from my ISP (Telefonica) and the time-outs and disconnected were very common,sometimes i cant even connect to my wireless in the XP O.S, in my case changing the type of WPA worked for me.
Please upgrade your system to another O.S like Windows 7-8.1 or any Linux distro if you can.
Edit: I just remember that router had a bug in the firmware with the XP O.S, look for the latest firmware.


text:
Q: PHP multiple file upload check empty file Let's say I have a form like this:
<form action="upload.php" method="post" enctype="multipart/form-data">
File 1 : <input type="file" name="file[]" />
File 2 : <input type="file" name="file[]" />
<input type="submit" name="submit" value="Upload" />
</form>

I want to make sure that each file had upload file.
Here is my condition and the code that I write:
File 1 empty:
if(empty($_FILES['file']['name'][0]))
{
    echo 'file 1 empty';
}

File 2 empty:
if(empty($_FILES['file']['name'][1]))
{
    echo 'file 2 empty';
}

File 1 and File 2 empty:
if(empty($_FILES['file']['name'][0]) && ($_FILES['file']['name'][1]))
{
     echo 'file 1 and file 2 empty';
}

Is it possible to write the above condition in for loop? Or just seperately write the code is enough?

A: use foreach
$i=1
foreach($_FILES['file']['name'] as $file){
if(empty($file))
{
    echo "file $i empty";
    $i++
}
}


text:
Q: Directory conventions for extra files I have written a (python) script which identifies all node on its subnet (NAT subnet) and send an email if the IP address doesn't exist within a record. For this size of project, I don't want to run a database. I think a text file delimited by new lines with an IP address on each would be suitable. What is the appropriate convention for the directory this file would be placed?

A: There are no real conventions and the answers to this question may be a little opinionated and a lot depends on the script's exact use case.
You have following choices:

*

*datafile in current working directory

*datafile in same directory as script

*datafile in a folder (that will be created if not existant) relative to the home directory

*like three but with an additional profile name

*in a system folder like /var/run/toolname

*explicit parameter to the script specifies file name

1.) Current working directory
Con:

*

*It forces you to cd into the directory where you have your data, otherwise script won't work or create new data from scratch

Pro:

*

*As the same user on the same machine you could have multiple projects each using its own data.

2.) datafile in same directory as script
Pro:

*

*you don't have to cd anywhere. you know where to find the data.

Con:

*

*you need write permissions to the directory where the script is located (might be a security concern if executed by a web server and if an exploit is found)

*only one data file per script

*no two users can execute the script with different data

3.) datafile in a folder (that will be created if not existant) relative to the home directory
Pro:

*

*script in one directory but each user has its own data.

*if script directory is removed, script is uninstalled and reinstalled the data will persist.

*no special write permissions for script dir required.

Con:

*

*you remove the script dir, data persists and might never be deleted.

*one user cannot run multiple instances use the script for multiple projects

*clean up of data required after uninstall of script

4.( like 3.) but with an additional profile/project name
Pro:

*

*same as for 3.)

*one can run multiple projects / profiles in parallel (firefox for example allows to be run with profiles, which are all stored in ~/.mozilla/firefox, but each profile creates its own sub directory ~/.mozilla/firefox/xxxx.profilename
Con:

*

*same as for 3.)

5.) in a system folder like /var/run/toolname
Pro:

*

*could be nice for tools, that run as service / server

Con:

*

*require admin privileges (at least during installation)

6.)
Pro:

*

*you can do whatever you want

Con:

*

*you must specify an additional paramater (except you have the behaviour of the other suggestions as default and the option only if you want to have different behaviour.

All solutions should be fine for you.
For your kind of tool 5.) 3.) 2.) 6.) are probably the better options. I assume your script will be run as a cron job or something alike.


text:
Q: Multiple Attachments with Swiftmailer I'm creating a form that allows multiple files to be uploaded.  The form field values and attachments are then to be emailed to certain address.  I'm using Swiftmailer to generate these emails.  I know how to attach a file with Swiftmailer, but I don't know how to attach multiple files.  Does anybody know whether this is possible using Swiftmailer?

A: Yes, it's simply a matter of making multiple calls to attach():
$message->attach(Swift_Attachment::fromPath('../../uploads/hocuradit/' . $attPath . $attA));
$message->attach(Swift_Attachment::fromPath('../../uploads/hocuradit/' . $attPath . $attB));

Source: http://groups.google.com/group/swiftmailer/browse_thread/thread/416b287591dfe931?fwc=1


text:
Q: swift_dynamicCastClassUnconditional runtime error I am having a weird runtime error in swift. I have a CollectionViewController scene in the following order:
Items Controller Scene
    Items Controller (class: ItemsController)
        ItemCell (class: ItemCell, reuseIdentifier: "ItemCell")
            View...

And the classes:
class ItemCell : UICollectionViewCell {

    @IBOutlet weak var nameLabel: UILabel!

}

class ItemsController : UICollectionViewController {

        override func viewDidLoad() {
            super.viewDidLoad()

            self.collectionView.registerClass(
                UICollectionViewCell.self,
                forCellWithReuseIdentifier: "ItemCell");

        }

        override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
            return 1
        }

        override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 10
        }

        override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(               "ItemCell",
            forIndexPath: indexPath) as ItemCell

            // ^^ The runtime error points to here

            cell.nameLabel.text = "Title";

            return cell
        }

}

This doesn't make any sense. What am I doing wrong? I have tried cleaning the project and recompiling but still didn't work (this generally works on most cases). I don't want to rewrite everything to work (that has happened to me also; recreating the Views fixed the problem). I am on Xcode 6.1; if there is no error here, I will pursue with recreating my storyboard but I don't want to do it until I am sure there is no problem in my code.
EDIT: Forgot to mention it. If I change the class from ItemCell to UICollectionViewCell in collectionView.dequeueReusableCellWithReuseIdentifier line, it at least runs. So, the problem does reside in the storyboard for assigning the custom class name.

A: Nevermind, found the problem. I forgot to change the class name to ItemCell when registering the class for the collection view:
self.collectionView.registerClass(ItemCell.self, forCellWithReuseIdentifier: "ItemCell")

EDIT: I don't have much experience with UICollectionViewController but I found out that, if I want to use the custom class using the above line will make all the IBOutlets nil. So removing that line fixes the problem.


text:
Q: How does a Markov Chain converge to a distribution we don't know? As succinctly stated in this answer:

it is possible to design a Markov chain with a stationary distribution equal to the posterior distribution, even though we don't know exactly what that distribution is.

To anyone without a rather deep understanding of the statistics behind Markov Chains, this sounds like pure magic. How can you construct a process that guarantees convergence to a distribution you don't know?
All the information I've found on the topic is quite mathematically involved, and not suitable for an introductory course for non-statisticians. How would you explain this property of Markov Chains in a simple way?

A: Let's emphasize the key part of the original statement.

it is possible to design a Markov chain with a stationary distribution equal to the posterior distribution, even though we don't know exactly what that distribution is.

While we don't know exactly what the distribution is, we can compute the density function up to a normalizing constant. This normalizing constant disappears when if we start thinking of ratios, i.e., if we have that $f$ is our posterior density (up to a multiplicative constant) then even without knowing that normalizing constant, if we know that
\begin{equation}
f(\theta_1) = 2f(\theta_2)
\end{equation}
then we know that $\theta_1$ is twice as likely as $\theta_2$ in the posterior. Note that this relation alone completely specifies the distribution; if you were able to make a function that could take random samples and in the long run, this relation of ratios is preserved, then you can take draws from the posterior exactly. This is the goal of an MCMC algorithm.
While there are a lot of different MCMC algorithms, the general theme is coming up with a really clever way of drawing samples where, in the long-run, one can reason that these ratios are preserved. For simplicity, let's think about the Metropolis-Hasting algorithm. Without going into a full proof, we can think that in the MH algorithm, we are taking draws from a random process (i.e. a random walk). We then essentially upweight draws that have very high posterior densities by getting "stuck" at that spot for several iterations, relative to spots that have low density in the posterior. Math that we apparently want to avoid tells us that in the long run, this will preserve the ratios given by the non-normalized posterior density function.

A: I think Ben overstates the resulting result a little in that answer. We do know something that is extremely useful, namely that we can query the function $\pi(\theta|x)$ in such a way that we always receive back $f(\theta|x)/Z$, where $Z^{-1} = \int_\Theta \pi(\theta|x) d\theta$, and $f(\theta|x) = L(x|\theta)p(\theta)$, the product of the likelihood and the prior. But this immediately implies another fact: that if we want to query a ratio of $\pi$ evaluated at two different values $\theta'$ and $\theta$, the ratio of $Z$s will immediately cancel, leaving the correct corresponding ratio. We can then proceed to design a clever Markov chain (via the Metropolis-Hastings method) that exactly uses this ratio when generating  moves on $\Theta$.


text:
Q: Kent Connolly is no where to be found even after the quest I saved a Kent Connolly from certain death as part of the Silver Shroud quest.
Afterwards, he was no where to be found - what gives? After all those pains I am unable to find the certain comic loving ghoul what gives? He is supposed to give me an armor upgrade to my shroud armor.
Where is he?

A: As far as I know, the character Kent Connolly gets stuck in the hospital for some reason.
Solving this requires access to the console. You can bring his object reference to yourself:

*

*Go to Goodneighbor.

*Type prid 000228ac - this is his reference ID and not base ID.

*Do a moveto player.

Now he will move into his room in The Memory Den. You can either talk to him or turn on the Silver Shroud Radio and he will mention armor upgrades waiting for you, since you are the best Shroud. These are level specific.
The Silver Shroud Radio will also seem to inoperative at this point (not a bug since at the end of saving Kent, he specifically mentions not doing the radio ever again). But at each of the upgrade levels for the Silver Shroud Armor (25?/35/45), Kent will go on the air in Goodneighbor and call for the Silver Shroud at which point you can talk to him in the Memory Den for the Armor upgrade.
And never cross my path, I am the Shroud!!!! (phew)

A: Kent should be with Hancock in the Old State House in Goodneighbor after you save him.
He'll be there when you turn in the quest to Hancock, then he'll go to his room in the Memory Den.
If he's not there, then you've probably run into a bug. If you're on PC, you can deal with this situation using console commands, as explained in ヴァイシャリ's answer.

A: For gamers of console:
I found that if you corral him into the elevator and take it down with him in it, he'll start walking out on his own once he's in the room with the exit.
NPC's and companions were made so they would walk to move out of your way if you make it clear that you want them to move. So by corral I mean keep running into Kent until he gets out of your way into the elevator.
It's somewhat time-consuming but if you don't want to maze through the hospital next time you want to get him to improve your silver shroud costume then it's your only option at this point.

A: I had Hancock as a follower while doing this quest. I was able to talk to Hancock and Kent straight after I killed the boss and saved Kent. I think this is what caused him to remain in Milton General Hospital for me.
 So heads up, don't have Hancock as a follower while doing this.

A: I am a console player.  When he started the radio station back up to upgrade the suit,  I couldn't find him in goodneighbor.  I went back to the hospital and after killing raiders, I found him in the same spot I left him.  He still upgraded my suit from there though.

A: I had Hancock as my companion as well, and this time, Kent got stuck at Milton General Hospital as well. On my 2 previous run-throughs I had different companions and he ended up back in Goodneighbor.
Either way, you can get your upgrades after 3 days to 1 week passes (in game). If you don't get the full 87/87 defense upgrade, make sure to check back at level 35 & 45. If you're level 45+, you'll automatically get the maximum.

A: I had the same problem.  Saving Kent is optional, and in my case he died.
Make sure you are dressed as the Silver Shroud when you are at the hospital, and to kill everyone after killing Sinjin. The game will tell you to meet Hancock at Goodneighbor - have him join you, then talk to him: this will finish the mission and you can now get rid of the uniform and put it in your inventory.


text: Q: Create shortcut of Folder or Document in Alfresco My requirement is to create shortcut of one folder or document into another folder. For example lets say I have a folder called A and in this folder I have many documents. Now I want to create shortcut of this folder into another folder name B. So basically I don't want to store same content in folder B, it's contains link or reference of folder A. Whatever change made in folder A, it has to be reflected to folder B also. So any one please help me how to do it alfresco using apache chemistry.


text:
Q: Password hashing and verification I'm trying to learn now about hashing and verification of passwords, I was told to use the module passlib and pbkdf2.
The code I was recommended was:
To Hash:
 from passlib.hash import pbkdf2_sha256
 hash = pbkdf2_sha256.hash("password", rounds=20000, salt_size=16)

To Authenticate:
from passlib.hash import pbkdf2_sha256
pbkdf2_sha256.verify("password", hash)

I think I understand all the code here, except for one thing, where would the Hash for any given password be stored, and mainly how to have the input for the password that i want to verify,
I tried using
password = input("Enter a password here: ")

That worked since I tried printing the hash, and each time i entered the same password, i got the same hash, so up to that point, everything is working.
now, i tried resetting password, by a new input, and then having the authentication code after it, thinking that I have set password as a new value, I should be able to get a False value each time i entered a password that does not match to the first one entered, yet, there, no matter the second input, returns True
here's the full code
from passlib.hash import pbkdf2_sha256

password = input("Enter a password:")
hash = pbkdf2_sha256.hash("password", rounds=20000, salt_size=16)
print(hash)

password = input("please enter your password:")

print(pbkdf2_sha256.verify("password", hash))

Then I tried setting the 2nd password as "password2" and that returns false always.

A: You are hashing and verifying the text "password" rather than hashing and verifying the input. Minor change to your variable names to make it a bit clearer what you need to change:
from passlib.hash import pbkdf2_sha256

password_input = input("Enter a password:")
hash = pbkdf2_sha256.hash(password_input, rounds=20000, salt_size=16)
print(hash)

password_confirm = input("please enter your password:")

print(pbkdf2_sha256.verify(password_confirm, hash))


text:
Q: Forcing a word to wrap How can I make the word "Hameln" take on a new line instead of breaking?
I've tried experimenting with overflow-wrap, word-break, & white-space but either the word breaks or it overflows beyond the container. It never talked a new line between "31789" and "Hameln".

<span class="standort-adresse-strasse"> Grabbestraße 23 | 31789 Hameln </span>

Screenshots:


text:
Q: Android upload to network drive(samba share) performance issue i have a problem when I upload a picture of 100kb to samba share with JCIFS from my tablet, it takes about 10-20 minutes (before I changed my buffer from 1024 to 20971520 it took almost 6 hours) but it does not give any effect anymore to increase it
it is not the connection issue as i had tested it with ES File where it Uploaded my picture immediately
private class MyCopy extends AsyncTask<String, String, String> {

    String z = "";
    String username = "", password = "", servername = "", filestocopy = "";

    @Override
    protected void onPreExecute() {
            username = edtusername.getText().toString();
            password = edtpassword.getText().toString();
            servername = "smb://" + edtservername.getText().toString();
            filestocopy = editdir.getText().toString();
        }

       protected String doInBackground(String... params) {
   //         String buffer;
  //          buffer = setingPreferences.getString("buffer", "");
            File file = new File(filestocopy);
            String filename = file.getName();

            NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(
                    servername, username, password);

            try {

                SmbFile sfile = new SmbFile(servername + "/" + filename, auth1);
                if (!sfile.exists())
                    sfile.createNewFile();
                sfile.connect();

                InputStream in = new FileInputStream(file);

                SmbFileOutputStream sfos = new SmbFileOutputStream(sfile);

                byte[] buf = new byte[20971520]; //(parseInt(buffer))
                int len;
                while ((len = in.read(buf)) > 0){
                    sfos.write(buf, 0, len);

                }
                in.close();
                sfos.close();

                z = "File copied successfully";
            } catch (Exception ex) {

                z = z + " " + ex.getMessage().toString();
            }

            return z;
        }
    }

A: The buffer size shouldn't make a noticeable difference, but it definitely shouldn't be 20M. Use something like 4k instead.
Are you sure it's the actual file transfer that is taking so long? There's no reason 100k should take more than a few seconds at the most. Have you tried putting log statements between each step, including before and after the authentication calls, createNewFile(), and connect() to check if those are the bottleneck?
Also, I believe you should be copying bytes while the read length is >= 0 instead of strictly > 0, since -1 signals the end of the stream, not 0.

A: Did you try
new SmbFile("username:password@server/")
instead of using NTLM? It can also be a DNS issue, so do try
jcifs.Config.setProperty("resolveOrder", "DNS");
If neither works, you might want to try BufferedOutputStream with your SmbFileOutputStream.


text:
Q: Gram–Schmidt process I got to use the Gram–Schmidt process on this set: $\left\{ \begin{bmatrix}0&1&0\\-1&0&0\\0&0&0 \end{bmatrix},\begin{bmatrix}0&0&0\\0&0&1\\0&-1&0 \end{bmatrix}, \begin{bmatrix}0&0&1\\0&0&0\\-1&0&0 \end{bmatrix} \right\}$
I only know how to deal with vectors but not with matrices. Anyone can show me how to do that?

A: The Gram-Schmidt process is defined for any inner product space, and the process is exactly the same. So you just need to know what is the inner product being used on $M_{3\times3}$. This is usually the Frobenius inner product:
$$
\langle A, B \rangle = tr(AB^T).
$$
(Here 'tr' means trace.)

A: You use the same process than with vectors, but the inner product with matrices is : $$\langle M_1,M_2\rangle=\mathrm{Tr}(M_2^*M_1)$$


text:
Q: Java debugging on Eclipse: Weird Error: StringIndexOutOfBoundsException I encountered a weird occurrence while debugging in Eclipse. I am debugging the following method.
private String parseMessage(String msg, String uptoWord) {
    String adjusted = msg.replaceAll("(\r?\n|\r)", " ").trim();
    adjusted = adjusted.substring(0, adjusted.length() - uptoWord.length()).trim();
    return adjusted;
}

In the second line within the method (adjusted = msg.replaceAll("(\r?\n|\r)", " ").trim();) when I check the value of the right hand side of the assignment I get the desired value that I expect to get. However when I advance to the next line (the return statement) the value of adjusted becomes a space (" "). Thus the program returns the following exception. I cannot understand why it changes the value in the return statement. Any ideas?
java.lang.StringIndexOutOfBoundsException: String index out of range: -8
    at java.lang.String.substring(Unknown Source)
    at com.emdi.sl3.server.emailConnector.EmailListenerOrderCreate.parseMessage(EmailListenerOrderCreate.java:65)
    at com.emdi.sl3.server.emailConnector.EmailListenerOrderCreate.XMLCreate(EmailListenerOrderCreate.java:57)
    at com.emdi.sl3.server.emailConnector.EmailConnectorEWS.run(EmailConnectorEWS.java:77)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

A: As per Java docs for subString , because of bad values of beginIndex and endIndex you are getting that error.

IndexOutOfBoundsException - if the beginIndex is negative, or
  endIndex is larger than the length of the String object, or beginIndex
  is larger than endIndex

.

A: If upToWord is longer than your adjusted string, you're going to be substringing with a negative end-bound parameter. By throwing that exception, String is telling you that you're gonna have a bad time with those parameters.

A: You have to handle the scenario when the length of uptoWord is bigger than the length of adjusted. The negative index will cause the substring method failed.

A: Thanks for all your inputs. However this problem wasn't a simple error in code. I tried a lot to solve the issue and apparently solved the issue by running an "ant clean". Thus the problem was some leftover/mismatching class files.


text:
Q: How to import a table of numbers from a .txt file without losing dimensions? I have a long txt file (which attached here). I want to import this file and then use a special line (in this case line 112) to plot a graph. I tried this
file = Import["data.txt", "Data"];
den = file[[112]];
den // Dimensions
(*
{303}
*)

As you can see it gives me dimensions {303} while the real dimensions of den must be {303,2} I don't know why Mathematica adds an addiional {} to den. Also when I try "Lines" in Import command it returns all of line 112 as a string. What is the best way to import line 112 as a real table as what I really need to plot?

A: This appears to be an unusual file format which mixes different types of output.  Import is attempting to read it as a CSV file, which is causing your problem.
Manual inspection suggests that line 112 is a string representation of a Mathematica List, which suggests that the following should work (using the link you provided).  The basic idea is to import the file as a list of strings (one string for each line), and then to interpret the desired line as needed:
file = Import[
   "http://www.deeplook.ir/wp-content/uploads/2021/05/data-1.txt",
   "List"];
den = ToExpression[ file[[112]] ];
Dimensions[den]  (* {201,2} *)

Warning:  It's generally considered dangerous to ToExpression random things on the internet.  I looked at line 112 first to see that it was an innocuous List.


text:
Q: Making an output of frends names instead of IDs Can somebody help me with this, i m new to javaScript and i m stuck at this point.I made an output of certain object within my array ,that output is writing a persons values, within that object(Osoba) there is an array of his friends and all values inside are IDs of each person, http://prntscr.com/i9m2ti how can i make that ID of a friend array ( within the object ) to be a first name and surname of that person which id is in array and when i want to output a certain object so there will be friends[ their names instead of IDs], can someone write me down how can i do that. Thanks for understanding.
class Osoba{
constructor(id,firstName,surname,age,gender,friends){
    this._id = id ;
    this._firstName = firstName;
    this._surname = surname;
    this._age = age;
    this._gender = gender;
    this._friends = friends;
    }

    get id() {
        return this._id;
    }
    set id(id){
        this._id = id;
    }
    get firstName() {
        return this._firstName;
    }
    set firstName(firstName){
        this._firstName = firstName;
    }
    get surname() {
        return this._surname;
    }
    set surname(surname){
        this._surname = surname;
    }
    get age() {
        return this._age;
    }
    set age(age){
        this._age = age;
    }

    get gender() {
        return this._gender;
    }
    set gender(gender){
        this._gender = gender;
    }

    get friends() {
        return this._friends;
    }
    set friends(friends){
        this._friends = friends;
    }

}

var osobe = [];  // my array

   $(function() {

   $.getJSON('https://raw.githubusercontent.com/Steffzz/damnz/master/
  data.json' , function(data)
    {
          var json = jQuery.parseJSON(JSON.stringify(data));

        for(person of json)
        {

            var id = person['id']  ;
            var firstName = person['firstName'] ;
            var surname = person['surname'] ;
            var age = person['age'] ;
            var gender= person['gender'] ;
            var friends = person['friends'] ;

            var x = new Osoba(id,firstName,surname,age,gender,friends);
            osobe.push(x); //filling array with objects and their values
        }
        console.log(osobe);
       document.write(JSON.stringify(osobe[0])) //output of a certain object
      })
 });

A: Assuming json is an array and contains all people you can map over friends array and find the person with that id: person['friends'].map( and json.find(function(person){person.id===friendId});.
Then return an object containing that person's first and last name:
console.log("json is:",JSON.stringify(json,undefined,3));
var friends = person['friends'].map(
  function(friendId){
    console.log("friendID is:",friendId);
    var friend = json.find(function(person){return person.id===friendId;});
    console.log("friend is:",JSON.stringify(friend,undefined,2));
    return {
      firstName:friend.firstName,
      surname:friend.surname
    }
  }
);

Now if that "does not work" could you please specify the output of the logs, any errors and expected results versus actual results?
UPDATE FULL CODE
Since the json is all your data you can pass that into your Osoba constructor. The friends getter will use the data to create an array Osaba items that will have data and friends that will create an array of Osaba ...
class Osoba {
  constructor(id, firstName, surname, age, gender, friends, data) {//added data
    this._id = id;
    this._firstName = firstName;
    this._surname = surname;
    this._age = age;
    this._gender = gender;
    this._friends = friends;
    this._data = data;//data has all the people
  }

  get id() {
    return this._id;
  }
  set id(id) {
    this._id = id;
  }
  get firstName() {
    return this._firstName;
  }
  set firstName(firstName) {
    this._firstName = firstName;
  }
  get surname() {
    return this._surname;
  }
  set surname(surname) {
    this._surname = surname;
  }
  get age() {
    return this._age;
  }
  set age(age) {
    this._age = age;
  }

  get gender() {
    return this._gender;
  }
  set gender(gender) {
    this._gender = gender;
  }
  //modified friends getter returning an array of Osoba items
  get friends() {
    var me = this;
    return this._friends.map(
      function (friendId) {
        var friend = me._data.find(function (person) { return person.id === friendId; });
        return new Osoba(
          friend.id,
          friend.firstName,
          friend.surname,
          friend.age,
          friend.gender,
          friend.friends,
          me._data
        );
      }
    );
  }

  set friends(friends) {
    this._friends = friends;
  }

}
$.getJSON('https://raw.githubusercontent.com/Steffzz/damnz/master/data.json')
  .then(
  json => {
    var people = json.map(
      person =>
        new Osoba(
          person.id,
          person.firstName,
          person.surname,
          person.age,
          person.gender,
          person.friends,
          json
        )
    );
    //you can keep getting friends now, because Osoba is
    //  creating new Osoba objects based on id's and data you pass in
    console.log(people[0].friends[0].friends[0].friends[0]);
  }
  );

A: If i understand correctly you just want to use id for id, firstname, and lastname. so just pass id 3 times instead of firstname and lastname:
var x = new Osoba(id,id,id,age,gender,friends);

~~~~
Ok so what you want is actually that the id property within each friend object be the first and last name of the friend instead of an idea code. So it's basically just the opposite of what i suggested earlier. All you have to do is manipulate what you push to id. There's no obligation on it being the id from the json.
so in your case:
for(person of json){

        var id = person['firstName'] + "" + person['surname']; // line to change.
        var firstName = person['firstName'] ;
        var surname = person['surname'] ;
        var age = person['age'] ;
        var gender= person['gender'] ;
        var friends = person['friends'] ;

        var x = new Osoba(id,firstName,surname,age,gender,friends);
        osobe.push(x); //filling array with objects and their values
    }

A: instead of
var friends = person['friends'] ;

try
var friends = [];
var friendIDs = person['friends'] ; //retrieve friendIDs

for(friendID of friendIDs) { //loop over friendIDs
  var friend = json[friendID]; //get friend dataset out of the json
  friends.push(friend['firstName']); // add friend dataset to friends array
}

I assume here that those friends are in that json aswell. and that the ids represent that index inside that array. if the indexes aren't those ids this won't work. feel free to comment if thats the case and i'll edit my answer.


text:
Q: get case insensitive key from list> I have a list> and now I want to search the key without considering case.
i.e. map.get(0).get("test") or map.get(0).get("TEST"). both result should give the value for key 'TESt'.
I am filling the List> list from other list> like below. There is no way to change the original map. Can anyone tell me how to add key with upper case?
mappedListHashed is List>
 accessLvlArray is List>
for (HashMap<String, String> map : mappedListHashed) {
                accessLvlArray.add(map);
            }

A: You could always put just lower case keys in your Map
list.get(0).put("tEst".toLowerCase(),"value");

and call
list.get(0).get("Test".toLowerCase())

in order to always search for the lower case version of the key.
If that's not an option, you can wrap your String key with a custom class that overrides equals and hashCode in a manner that ignores case.

A: You can try to override the put method:
public class myMap extends HashMap<String, String> {
@Override
public String put(String key, String value) {
   return super.put(key.toLowerCase(), value);
}

public String get(String key) {
   return super.get(key.toLowerCase());
}
}


text:
Q: Call a method/ handle event in Windows Service from hosted WCF Service apologies in advance for this question being dumb, or previously covered. I have researched far and wide but have not found any resources on WCF/ Windows Services that cover this question.
I have a managed Windows Service which is working nicely. Every n (>5) seconds it checks on the status (e.g. memory consumption) of some processes and other Windows services and also does some database logging and raises events where necessary.
I intend to make an ASP.NET website that would allow users to query the status of the processes that the Windows Service is monitoring. Having researched the options it looks like the up-to-date method would be to use a WCF Service, hosted in the Windows Service, to act as intermediary between the ASP.NET website and the Windows Service. Such that, a user could request through the browser a snapshot of the current status of whatever set of processes the Windows Service was monitoring, and have this request and subsequent response  relayed through the WCF service (using named pipes, I think).
So, my difficulty is that there a set of methods and events in the Windows Service for which a single root object exists (let's say MonitorObject). I don't see how the ServiceHost can be instantiated with the reference to MonitorObject so that the WCF Service can call the methods in the Windows Service. I am thinking that perhaps I need to make the Monitor object a shared (I am VB'ing) member of the Windows Service class (that contains OnStart and OnStop) and make all the events shared so that the WCF Service can just access the WindowsService.SharedMonitorObject without needing to be passed the object....
However, I am lost in the subject and am seeking any advice on how best to proceed.
Thanks in advance.

A: I think you're going down the right track.  I wouldn't necessarily make the entire MonitorObject shared, but you might put a shared method in that object that will return the single root object to the caller.
There is a design pattern called the Singleton Pattern that will help you with this.  Jon Skeet has written an excellent article on some of the things to be aware of when using this pattern in .NET.  His article uses C# for the examples, but here's a SO question referencing this pattern using VB.
While it's unclear from your description, my guess is that your Windows Service is essentially single-threaded right now.  Just keep in mind that once you add the WCF service, you'll need to make the methods that it references thread-safe.


text:
Q: GOOGLE SHEET IGNORE #REF I m working on a project on GOOGLE SHEET and I solve all of my problems, except one.
I have many Sheets which are called between different pages.
I need to recover all the data of any pages created, who have specific name.
Like : ='io208'!E28 // ='io308'!E28 // ='io408'!E28 // ETC...
The things is, all of theses pages are not created so I have to take all value but if I do a sum, some informations are missing (coz not createad) and the RESULT of my sum is #ref!
If someone have a idea..

A: try IFERROR before SUM:
=SUM(IFERROR({io208!E28, io308!E28, io408!E28}))


text:
Q: Retrieving Office.customeXMLparts without namespaces I am trying to store some data in an Excel file using it's CustomXMLParts component.
I am also failing quite hard.
I have the following code:
    Public Shared Sub AddSettingsXMLToDocument()

        Dim xmlPart As XElement =
            <SoftwareName xmlns="myNamespace">
                <Settings>
                    <FormVersion></FormVersion>
                    <FormPassword>"Password"</FormPassword>
                    <DatabaseRequiresAdminMode></DatabaseRequiresAdminMode>
                </Settings>
            </SoftwareName>

        Dim aWorkbook As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
        aWorkbook.CustomXMLParts.Add(xmlPart.ToString(), System.Type.Missing)
    End Sub

    Public Shared Function GetSettingsXMLFromDocument() As String
        Dim aWorkbook As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook

        'GET THE ENTIRE THING
        Dim retrievedXMLParts As Office.CustomXMLParts = aWorkbook.CustomXMLParts.SelectByNamespace("myNamespace")
        Dim customXMLPart As Office.CustomXMLPart = retrievedXMLParts2.Cast(Of Office.CustomXMLPart)().FirstOrDefault()

        'TRYING TO GET A SPECIFIC FIELD
        Dim formField As Office.CustomXMLNode = customXMLPart2.SelectSingleNode("XpathExpression")
        If (Not IsNothing(formField)) Then _
            MsgBox("FINALLY GOT MY NODE!   " & vbNewLine & d1.XML)
        If (IsNothing(formField)) Then _
            MsgBox("ARG")
        Return FormField.XML
    End Function

The line I'm interested in is:
Dim formField As Office.CustomXMLNode = customXMLPart2.SelectSingleNode("XpathExpression")
I have pretty tried EVERY thing as a Xpath Expression and I received a null value for everything except "*/".
I also read an article about namespaces, but it won't work with VSTO as Office.CustomXMLParts won't allow you to overload the function with a NamespaceManager parameter.
SelectSingleNode returning null for known good xml node path using XPath
How can I build my data out of Office.CustomXMLParts ?
How would I update the Workbook.CustomXMLParts ?
Many thanks!
Edit: I am leaving for a few days. I appreciate your input a lot! Unfortunately, I won't be able to confirm any solution until my return.

A: If you really can't find a way to register namespace prefix and use it in your XPath, you may be able to resort to ignore the namespace and filter nodes by it's local name. For example (formatted for the sake of readability) :
//*[local-name()='SoftwareName']
   /*[local-name()='Settings']
   /*[local-name()='FormPassword']


text:
Q: My  tag is taking style from another tag <FormWrap>
    <FormImg img src='./img/CB.png' alt="CB" />
    <FormContent>
       <Form onSubmit={handleSubmit}>
           {errorMessage && (
 {errorMessage}
)}
           <FormH1>Log in to your account</FormH1>
           <FormLabel htmlFor='for'>Email</FormLabel>
           <FormInput type='text' value={email} required
            onChange={e => setemail(e.target.value)}/>
           <FormLabel htmlFor='for'>Password</FormLabel>
           <FormInput type='password' value={password} required
            onChange={e => setpassword(e.target.value)}/>
           <FormButton type='submit'>Sign in</FormButton>
     <Navtext>
        <NavtextLink to="/Register">Register</NavtextLink>
     </Navtext>

    </Form>

      </FormContent>
</FormWrap>

export const errorM = styled.p`
    width:1000px;
    height:692px;
    background:black;
    color:white;
    display:grid;
    grid-template-columns: 1fr 6fr;
    position:relative;

    border-radius:10px;
    `

export const FormWrap = styled.div`
    width:800px;
    height:692px;
    background:white;
    color:yellow;
    display:grid;
    grid-template-columns: 1fr 6fr;
    position:relative;

    border-radius:10px;

    @media screen and (max-width: 980px){
        height:95%;
        padding:50px;

    }

    @media screen and (max-width: 720px){
        height:90%;
        padding-left:95px;
    }
`

The thing is that errorM is taking the style from FormWrap even through the one is  and the other is <div.I tried to make inline style but then only that I managed to change was the cooler of the texts tried to change the fond but nothing happened.

A: In your first code example, the
 has the className "errorM".
And in your second code example, you have created a styled component called "errorM".
When you create a styled component the variable should start with a capital letter, for example, ErrorM.
There are two ways to add the style to
 tag.

*

*Applying style to the className.
Change export const errorM = styled.p to .errorM { ... }.

*Using the styled component instead of adding className to
.
Change
{errorMessage}
 to <ErrorM>{errorMessage}</ErrorM>

A: use id to specify particular paragraph
<!DOCTYPE html>

  <title>Browser</title>

Write, edit and run HTML, CSS and JavaScript code online.

This is paragraph


text:
Q: OpenERP New column not showing up in DB Table I am trying to access the field manufacturer_pref from the product.product table from the purchase order report.
This is the module that created the field :
class product_product(osv.osv):
_inherit = 'product.product'
_columns = {
    'manufacturer' : fields.many2one('res.partner', 'Manufacturer'),
    'manufacturer_pname' : fields.char('Manufacturer Product Name', size=64),
    'manufacturer_pref' : fields.char('Manufacturer Product Code', size=64),
    'attribute_ids': fields.one2many('product.manufacturer.attribute', 'product_id', 'Attributes'),
}

I went in the purchase module, edited purchase.py and added this under _columns = {
'manufacturer_pref': fields.related('order_line','manufacturer_pref', type='char', relation='product.product', string='Manufacturer'),

saved, did a
./openerp-server -db My_DB -u=all

and when I get back in pgAdminIII, when I look in purchase_order_line table, the column is not showing up.
Where I am wrong ?


text:
Q: Model Value is not setting I am creating an CRUD Application in Asp.Net Core
After Add Operation I am redirecting to same view with setting model value as null to get another entry
Below is my code
public IActionResult Add(OptionMasterVM model)
    {
        try
        {
            model.QuestionList = context.QuestionMaster.Select(x => new SelectListItem { Text = x.QuestionName, Value = x.QuestionId.ToString() }).ToList();

            if (HttpContext.Request.Method == "POST")
            {
                OptionMaster _optionmaster = new OptionMaster();
                _optionmaster = model.OptionMaster;
                using (var ctx = new QuestionnaireEntities(_configuration))
                {
                    ctx.OptionMaster.Add(_optionmaster);
                    ctx.SaveChanges();
                }
                TempData["Msg"] = "Option Added Successfully , Add Another Option";
                model.OptionMaster.OptionValue = string.Empty;
                model.OptionMaster.OptionRating = 0;
                return View(model);
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex);
        }
        finally
        {
        }
        return View(model);
    }

Here I am setting Option Value to empty and rating to Zero to take next entry , but on view it does not show empty and zero , on view it show previously filled value.

After Setting below code these two fields should be reset but they don't
model.OptionMaster.OptionValue = string.Empty;
model.OptionMaster.OptionRating = 0;

Is there any other way to set model object as null in Asp.net Core ?

A: This can happen because Razor helpers use values from ModelState, rather than the model itself. Your OptionValue is probably displayed using a helper, for example:
@Html.TextBoxFor(m => m.OptionMaster.OptionValue)

When you change model values within an action, you need remove the old values from ModelState before rendering the View.
The easiest way of doing this is to call ModelState.Clear()
model.OptionMaster.OptionValue = string.Empty;
model.OptionMaster.OptionRating = 0;

ModelState.Clear();     // ensure these changes are rendered in the View

return View(model);

A: The values displayed for bound form fields come from ModelState, which is composed based on values from Request, ViewData/ViewBag, and finally Model. After posting, obviously, you'll have values set in Request, which will therefore be the values in ModelState. It works this way, so that when there's a validation error and the user is returned to the form to correct their mistakes, the values they posted will be there for them to edit.
Long and short, you need to follow the PRG (Post-Redirect-Get) pattern. Essentially, after posting, you only return the view on error. If the post is successful, you redirect. This not only clears ModelState, but also prevents accidental re-posts if the user attempts to refresh the page.
If you want to take the user back to the same view, simply redirect to the same action, but you need to do a redirect, not return the view.