Q: How can I download images from a list of links? I have a list of links to images (about 5000 lines), and I need to know how I can download all it fast. Please help me with my code:
import concurrent.futures
import urllib.request

catname = 'amateur'

def getimg (count, endcount):
    while (count < endcount):
      urllib.request.urlretrieve(URLS[count], catname+'/images/'+catname+str(count)+'.jpg')
      URLS[count] = catname+'/images/'+catname+str(count)+'.jpg'
      count = count + 1

with concurrent.futures.ThreadPoolExecutor(max_workers=50) as e:
    e.submit(getimg, 0, 5000)

It works fine but slow.

A: Your code download 5000 images 50 times. Try following:
import concurrent.futures
import urllib.request

catname = 'amateur'

def getimg(count):
    localpath = '{0}/images/{0}{1}.jpg'.format(catname, count)
    urllib.request.urlretrieve(URLS[count], localpath)
    URLS[count] = localpath

with concurrent.futures.ThreadPoolExecutor(max_workers=50) as e:
    for i in range(5000):
        e.submit(getimg, i)


Q: How to reuse bookmarks contextmenu. (Contextmenu commands not issued.) I have a Firefox addon that creates several buttons with dropdowns. Each dropdown contains several menu items representing bookmarks.
Almost identical to bookmark folders or tags on the bookmarks toolbar (after having dragged them there) which also have dropdowns with bookmark menu items.
I would like to reuse bookmarks contextmenu already existing on those latter dropdown menu-items.
I have found this way of doing it partly, but I'l stuck (see below how):
var mi = doc.createElementNS(XUL_NS,'menuitem');
mi.setAttribute('class',        'menuitem-iconic bookmark-item menuitem-with-favicon');
mi.setAttribute('scheme',       'http');
//this gets the existing contextmenu all right
mi.setAttribute("context",      "placesContext");
//this.pp = my own dropdown menupopup,
this.pp.appendChild(mi);

Resulting contextmenu screenshot:

First (minor) problem:
Everything is grayed out until I first right-click on one of the latter dropdown items before right-clicking my own.
Second (major) problem:
When hitting a command/menu-item of the placesContext menu, the commands (e.g. "Open" or "Open in new tab") are not done. Nothing happens.  Is there some attributes that my menu-item misses so that the "placesCmd_open" ignores it or do I really have to override the existing event listeners of placesContext or even different?!


Q: Airflow BashOperator doesn't work but PythonOperator does I seem to have a problem with BashOperator. I'm using Airflow 1.10 installed on CentOS in a Miniconda environment (Python 3.6) using the package on Conda Forge.
When I run airflow test tutorial pyHi 2018-01-01 the output is "Hello world!" as expected.
However, when I run airflow test tutorial print_date 2018-01-01 or
airflow test tutorial templated 2018-01-01 nothing happens.
This is the Linux shell output:
(etl) [root@VIRT02 airflow]# airflow test tutorial sleep 2015-06-01
[2018-09-28 19:56:09,727] {__init__.py:51} INFO - Using executor SequentialExecutor
[2018-09-28 19:56:09,962] {models.py:258} INFO - Filling up the DagBag from /root/airflow/dags
My DAG configuration file, which is based on the Airflow tutorial, is shown below.
from airfl ow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta

import test

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2010, 1, 1),
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

dag = DAG(
    'tutorial',
    'My first attempt',
    schedule_interval=timedelta(days=1),
    default_args=default_args,
)

# t1, t2 and t3 are examples of tasks created by instantiating operators
t1 = BashOperator(
    task_id='print_date',
    bash_command='date',
    dag=dag)

t2 = BashOperator(
    task_id='sleep',
    bash_command='sleep 5',
    retries=3,
    dag=dag)

templated_command = """
    {% for i in range(5) %}
        echo "{{ ds }}"
        echo "{{ macros.ds_add(ds, 7)}}"
        echo "{{ params.my_param }}"
    {% endfor %}
"""

t3 = BashOperator(
    task_id='templated',
    bash_command=templated_command,
    params={'my_param': 'Parameter I passed in'},
    dag=dag)

t4 = BashOperator(
    task_id='hi',
    bash_command = 'test.sh',
    dag=dag,
)

t5 = PythonOperator(
    task_id='pyHi',
    python_callable=test.main,
    dag=dag,
)

t2.set_upstream(t1)
t3.set_upstream(t1)

A: Technically it's not that the BashOperator doesn't work, it's just that you don't see the stdout of the Bash command in the Airflow logs. This is a known issue and a ticket has already been filed on Airflow's issue tracker: https://issues.apache.org/jira/browse/AIRFLOW-2674
The proof of the fact that BashOperator does work is that if you run your sleep operator with
airflow test tutorial sleep 2018-01-01

you will have to wait 5 seconds before it terminates, which is the behaviour you'd expect from the Bash sleep command.


Q: What's the difference in Github between fixing, resolving and closing and issue? Here in Github it refrences 3 ways to discuss a ticket:
https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue

*

*close

*resolve

*fix

I was wondering what the techincally differences are between these 3, they all sound very similar to me.

A: The list you are quoting is not a list of options presented in a menu, it is a list of different ways of saying the same thing.
These are all just keywords which Github recognises when it looks at the description. Different people use different terms, so rather than forcing people to use (and remember) one preferred term, they include multiple possibilities.
The examples below the list use different keywords just for illustration. All the keywords are interchangeable.


Q: How to select fonts more specifically in cairo? In cairo, fonts can be specified by their family name, e.g. 'HelveticaNeueLTStd'. Then, weights and styles can be defined by cairo.FONT_WEIGHT_[NORMAL|BOLD] and cairo.FONT_SLANT_[NORMAL|OBLIQUE|ITALIC], which are constants with integer values. Only these 2 and 3 options are built in. I am wondering, how to select specific weights and styles in case the family have more of them? E.g. Light, Semi-bold, etc.
I am using pycairo 1.10.0 in python 2.7, although these things looks the same in any language.
I could find the solution by guessing, so I will answer my question, but still I am wondering if this is the standard way of doing.

A: Font files have various names and other annotations. In FontForge, you can find these listed in menu Element > Font info. Here as I found cairo is able to identify the font by its TTF names > Family or which is the same its WindowsString. In case of Adobe's Helvetica Neue light this string has the value 'HelveticaNeueLT Std Lt'. Then selecting the font by this name, and setting the slant and weight to normal, the light weight will be used:
context.select_font_face('HelveticaNeueLT Std Lt', \
    cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)

It is possible to find font names by many softwares. On Linux fontconfig is able to list fonts, and the name in the second column what cairo recognizes:
$ fc-list | grep HelveticaNeue
...
/usr/share/fonts/.../HelveticaNeueLTStd-Lt.otf: Helvetica Neue LT Std,HelveticaNeueLT Std Lt:style=45 Light,Regular
...
$ fc-list | sed 's/.*:\(.*,\|\s\)\(.*\):.*/\2/'
...
HelveticaNeueLT Std Lt
...


Q: Button with Navigation to other page in navbar materialize react I wanted to insert buttons in the navbar of materialize to navigate to other pages. How can I create a button that helps me to open another page. I used the "Linked to" from react-router, but it doesn't work. Thank you very much for your response
import { Link } from "react-router-dom";

              How teechr works?

              About us

                <Link to="/chooseachatbottype">Get started!</Link>

            <Link style={navStyle} to="/createquiz1">

Create your quizbot!

            </Link>

                Sign in

```

A: I just tried to clean up your code, as there was a Link outside a li element. This should work:

        How teechr works?

        About us

        <Link to="/chooseachatbottype">Get started!</Link>

        <Link style={navStyle} to="/createquiz1">
          Create your quizbot!
        </Link>

          Sign in

A: pass a prop of target="__blank" should work like in Standart HTML.
Create your Links in const and you have better overview.
Didn't add your Styles...
import React, { Fragment, useEffect } from 'react';
import { Link } from 'react-router-dom';

    const Navbar = () => {

      const links = (
        <Fragment>

            <Link className="link-item" to='/'>Home</Link>

            External Website

        </Fragment>
      )

      return (
        <Fragment>

              {links}

        </Fragment>
      )
    }

    export default Navbar;

Your typo:

src not scr


Q: Using xmlhttp.open async instead of sync I am using xml http to read a XML file and then do something with it. It works fine when I use sync, setting it to "false" when using .open().
var xmlhttp=new XMLHttpRequest();

xmlhttp.open("GET",".."+baseRestUrl+restService+"/"+jmxConnection,false);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
var beanRepArray = xmlDoc.getElementsByTagName("beanRepresentation");

But when I set it to "true", it always says xmlDoc is not defined.
var xmlhttp=new XMLHttpRequest();

xmlhttp.open("GET",".."+baseRestUrl+restService+"/"+jmxConnection,true);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
var beanRepArray = xmlDoc.getElementsByTagName("beanRepresentation");

How should I fix this?


Q: How do I make Discord.JS v13 make a role with Administrator permissions? I've seen a bunch of answers on Stack Overflow showing how to make a role with a colour but it doesn't show how to make it with permissions.
Any ideas?

A: You can create a role with permissions using this:
guild.roles.create({
  name: 'Super Cool Blue People',
  color: 'BLUE',
  reason: 'we needed a role for Super Cool People',
  permissions: ['ADMINISTRATOR', 'KICK_MEMBERS'],
})

I have added two examples above ADMINISTRATOR and KICK_MEMBERS.
Flag List: https://discord.js.org/#/docs/main/stable/class/Permissions?scrollTo=s-FLAGS
Please note that you're recommended to use Permissions.FLAGS.<FLAG-NAME> instead of hard-coding the permission name.

A: A guild's RoleManager#create takes a parameter of type CreateRoleOptions, which has a property permissions of type PermissionResolvable. Therefore, you can create a role with specific permissions by calling:
guild.roles.create({
    permissions: "ADMINISTRATOR"
});


Q: Honeycomb webview flickering jittering My app has a scrollview and a webview inside a LinearLayout.
When the Ads from millenial come in it happens some jittering and some webview parts get white.
I have tried ALL possible parameter combination and nothing works.
Does anyone a better solution or even a explanation?
Notice the blank text in the bottom:

Notice 9 10 11 and 11 sections:

thanks

A: For those having problems with this I have solved it as following -
Compatibility.getCompatibility().setWebSettingsCache(webSettings);

Make sure to implement a Compatibility layer, since following method doesn't work in SDK_INT < 11.
webViewInstance.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

A: I have similar problem with AdMob, which I solved by adding:
    android:layer="software"
to the AdView in my xml layout

A: try adding the attribute android:fadingEdge="none" to the ScrollView in your layout.

A: The answer to this was removing millenial ads. It seems that their animation to bring the ad visible was interfering with the webview stuff.


Q: DataSource.initialzie() vs createConnection() in typeorm. Which one to use? I just started using TypeORM as my main ORM for my server. I have seen some tutorials where they use createConnection() instead of creating a DataSource object and initializing it.
Are they different? Do they have different use cases?
Thanks.

A: createConnection() is the old way to do it. Since typeorm 0.3.x  you should use the DataSource object with DataSource.initialize().


Q: Removing /n from print after web scraping I'm trying to capture some columns from the following link:
https://es.wiktionary.org/wiki/Wikcionario:Frecuentes-(1-1000)-Subt%C3%ADtulos_de_pel%C3%ADculas
The code I've come up with is as follows:
import requests
wiki_url = "https://es.wiktionary.org/wiki/Wikcionario:Frecuentes-(1-1000)-Subt%C3%ADtulos_de_pel%C3%ADculas"
wiki_texto = requests.get(wiki_url).text

from bs4 import BeautifulSoup
wiki_datos = BeautifulSoup(wiki_texto, "html")

wiki_filas = wiki_datos.findAll("tr")
print(wiki_filas[1])

print("...............................")

wiki_celdas = wiki_datos.findAll("td")
print(wiki_celdas[0:])

fila_1 = wiki_celdas[0:]
info_1 = [elemento.get_text() for elemento in fila_1]
print(fila_1)
print(info_1)
info_1[0] = int(float(info_1[0]))
print(info_1)

print("...............................")

num_or = [int(float(elem.findAll("td")[0].get_text())) for elem in wiki_filas[1:]]
palabras = [elem.findAll("td")[1].get_text() for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text() for elem in wiki_filas[1:]]

print(num_or[0:])
print(palabras[0:])
print(frecuencia[0:])

from pandas import DataFrame
tabla = DataFrame([num_or, palabras, frecuencia]).T
tabla.columns = ["Núm. orden", "Palabras", "Frecuencia"]
print(tabla.head())

The problem is that I can't remove the following /n from colums "Palabras" and "Frecuencia":

Any ideas? Thanks in advance.

A: I think, that rstrip() method should help you:
palabras = [elem.findAll("td")[1].get_text().rstrip() for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text().rstrip() for elem in wiki_filas[1:]]

You can also use lstrip for left side and strip() method for both sides of string.
edit: this removes all whitespaces.

A: \n is a newline.
You can remove it either with .replace("\n", ""):
palabras = [elem.findAll("td")[1].get_text().replace("\n", "") for elem in wiki_filas[1:]]
frecuencia = [elem.findAll("td")[2].get_text().replace("\n", "") for elem in wiki_filas[1:]]

Alternatively, .strip() removes any surrounding whitespace.


Q: can i put the form-login-page html in a library for a webapp? I was trying to create an app with login page authentication. And for the same i added <form-login-page> into the web.xml (as shown below).
I jar'ed the logon.html and logonerror.html , and added them as a library along with the .war webapp file. (under WEB-INF/lib/logon.jar) .
But when I am deploying the app , am getting ERROR 404 , logon.html not found error.
Any pointers to why ? Cant i keep the logon files (htmls,js,css files) in a library ?
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>MyFilter</filter-class>
     <init-param>
        <param-name>Domainname</param-name>
        <param-value></param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<security-constraint>
    <web-resource-collection>
        <web-resource-name>SecuredResources</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>Default_Role</role-name>
    </auth-constraint>
        <user-data-constraint>
         <transport-guarantee>CONF</transport-guarantee>
    </user-data-constraint>
</security-constraint>

<login-config>
    <auth-method>FORM</auth-method>
    <form-login-config>
      <form-login-page>/logon.html</form-login-page>
      <form-error-page>/logonerror.html</form-error-page>
    </form-login-config>
  </login-config>

   <security-role>
    <role-name>Default_Role</role-name>
  </security-role>

</web-app>

A: My understanding is that a WAR will only expose the resources contained within its own root file structure. Hence the work-arounds (weblets, Maven config) mentioned in the answers to this question. You could make a custom build script that unpacked the content of logon.jar into your WAR, but I definitely wouldn't recommend that sort of hack. With a little more information concerning why you want to do this someone may be able to provide a better approach.

A: As far as I understand, html files should be placed in a WAR instead of a JAR because those are web resources. JAR file should only contain classes/resources that would be looked up by your web components (e.g. Servlet, JSP) using class loading mechanism.


Q: Optimizing svg using scour or any other optimizer in Python I have been using scour and it works well.
I would like to use it inside a Python app instead of a cli.
I would like the output to be the same as when I run the following command on CMD:
scour -i input.svg -o output.svgz --enable-viewboxing --enable-id-stripping \
  --enable-comment-stripping --shorten-ids --indent=none
Can't find any documentation how to call this function inside a python application

A: In the scour download, there is a testscour.py that you could use to see how you can access scour from within the code instead over the cli.
When I was finally solving my mostly similar scour problem, I did it like this:
from scour import scour
import re

with open(svg_file, 'r') as f
    svg = f.read()

scour_options = scour.sanitizeOptions(options=None) # get a clean scour options object
scour_options.remove_metadata = True # change any option you like
clean_svg = scour.scourString(svg, options = scour_options) # use scour


Q: Union types with TypeScript and React I want a component to accepts different props based on the value of a given, specific one. Something like the following.
const Button: React.FC<TButton> = ({ href, children, ...rest }) => {
  if (href) {
    return {children}
  }

  return <button {...rest}>{children}</button>
}

type TButton = { href: string & IAnchor } | { href: undefined & IButton }

interface IAnchor extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}
interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {}

Thing is, can't figure how to go through this properly. I mean, it seems the conditions aren't being parsed or interpreted correctly.
If you want to have a closer look at the issue, please refer to this StackBlitz.

A: It seems that you essentially try to use discriminated union. But it seems that it is not working with ...rest. So to make it work

*

*Add additional property to both interfaces, say type which will be used as discriminant
interface IAnchor extends React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement> {
    type: 'anchor'
    href: string
}

interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {
    type: 'button'
}

*Accept porps and than destruct them in condition branch
const Button: React.FC<TButton> = (props): JSX.Element => {
    if (props.type === 'anchor') {
        const { type, href, children, ...rest } = props;
        return (

                {children}

        )
    }
    const { type, children, ...rest } = props;
    return <button {...rest}>{children}</button>
}

See working example

A: I took a look at your StackBlitz and was able to approach this using the ts-toolbelt library:
First, let's define your two different possible prop types (all anchor props and all button props), combine them as a strict union and use a type guard to let our React component know when we're using which set of props:
import { Union } from 'ts-toolbelt'

type TButton = Union.Strict<IAnchor | IButton>

interface IAnchor extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}

interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {}

const isAnchor = (props: TButton): props is IAnchor => {
  return props.href !== undefined;
}
const isButton = (props: TButton): props is IButton => {
  return props.type !== undefined
}

Now, let's write our custom component that can either be a button or an anchor:
const Button: React.FC<TButton> = ({ children, ...props }): JSX.Element => {
  if (isAnchor(props)) {
    return (

        {children}

    )
  } else if (isButton(props)) {
    return <button {...props}>{children}</button>
  }
}

You can view it working in this StackBlitz.


Q: JPA oneToMany with List and JoinTable I am having a Tournament class and a Member class.
Only tournament has members (that is the information that I need) so in the tournament class I have:
@OneToMany(fetch = FetchType.LAZY,
        cascade = CascadeType.PERSIST, orphanRemoval=true)
@JoinTable(name = "tournament_players",
joinColumns={@JoinColumn(name="tournament_id", nullable=false)},
inverseJoinColumns={@JoinColumn(name="member_id", nullable=false)})
List<Member> players;

The ids are auto generated integers.
When I have only one tournament everything its ok when I set the members.
If a I add a member already existed in tournament 1 to tournament 2 then I get a constraint violation which is correct from what I have read.
 Unique index or primary key violation: "UK_9JMTVNIY5RJ4A9S9XCI40NQGJ_INDEX_9 ON PUBLIC.TOURNAMENT_PLAYERS(TOURNAMENT_ID)

My question is what is the proper solution to my problem?

A: I think what you really need is ManyToMany relationship.
Because in your case, one Tournament can have many Member(s), and Member can follow many Tournament(s).
If you use OneToMany, the JPA provider will check if the Member already has Tournament assigned, and will fail to add if it true


Q: Multiple/same data I try to make condition where i delete data before insert data to prevent multiple data but it didnt work | even the data in table become empty || 'id_lokasi' is my column name in table - database
$factpelanggan4 = DB::connection('clickhouse')
        ->select("SELECT t.id_tahun, l.id_lokasi, stage.jml_pelanggan
    from dim_tahun t
    inner join stage_pelanggan stage on t.tahun = stage.years
    inner join dim_lokasi l on stage.city_id = l.id_kota
    WHERE (stage.country_id = l.id_negara)
    ORDER BY t.id_tahun ASC , l.id_lokasi ASC, stage.jml_pelanggan ASC
    ");

    foreach ($factpelanggan4 as $value) {
        $tahun_id[] = $value['t.id_tahun'];
        $lokasi_id[] = $value['l.id_lokasi'];
        $jml[] = $value['stage.jml_pelanggan'];
    }
    DB::connection('clickhouse')->table('fakta_pelanggan')->where('id_lokasi', $lokasi_id)->delete();
    //DB::connection('clickhouse')->table('fakta_pelanggan')->where('id_lokasi', Not Null)->delete();

    foreach ($factpelanggan4 as $key => $value) {
        $arrayInsert = array(
            'id_tahun' => $tahun_id[$key],
            'id_lokasi' => $lokasi_id[$key],
            'jml_pelanggan' => $jml[$key],
        );
        DB::connection('clickhouse')->table('fakta_pelanggan')->insert($arrayInsert);
        $key++;
    }

A: You should avoid deleting if you're just inserting, or deleting then inserting. If something goes wrong, you'd be left with no data similar to a truncate. What you really should be doing is inserting or updating.
You can do this manually, selecting, then either inserting or updating, separately. Or you can use firstOrCreate, firstOrNew, updateOrCreate or similar approaches.
Since you're working on multiple records at once, you might try an upsert for updating/inserting multiple records at once:
https://laravel.com/docs/9.x/eloquent#upsert
$toInsertOrUpdate = [];
foreach ($factpelanggan4 as $key => $value) {
    // I don't quite follow your looping logic.
    // What you wrote with $key++ after each loop before
    // will be completely ignored since each loop overwrites it.
    // This is a factored version of what you wrote before.
    // Please double check it to make sure it does what you want.
    $toInsertOrUpdate[] = [
        'id_tahun' => $tahun_id[$key],
        'id_lokasi' => $lokasi_id[$key],
        'jml_pelanggan' => $jml[$key],
    ];
}

// these columns together identify duplicate records.
$uniqueIdentifyingColumns = ['id_tahun','id_lokasi','jml_pelanggan'];

// when a duplicate record is found, only these columns will be updated
$columnsToUpdateOnDuplicate = ['id_tahun','id_lokasi','jml_pelanggan'];

$tbl = DB::connection('clickhouse')->table('fakta_pelanggan');

$tbl->upsert(
    $toInsertOrUpdate,
    $uniqueIdentifyingColumns,
    $columnsToUpdateOnDuplicate
);


Q: PHP sum array values with same keys This is the original main array:
Array
(
[0] => Array

    (
        [subtotal] => 0.6000
        [taxes] => 0.0720
        [charged_amount] => 0.6720
        [total_discount] => 0.0000
        [provinceName] => BC
        [store_key] => 1
        [store_id] => 5834
        [categories] => Array
            (
                [2] => 0.6000
                [4] => 0
                [3] => 0
            )

    )

[1] => Array
    (
        [subtotal] => 29.8500
        [taxes] => 2.3270
        [charged_amount] => 20.2370
        [total_discount] => 11.9400
        [provinceName] => MB
        [store_key] => 9
        [store_id] => 1022
        [categories] => Array
            (
                [2] => 0
                [4] => 29.8500
                [3] => 0
            )

    )

[2] => Array
    (
        [subtotal] => 0.3000
        [taxes] => 0.0390
        [charged_amount] => 0.3390
        [total_discount] => 0.0000
        [provinceName] => NB
        [store_key] => 8
        [store_id] => 1013
        [categories] => Array
            (
                [2] => 0.3000
                [4] => 0
                [3] => 0
            )

    )

[3] => Array
    (
        [subtotal] => 24.3100
        [taxes] => 1.1830
        [charged_amount] => 10.2830
        [total_discount] => 15.2100
        [provinceName] => NL
        [store_key] => 4
        [store_id] => 3033
        [categories] => Array
            (
                [2] => 24.3100
                [4] => 0
                [3] => 0
            )

    )

[4] => Array
    (
        [subtotal] => 1116.3400
        [taxes] => 127.6960
        [charged_amount] => 1110.0060
        [total_discount] => 134.0300
        [provinceName] => ON
        [store_key] => 2
        [store_id] => 1139
        [categories] => Array
            (
                [2] => 85.7300
                [4] => 143.2800
                [3] => 887.3300
            )

    )

[5] => Array
    (
        [subtotal] => 10.8500
        [taxes] => 1.4100
        [charged_amount] => 12.2600
        [total_discount] => 0.0000
        [provinceName] => ON
        [store_key] => 5
        [store_id] => 1116
        [categories] => Array
            (
                [2] => 10.8500
                [4] => 0
                [3] => 0
            )

    )

)
I just need to add the values of the array [categories] with same keys and use it further to print the total, but not getting correct output, can someone help me out to get the desired result:
Desired result
An array with same keys but total of individual array values
Array ( [2] => 0.9000 [4] => 29.8500 [3] => 1.5 )

NOTE: Initial array is dynamic can have n number of key value pair
Thanks

A: The first thing that you need to do is iterate through the outer array.  Then, for each row in the outer array, you and to iterate through each entry in the category element.  So this means that we have two foreach loops.  Inside the inner foreach, we simply set the value for the current index to be the value of the same index on a 'sum' array (if it doesn't already exist), or increment the value of that index if it already exists in the 'sum' array.
<?php
$sumArray = array();

foreach($outerArray as $row)
{
    foreach($row["categories"] as $index => $value)
    {
        $sumArray[$index] = (isset($sumArray[$index]) ? $sumArray[$index] + $value : $value);
    }
}
?>

Demo using your example array


Q: Final circle: Knights of the Round Table A friend of mine had a job interview. The question he was asked sounded like this:

Is it possible to create a given number of similarly typed objects virtually arranged in a circle such that each of them contains two final references to its left (clockwise) and right (counterclockwise) neighbours?

If this seems too abstract to you, there was a more concrete interpretation. Think about the Knights of the Round Table. Suppose King Arthur considers their union and arrangement at the table constant and inviolable. To express this idea, he created the following simplified model of a Knight at the Table:
public class Knight {
    private final String name;
    private final Knight leftNeighbour;
    private final Knight rightNeighbour;

    public final Knight getLeft() {
        return leftNeighbour;
    }

    public final Knight getRight() {
        return rightNeighbour;
    }

    @Override
    public final String toString() {
        return name;
    }
}

Note that all fields are final. Once set, they cannot be changed. The name field here merely illustrates individual properties of each object (there may also be other fields, final or not, but for the sake of simplicity, they are omitted). The primary interest here are the leftNeighbour and rightNeighbour fields. Being final, they "fasten" the circle making its structure immutable yet consisting of individual objects.
There is one problem, however. As you might have noticed, the above class outline lacks very important detail: constructor(s). There must be a place where the final fields are assigned. To create constructor(s) - that was exactly the problem the interviewer proposed to solve - given the desired number of knights and their names in counterclockwise order, you should create corresponding objects and fill their fields. You may create as many constructors as you need and also may use instance initialization blocks and static factory methods, if you like, just don't touch the above lines. There should be at least one public constructor or a static factory method that returns one of the knights created. For example, the verification code below relies on the
public Knight(int knightCount, IntFunction<String> nameGenerator)

constructor, where nameGenerator of type java.util.function.IntFunction<String> is just a function that supplies a knight's name in response to its index. You may use an array of names instead, if you like.
My friend said that this is possible only via reflection - first create objects giving their leftNeighbour and rightNeighbour fields dumb values (e.g. null), then gain access to these fields and assign them meaningful values. But the interviewer said that the use of reflection, for the purpose of solving this problem, is prohibited. My friend concluded that the problem is unsolvable under such conditions. Indeed, to create a Knight, you need to know his neighbours first since it is not possible to assign a final field after exit from a constructor; but for this you need to know the neighbours of these neighbours including that very first Knight that has not yet been created - the chicken or the egg dilemma.
At first, I thought exactly the same. But after some thinking I come to the conclusion that the problem is not as hopeless as it appeared at the beginning. Could you provide a solution? You may use this verification code:
public static void testRoundTable(int size, IntFunction<String> nameGenerator,
            boolean printNames) {
    Knight k = new Knight(size, nameGenerator);
    Knight a = k;
    int c = 0;
    do {
        if (printNames)
            System.out.println(a);
        c++;
        a = a.getRight();
    } while (a != k);
    if (c != size)
        throw new RuntimeException("Wrong knight count: " + c);
    if (printNames)
        System.out.println();
    a = k;
    c = 0;
    do {
        a = a.getLeft();
        if (printNames)
            System.out.println(a);
        c++;
    } while (a != k);
    if (c != size)
        throw new RuntimeException("Wrong knight count: " + c);
    if (!printNames)
        System.out.println(c + " knights created");
    System.out.println();
}

public static void main(String[] args) {
    testRoundTable(10, i -> "Knight #" + (i + 1), true);
    testRoundTable(20_000_000, i -> "Knight", false);
}

The output should be as follows:
Knight #1
Knight #2
Knight #3
Knight #4
Knight #5
Knight #6
Knight #7
Knight #8
Knight #9
Knight #10

Knight #10
Knight #9
Knight #8
Knight #7
Knight #6
Knight #5
Knight #4
Knight #3
Knight #2
Knight #1

20000000 knights created

Important notes:

*

*Reflection is strongly prohibited. It was either unknown at the time of King Arthur or considered blasphemous.

*The number of knights that you will be requested to create might be limited only by available memory, so be ready to create very large tables (e.g. with 20000000 knights, as above), without causing a stack overflow.

Here's my solution just for two knights:
public Knight(int knightCount, IntFunction<String> nameGenerator) {
    name = nameGenerator.apply(0);
    Knight other = new Knight(this, nameGenerator.apply(1));
    leftNeighbour = other;
    rightNeighbour = other;
}

private Knight(Knight mate, String name) {
    this.name = name;
    leftNeighbour = mate;
    rightNeighbour = mate;
}

This idea can be extended to the case of three, four and any other small number of knights. Each knight is responsible for creating the next one:
public Knight(int knightCount, IntFunction<String> nameGenerator) {
    name = nameGenerator.apply(0);
    Knight other = new Knight(1, knightCount, this, this, nameGenerator);
    rightNeighbour = other;
    for (int i = 1; i <= knightCount - 2; i++)
        other = other.rightNeighbour;
    leftNeighbour = other;
}

private Knight(int index, int knightCount, Knight first, Knight previous,
        IntFunction<String> nameGenerator) {
    name = nameGenerator.apply(index);
    leftNeighbour = previous;
    if (index == knightCount - 1)
        rightNeighbour = first;
    else
        rightNeighbour = new Knight(index + 1, knightCount, first, this, nameGenerator);
}

However, this implementation becomes increasingly difficult and would surely cause a stack overflow when the count reaches a million or so. On my computer, the "red line" is 5614.


Q: Repositories links not working yum.conf in CentOS 6 I am running a linux server using RedHat and Centos 6.4
I need to install gcc onto the server, so I have been trying to use yum to install gcc for me, however I seem to have a bit of an issue with installing and updating packages using yum due to the yum.conf file.
If I open my current yum.conf file, I see the following code:
[main]
cachedir=/var/cache/yum
debuglevel=2
logfile=/var/log/yum.log
pkgpolicy=newest
distroverpkg=redhat-release
tolerant=1
exactarch=1

[base]
name=Red Hat Linux $releasever - $basearch - Base
baseurl=http://mirror.dulug.duke.edu/pub/yum-repository/redhat/$releasever/$basearch/

[updates]
name=Red Hat Linux $releasever - Updates
baseurl=http://mirror.dulug.duke.edu/pub/yum-repository/redhat/updates/$releasever/

and whenever I try to run a yum command - for example, "yum update" I get the following errors in my terminal:
[root@SERVER etc]# yum update
Gathering header information file(s) from server(s)
Server: Red Hat Linux 6 - x86_64 - Base
retrygrab() failed for:
  http://mirror.dulug.duke.edu/pub/yum-repository/redhat/6/x86_64/headers/header.info
  Executing failover method
failover: out of servers to try
Error getting file http://mirror.dulug.duke.edu/pub/yum-repository/redhat/6/x86_64/headers/header.info
[Errno 4] IOError: <urlopen error >
[root@SERVER etc]#

I believe this is due to some old yum mirrors being down, however I cannot find any reference to a proper set of repositories to use in my yum.conf file which would work on CentOS 6.4
The question is: does anybody know where I can find a set of repositories that will work in this scenario? I know that the Yum website is now found at http://yum.baseurl.org/ however I cannot see anything clear with regard to what repositories I should be putting in my yum.conf file..
I am obviously a linux newbie, so if I am missing something important, flame me gently...

A: Looks like you have a mix of CentOS and RedHat bits. Delete whatever you added. CentOS is easy (examples below). For RedHat if you aren't a registered machine you'll want to use the DVD ISO as source (baseurl=file:///media) or maybe attach to a public EPEL.
Here's a CentOS /etc/yum.conf.
[main]
cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release

And then you should have a few repos that already exist in /etc/yum.repos.d (base/debuginfo/media/vault). Hers's /etc/yum.repos.d/CentOS-Base.repo
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#released updates
[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

#contrib - packages by Centos Users
[contrib]
name=CentOS-$releasever - Contrib
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib
#baseurl=http://mirror.centos.org/centos/$releasever/contrib/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6


Q: How to implement allowed fields mapping with array object in javascript? I have two object one for allowed fields another one for overall response. I need to map overall response with allowed fields. Existing code working fine with object but not works with array object fields. Kindly suggest the better solution to implement field mapping.
let allowedFields = [
                "id",
                "candidate_id",
                "prospect",
                "location",
                "jobs.id",
                "jobs.name"
            ]

let data = {
                "id": 34050740004,
                "candidate_id": 30068728004,
                "prospect": false,
                "applied_at": "2022-06-10T18:00:52.034Z",
                "rejected_at": null,
                "last_activity_at": "2022-06-10T18:03:05.070Z",
                "location": null,
                "jobs": [
                    {
                        "id": 4354756004,
                        "name": "E2E Testing",
                        "email": "manikandanp97@gmail.com"
                    },
                    {
                        "id": 65765,
                        "name": "E2E consensys",
                        "email": "mani.raina@gmail.com"
                    }
                ]
            }

Below code is working fine with objects, but field mapping is not working for array objects.
async function mapAllowedFields(allowedFields, data) {
            const response = {}
            allowedFields.forEach((loc) => {
                const fields = loc.split(".")
                let conditionObj = data
                let responseObj = response
                for (let i = 0; i < fields.length; i++) {
                    const key = fields[i]
                    conditionObj = conditionObj?.[key]
                    if (i === fields.length - 1) {
                        responseObj[key] = conditionObj
                    } else if (responseObj[key] === undefined) {
                        responseObj[key] = {}
                    }
                    responseObj = responseObj[key]
                }
            })

            return response
        }

Expected results only with allowed fields be like, fields that does not exist in allowed fields array like applied_at, last_activity_at, rejected_at and in jobs array object, email field should be removed from result
let result = {
                "id": 34050740004,
                "candidate_id": 30068728004,
                "prospect": false,
                "location": null,
                "jobs": [
                    {
                        "id": 4354756004,
                        "name": "E2E Testing",
                    },
                    {
                        "id": 65765,
                        "name": "E2E consensys",
                    }
                ]
            }

A: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#syntax

const allowedFields = [
  "id",
  "candidate_id",
  "prospect",
  "location",
  "jobs",
  "name"
];
const txt = [
  {
    "id": 34050740004,
    "candidate_id": 30068728004,
    "prospect": false,
    "applied_at": "2022-06-10T18:00:52.034Z",
    "rejected_at": null,
    "last_activity_at": "2022-06-10T18:03:05.070Z",
    "location": null,
    "jobs": [
      {
        "id": 4354756004,
        "name": "E2E Testing",
        "email": "manikandanp97@gmail.com"
      },
      {
        "id": 65765,
        "name": "E2E consensys",
        "email": "mani.raina@gmail.com"
      }
    ]
  },
  {
    "id": 34050740004,
    "candidate_id": 30068728004,
    "prospect": false,
    "applied_at": "2022-06-10T18:00:52.034Z",
    "rejected_at": null,
    "last_activity_at": "2022-06-10T18:03:05.070Z",
    "location": null,
    "jobs": [
      {
        "id": 4354756004,
        "name": "E2E Testing",
        "email": "manikandanp97@gmail.com"
      },
      {
        "id": 65765,
        "name": "E2E consensys",
        "email": "mani.raina@gmail.com"
      }
    ]
  }
];
const obj = JSON.stringify(txt, allowedFields);
document.getElementById("demo").innerHTML = JSON.stringify(JSON.parse(obj), null, 4);


Q: Incremental build in TFS 2017 - How to build only code that has changed from the last build? We are currently building an incremental build but it is building all the projects in the proj file regardless of if those projects have changed.  Is there a way that a script can be written that would pull out only what has changed and checked in or more of an actual incremental build?
When I build a solution, I should only get the changed dlls not all (which includes Microsoft and other 3rd party dlls which are never changed.
TFS 2017 always delivered all files - changed and unchanged, but I need only changed.
I have tried the following but it did not work:
<PropertyGroup>
  <SkipClean>true</SkipClean>
  <SkipInitializeWorkspace>true</SkipInitializeWorkspace>
  <ForceGet>false</ForceGet>
  <IncrementalBuild>true</IncrementalBuild>
</PropertyGroup>


Q: Check if date object is over one year old I would like to see if a date object is over one year old! I don't know how to even compare them due to the leap years etc..
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();

if(???) {
    console.log("it has been over one year!");
} else {
    console.log("it has not gone one year yet!");
}

A: You could make the check like this
(todayDate - oldDate) / (1000 * 3600 * 24 * 365) > 1

You can see and try it here:
https://jsfiddle.net/rnyxzLc2/

A: This code should handle leap years correctly.
Essentially:
If the difference between the dates' getFullYear() is more than one,
or the difference equals one and todayDate is greater than oldDate after setting their years to be the same,
then there's more than a one-year difference.

var oldDate = new Date("Oct 2, 2014 01:15:23"),
    todayDate = new Date(),
    y1= oldDate.getFullYear(),
    y2= todayDate.getFullYear(),
    d1= new Date(oldDate).setFullYear(2000),
    d2= new Date(todayDate).setFullYear(2000);

console.log(y2 - y1 > 1 || (y2 - y1 == 1 && d2 > d1));

A: use getFullYear():
fiddle: https://jsfiddle.net/husgce6w/
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
var thisYear = todayDate.getFullYear();
var thatYear = oldDate.getFullYear();
console.log(todayDate);
console.log(thatYear);

if(thisYear - thatYear > 1) {
    console.log("it has been over one year!");
} else {
    console.log("it has not gone one year yet!");
}


Q: c++ Observer pattern: Is it a sensible design to make subject to be an observer at the same time? In observer pattern, subject notices a change to observer. But I also need subject to be notified by observer.
I went something like this for the purpose:
//Observer.h
class Subject;
class Observer{
public:
    void update(Subject* p_subject);
    void Subject_Notify();
private:
    Subject* subject;
}

//Subject.h
#include "Observer.h"
class Subject{
public:
    void observer_notify()
    {
        observer->update(this);
    }
    void update(Observer* observer);
private:
    Observer* observer;
}

//Observer.cpp
#include "Observer.h"
#include "Subject.h"
void Observer::update(Subject* p_subject)
{
    //do something with p_subject
}

void Observer::Subject_Notify()
{
    subject->update(this);
}

The code seems complicated and I am not sure if I am going in the right direction. Is there alternative or is this just ok?


Q: Primefaces scrollable datatable header alignment I know it is often discussed issue but I didn't find any reasonable solution. I have a datatatable with filtering, sorting, lazy loading and dynamic columns. If I set width of a datatable to 100% and scroll to right, cells don't align to a header. Is some simple solution?  I'm using primefaces-5.0.

XHTML:
<p:dataTable
    var="rec"
    value="#{bean.list}"
    selection="#{bean.selectedRow}"
    selectionMode="single"
    rowKey="#{rec.id}"
    resizableColumns="true"
    rows="4"
    paginator="true"
    paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
    filteredValue="#{bean.filteredList}"
    scrollable="true"
    style="width: 100%;">

    <p:columns value="#{bean.list}"
       width="150"
       var="column"
       sortBy="#{rec[column.property]}"
       filterBy="#{rec[column.property]}"
       filterMatchMode="contains" >
       <f:facet name="header">
           <h:outputText value="#{column.header}" />
       </f:facet>
       <h:outputText value="#{rec[column.property]}" />
    </p:columns>
</p:datatable>


Q: CMake undefined reference to irrklang I'm trying to link up CMake for a old project, this is the relevant structure:
Project
  -build
  -src
  -res/include/irk
             -all the irrklang header files

In my top-level CMakeLists.txt I have:
target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/res/include/irk/")

I believe that's all that is needed since IrrKlang is a header-only library as far as I know. When I try to build however, I get this error:
undefined reference to `irrklang::createIrrKlangDevice(irrklang::E_SOUND_OUTPUT_DRIVER, int, char const*, char const*)'

For some reason CMake doesnt pick up on the library and I've no idea why.


Q: Can an iOS app "know" if it's a beta distribution through Apple's Testflight? I'm in the middle of transitioning from TestFlight's native app to Apple's TestFlight through iTunes Connect. My Xcode Project is set up with a beta scheme and a distribution scheme, so I can include a number of debug features in the beta version using a custom flag (lots of #ifndef PROD in the debug code). The beta scheme also has a separate bundle identifier and bundle display name, so that beta and distribution can live side by side on a tester's phone (separate icons, etc).
With Apple's TestFlight, the bundle ID needs to be the same for beta and for distribution. Because of that, I can't include any of the debug features in my current arrangement.
I'm looking for a way around this. One possibility I thought of was to create another app in iTunes Connect solely for testing, but that seems dirty. Is there a conditional or a way to test, in the code, whether the current build is a TestFlight build or a distribution build? Or is there a better way to handle this?
Thanks in advance!


Q: Sign custom JRE for an Java App in macOS Catalina I bundled my java application as an.app. Inside this bundle is a jre, created with jLink. (Contents/Resources/jre/jre_11.../) I now try to sign it with --deep so it signs everything recursively, but it doesn't seem to work. When I try to notarise the app, I get an error, that the bin files and dynamic libraries are not signed.
This is the command I use:
codesign --force --deep --timestamp --entitlements ./sign.entitlements --options runtime --sign "AppleDevIDStuff" ../../../Desktop/Launch.app/

*

*code sign doesn't give me any errors

*command codesign -vvv --deep --strict ../../../Desktop/Launch.app/ says everything is ok

*If I try to sign Contents/Resources/jre/jre_.../bin I get an error, saying this directory is not a valid bundle (which is true)

*Signing the JRE as a directory for itself, outside the app, gives me the same error (Not a valid package)

*jPackage cannot be used, because it produces a different layout for .app, my application needs a specific layout for the contents inside .app.

I didn't find any guide how to sign a custom created JRE and somehow I'm unable to sign this.
So the question is basically: How to sign a custom JRE created with jLink?


Q: Java: Need to extract a number from a string I have a string containing a number. Something like "Incident #492 -  The Title Description".
I need to extract the number from this string.
Tried
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(theString);
String substring =m.group();

By getting an error
java.lang.IllegalStateException: No match found

What am I doing wrong?
What is the correct expression?
I'm sorry for such a simple question, but I searched a lot and still not found how to do this (maybe because it's too late here...)

A: You are getting this exception because you need to call find() on the matcher before accessing groups:
Matcher m = p.matcher(theString);
while (m.find()) {
    String substring =m.group();
    System.out.println(substring);
}

Demo.

A: There are two things wrong here:

*

*The pattern you're using is not the most ideal for your scenario, it's only checking if a string only contains numbers.  Also, since it doesn't contain a group expression, a call to group() is equivalent to calling group(0), which returns the entire string.

*You need to be certain that the matcher has a match before you go calling a group.
Let's start with the regex.  Here's what it looks like now.

Debuggex Demo
That will only ever match a string that contains all numbers in it.  What you care about is specifically the number in that string, so you want an expression that:

*

*Doesn't care about what's in front of it

*Doesn't care about what's after it

*Only matches on one occurrence of numbers, and captures it in a group

To that, you'd use this expression:
.*?(\\d+).*

Debuggex Demo
The last part is to ensure that the matcher can find a match, and that it gets the correct group.  That's accomplished by this:
if (m.matches()) {
    String substring = m.group(1);
    System.out.println(substring);
}

All together now:
Pattern p = Pattern.compile(".*?(\\d+).*");
final String theString = "Incident #492 -  The Title Description";
Matcher m = p.matcher(theString);
if (m.matches()) {
    String substring = m.group(1);
    System.out.println(substring);
}

A: You need to invoke one of the Matcher methods, like find, matches or lookingAt to actually run the match.


Q: Selections in D3: how to use parentNode.appendChild? I'd like to deal with overlapping SVG elements in D3.js using this method from StackOverflow.
However, due to the nature of my code, I want to use a D3 selector rather than this to re-add the element to the DOM. My question is: how can I use a D3 selector to get the relevant node?
This is how the original example does it:
this.parentNode.appendChild(this);

This is my attempt, which fails with "Uncaught TypeError: Cannot call method 'appendChild' of undefined":
var thisNode = d3.select("#" + id);
thisNode.parentNode.appendChild(thisNode);

This JSFiddle (adapted from the original example) demonstrates the problem: http://jsfiddle.net/cpcj5/
How is my D3 selection different from the this in the original example? I tried using thisNode.node().parentNode.appendChild(thisNode) but that also failed.

A: The .parentNode method is for a DOM element, not a d3 selection.
To access the DOM element from a d3 selection is a little tricky, and there are often better ways to achieve what you want to do. Regardless, if you have a single element selected, it will be the first and only item within the first item of a d3.selection - i.e. you need to access it like so:
var someIdDOMelement = d3.select("#someid")[0][0];

An edited example of your original using this: http://jsfiddle.net/cpcj5/1/
If you have the id and specifically want to get the DOM element, I'd just go with getElementById:
var someIdDOMElement = document.getElementById("someid")

Looking at d3 documentation for binding events using on, we can see that, within the function you bind, the this variable is the DOM element for the event which was triggered. So, when dealing with event handling in d3, you can just use this to get the DOM element from within a bound function.
But, looking at your code, I think it's easier to stick with the original implementation for re-appending the node using the original javascript methods, and then creating a d3 selection using d3.select on the dom element bound to this. This is how the original code does it: http://jsfiddle.net/cpcj5/3/
If you have any difficulties caused by this, please comment so I can address them.

A: You can also use selection.node() in D3:
var thisNode = d3.select("#" + id);
thisNode.node().parentNode.appendChild(thisNode.node());


Q: Different behaviour NSAllowsArbitraryLoadsInWebContent IOS 10.1 and 10.2 When loading a certain url in UIWebView in IOS 10.1 it is failing on

Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made"

However the same webview loads fine in iOS 10.2
I can load the url in both 10.1 and 10.2 if I use NSAllowsArbitraryLoads = YES but only in 10.2 with NSAllowsArbitraryLoadsInWebContent = YES
I tested the URL with nscurl --ats-diagnostics and it passes all tests
I think that the issue may have something to do with an ip location validation within the webpage.
Are the differences between 10.1 and 10.2 in the handling of App Transport Security Settings? Are these documented?
---- Edit -----
I managed to resolve my issue by looking at the error in didFailLoadWithError. This told me exactly what the url was that was causing the failure. I added this url to my Exception Domains with NSExceptionRequiresForwardSecrecy=NO (determined using the ats diagnostics)
This fixed my problem but I still would like to understand the differences in the two versions 10.1 & 10.2.

A: Yes, earlier versions of iOS 10 did still enforce the forward secrecy requirement of app transport security in web views even with the NSAllowsArbitraryLoadsInWebContent key. That was a bug, that was fixed by Apple. The problem is that earlier versions of iOS shipped with the bug so you must be able to handle it, which isn't always possible if you don't know all the possible URLs that your Web you could navigate to. This may be part of the reason that Apple has extended their deadline for enabling app transport security and all apps submitted to the App Store.


Q: Wpf Clickonce deployment I tried to do the clickonce deployment of a simple demo project. The project is deployed but when I click on the RUN button it gives the error that this application can not start and when I try to launch the application It gives the error that this application can not be installed. What wrong I am doing?

A: Usually the log file from a ClickOnce installation tells you what the problem is. I suggest you take a look at that file.
In my experience, it usually is some dependency that's missing.
Here's a useful guide: Troubleshooting Specific Errors in ClickOnce Deployments
If you are using the Google Chrome web browser to launch ClickOnce applications, then take a look at the Chrome Extension for ClickOnce.


Q: asp.net website giving errors after upload to server, works fine on local server I have an asp.net website which when i put it up on my college server gave me an error when i retireved the inner text of an xml element and converted it to date which should be selected on the calender control.
The error i recieve is-
String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error:

Line 91:                 displayEvent.Text += "On-" + node.SelectSingleNode("date").InnerText + "
";
Line 92:                 displayEvent.Text += "Contact Number-" + node.SelectSingleNode("phone").InnerText + "
";
Line 93:                 DateTime dts1 = Convert.ToDateTime(node.SelectSingleNode("date").InnerText);
Line 94:                 Calendar1.SelectedDate = dts1;
Line 95:                 latitude = node.SelectSingleNode("latitude").InnerText;

The xml file looks like-
<root1><data><event_name>Christmas Party</event_name><event_desc>The annual christmas bash is happening as planned. This year there is bound to be more excitement.</event_desc><date>12/25/2011</date><phone>111-111-1111</phone><latitude>43.700573</latitude><longitude>-79.296661</longitude></data><data><event_name>New Year Party</event_name><event_desc>Ring in the new year with us, the party is going to be a never before event with a huge celebrity guest line up.</event_desc><date>12/31/2011</date><phone>222-222-2222</phone><latitude>43.728572</latitude><longitude>-79.48669</longitude></data><data><event_name>Jt Birthday</event_name><event_desc>It's jasmeet's birthday. He wanted to get a samsung nexus s, so i should try and buy that for him.</event_desc><date>12/11/2011</date><phone>333-333-3333</phone><latitude>45.515849</latitude><longitude>-73.553417</longitude></data></root1>

Also i am using the latitude and longitude for showing them on a map. It also has problem converting the inner texts of these elements to double
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:

Line 75:     {
Line 76:         GMap1.reset();
Line 77:         GMap1.addGMarker(new GMarker(new GLatLng(Convert.ToDouble(latitude),Convert.ToDouble(longitude))));
Line 78:         GMap1.setCenter(new GLatLng(Convert.ToDouble(latitude), Convert.ToDouble(longitude)), 6);
Line 79:         displayEvent.Text = "                                   ";

The thing that i am unable to understand is that all of this working absolutely fine on my computer. when i test it on the local server it works fine but on my college server it is giving these errors. Can anybody guide me as to what am i doing wrong here. Other parts of the website are reading from other xml files and they dont throw any exceptions. This is the latest addition of xml reading to the website, everything else works fine.
The method which is used for reading the xml file and conversion-
  protected void okButton_Click(object sender, EventArgs e)
    {
        GMap1.reset();
        GMap1.addGMarker(new GMarker(new GLatLng(Convert.ToDouble(latitude),Convert.ToDouble(longitude))));
        GMap1.setCenter(new GLatLng(Convert.ToDouble(latitude), Convert.ToDouble(longitude)), 6);
        displayEvent.Text = "                                   ";
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("Xml/try.xml"));
        XmlNodeList nodeList = doc.SelectNodes("root1/data");
        foreach (XmlNode node in nodeList)
        {
            if (node.SelectSingleNode("event_name").InnerText.Equals(DropDownList1.SelectedValue))
            {
                latitude = "";
                longitude = "";
                displayEvent.Text += "Event name-" + node.SelectSingleNode("event_name").InnerText + "
";
                displayEvent.Text += "Description-" + node.SelectSingleNode("event_desc").InnerText + "
";
                displayEvent.Text += "On-" + node.SelectSingleNode("date").InnerText + "
";
                displayEvent.Text += "Contact Number-" + node.SelectSingleNode("phone").InnerText + "
";
                Calendar1.SelectedDate = Convert.ToDateTime(node.SelectSingleNode("date").InnerText);
                latitude = node.SelectSingleNode("latitude").InnerText;
                longitude = node.SelectSingleNode("longitude").InnerText;
            }
        }
    }

A: The two computers have different regional settings. You are converting string "12/25/2011" to a DateTime value. If in Control Panel/Regional Settings short date format is dd/MM/yyyy, then 25 is interpreted as month number and the string is considered invalid, since we only have twelve. As for longitude/latitude values, my guess would be that decimal separator is set to comma on your college server. Consider using the versions of Convert.ToDateTime/ToDouble with the second IFromatProvider parameter.


Q: Can I replace signed-in user using an older user uid in FireStore Anonymous Login? In my app, users are signed in anonymously. If someone uninstalls the app and re-installs it, the new generated uid is different from the older one. Is there some way I can revert the firebase auth instance to use the older uid instead of the new one?

A: Once a user is signed out from Firebase's anonymous authentication provider, there is no way to reclaim that UID through that provider. Given that a user doesn't have to provide any credentials to sign-in anonymously, allowing them to claim a specific UID would be a big security risk.
The only option would be to build your own provider for Firebase Authentication and give the user the same UID as before there, after you've verified that they are the same user.


Q: Count the number of occurrences between markers in a python list I have a boolean (numpy) array.  And I want to count how many occurrences of 'True' are between the Falses.
Eg for a sample list:
b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]

should produce
ml = [3,3,1]

my initial attempt was to try this snippet:
i = 0
ml = []
for el in b_List:
  if (b_List):
    i += 1
  ml.append(i)
  i = 0

But it keeps appending elements in ml for each F in the b_List.
EDIT
Thank you all for your answers. Sadly I can' accept all the answers as correct. I've accepted Akavall's  answer because he referred to my initial attempt (I know what I did wrong now) and also did a comparison between the Mark's and Ashwinis posts.
Please don't take as a define answer the accepted solution, since both the other suggestions introduce alternative methods what work equally well

A: itertools.groupby provides one easy way to do this:
>>> import itertools
>>> T, F = True, False
>>> b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]
>>> [len(list(group)) for value, group in itertools.groupby(b_List) if value]
[3, 3, 1]

A: Using NumPy:
>>> import numpy as np
>>> a = np.array([ True,  True,  True, False, False, False, False,  True,  True, True, False, False,  True, False], dtype=bool)
>>> np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
array([3, 3, 1])

>>> a = np.array([True, False, False, True, True, False, False, True, False])
>>> np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
array([1, 2, 1])

Can't say that this is the best NumPy solution, but it is still faster than itertools.groupby:
>>> lis = [ True,  True,  True, False, False, False, False,  True,  True, True, False, False,  True, False]*1000
>>> a = np.array(lis)
>>> %timeit [len(list(group)) for value, group in groupby(lis) if value]
100 loops, best of 3: 9.58 ms per loop
>>> %timeit np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
1000 loops, best of 3: 1.4 ms per loop

>>> lis = [ True,  True,  True, False, False, False, False,  True,  True, True, False, False,  True, False]*10000
>>> a = np.array(lis)
>>> %timeit [len(list(group)) for value, group in groupby(lis) if value]
1 loops, best of 3: 95.5 ms per loop
>>> %timeit np.diff(np.insert(np.where(np.diff(a)==1)[0]+1, 0, 0))[::2]
100 loops, best of 3: 14.9 ms per loop

As @justhalf and @Mark Dickinson pointed out in comments the above code will not work in some cases, so you need to append False on both ends first:
In [28]: a
Out[28]:
array([ True,  True,  True, False, False, False, False,  True,  True,
        True, False, False,  True, False], dtype=bool)

In [29]: np.diff(np.where(np.diff(np.hstack([False, a, False])))[0])[::2]
Out[29]: array([3, 3, 1])

A: Your original try has some problems:
i = 0
ml = []
for el in b_List:
    if (b_List): # b_list is a list and will evaluate to True
                 # unless you have an empty list, you want if (el)
        i += 1
    ml.append(i) # even if the above line was correct you still get here
                 # on every iteration, and you don't want that
    i = 0

You probably want something like this:
def count_Trues(b_list):
    i = 0
    ml = []
    prev = False
    for el in b_list:
        if el:
            i += 1
            prev = el
        else:
            if prev is not el:
                ml.append(i)
                i = 0
            prev = el
    if el:
        ml.append(i)
    return m

Result:
>>> T, F = True, False
>>> b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]
>>> count_Trues(b_List)
[3, 3, 1]
>>> b_List.extend([T,T])
>>> count_Trues(b_List)
[3, 3, 1, 2]
>>> b_List.extend([F])
>>> count_Trues(b_List)
[3, 3, 1, 2]

This solution runs surprisingly fast:
In [5]: T, F = True, False

In [6]: b_List = [T,T,T,F,F,F,F,T,T,T,F,F,T,F]

In [7]: new_b_List = b_List * 100

In [8]: import numpy as np

# Ashwini Chaudhary's Solution
In [9]: %timeit np.diff(np.insert(np.where(np.diff(new_b_List)==1)[0]+1, 0, 0))[::2]
1000 loops, best of 3: 299 us per loop

In [11]: %timeit count_Trues(new_b_List)
1000 loops, best of 3: 130 us per loop

In [12]: new_b_List = b_List * 1000

# Ashwini Chaudhary's Solution
In [13]: %timeit np.diff(np.insert(np.where(np.diff(new_b_List)==1)[0]+1, 0, 0))[::2]
100 loops, best of 3: 2.25 ms per loop

In [14]: %timeit count_Trues(new_b_List)
100 loops, best of 3: 1.33 ms per loop


Q: Use process.on('uncaughtException to show a 500 error page I'm developing an express app.
I currently have the following in my server.js
process.on('uncaughtException', function (err) {
    console.log( "UNCAUGHT EXCEPTION " );
    console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message );
});

Which stops the server crashing every time there's an error, however, it just sits there...
is it possible to instead of console.log, to send a 500 error page with the error details?

A: I don't think you can from within the uncaughtException do a response since that could happen even when there is no request occurring.
Express itself provides a way to handle errors within routes, like so:
app.error(function(err, req, res, next){
    //check error information and respond accordingly
});

A: Per ExpressJS Error Handling, add app.use(function(err, req, res, next){ // your logic }); below your other app.use statements.
Example:
app.use(function(err, req, res, next){
  console.log(err.stack);
  // additional logic, like emailing OPS staff w/ stack trace
});


Q: Converting a simple regex line from perl to python I am trying to convert this line from Perl to python:
$line =~ s/$alwayssep/ $& /g;

Any ideas how this might be done in python?

A: In Python, do the following where alwayssep is the expression and line is the passed string:
line = re.sub(alwayssep, r' \g<0> ', line)

A: My Pythonizer converts that to this:
line = re.sub(re.compile(alwayssep),r' \g<0> ',line,count=0)


Q: Password encryption at client side
Possible Duplicate:
About password hashing system on client side

I have to secure the passwords of my web site users.  What I did was use MD5 encryption hashing in server side. But the problem is the passwords remain in plain text until it arrives at the server, which means that the password can be captured using traffic monitoring. So what I want is to use a client side password encryption/hashing mechanism and send the encrypted/hashed password.
 Can anybody tell what is the way to do this?

A: You've tagged this question with the ssl tag, and SSL is the answer. Curious.

A: I would choose this simple solution.
Summarizing it:

*

*Client "I want to login"

*Server generates a random number #S and sends it to the Client

*Client

*

*reads username and password typed by the user

*calculates the hash of the password, getting h(pw) (which is what is stored in the DB)

*generates another random number #C

*concatenates h(pw) + #S + #C and calculates its hash, call it h(all)

*sends to the server username, #C and h(all)

*Server

*

*retrieves h(pw)' for the specified username, from the DB

*now it has all the elements to calculate h(all'), like Client did

*if h(all) = h(all') then h(pw) = h(pw)', almost certainly

No one can repeat the request to log in as the specified user. #S adds a variable component to the hash, each time (it's fundamental). #C adds additional noise in it.

A: You can also simply use http authentication with Digest (Here some infos if you use Apache httpd, Apache Tomcat, and here an explanation of digest).
With Java, for interesting informations, take a look at :

*

*Understanding Login Authentication

*HTTP Digest Authentication Request & Response Examples

*HTTP Authentication Woes

*Basic Authentication For JSP Page (it's not digest, but I think it's an interesting source)

A: There are MD5 libraries available for javascript.  Keep in mind that this solution will not work if you need to support users who do not have javascript available.
The more common solution is to use HTTPS.  With HTTPS, SSL encryption is negotiated between your web server and the client, transparently encrypting all traffic.

A: This sort of protection is normally provided by using HTTPS, so that all communication between the web server and the client is encrypted.
The exact instructions on how to achieve this will depend on your web server.
The Apache documentation has a SSL Configuration HOW-TO guide that may be of some help. (thanks to user G. Qyy for the link)

A: This won't be secure, and it's simple to explain why:
If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.
But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!
Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.
And finally, do you really want to require users to have javascript turned on before they can log into your website?
In any case, SSL is neither an expensive or especially difficult to set up solution any more

A: You need a library that can encrypt your input on client side and transfer it to the server in encrypted form.
You can use following libs:

*

*jCryption. Client-Server asymmetric encryption over Javascript

Update after 3 years (2013):

*

*Stanford Javascript Crypto Library
Update after 4 years (2014):

*

*CryptoJS - Easy to use encryption

*ForgeJS - Pretty much covers it all

*OpenPGP.JS - Put the OpenPGP format everywhere - runs in JS so you can use it in your web apps, mobile apps & etc.

A: I've listed a complete JavaScript for creating an MD5 at the bottom but it's really pointless without a secure connection for several reasons.
If you MD5 the password and store that MD5 in your database then the MD5 is the password. People can tell exactly what's in your database. You've essentially just made the password a longer string but it still isn't secure if that's what you're storing in your database.
If you say, "Well I'll MD5 the MD5" you're missing the point. By looking at the network traffic, or looking in your database, I can spoof your website and send it the MD5. Granted this is a lot harder than just reusing a plain text password but it's still a security hole.
Most of all though you can't salt the hash client side without sending the salt over the 'net unencrypted therefore making the salting pointless. Without a salt or with a known salt I can brute force attack the hash and figure out what the password is.
If you are going to do this kind of thing with unencrypted transmissions you need to use a public key/private key encryption technique. The client encrypts using your public key then you decrypt on your end with your private key then you MD5 the password (using a user unique salt) and store it in your database. Here's a JavaScript GPL public/private key library.
Anyway, here is the JavaScript code to create an MD5 client side (not my code):
/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/

var MD5 = function (string) {

    function RotateLeft(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    }

    function AddUnsigned(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    }

    function F(x,y,z) { return (x & y) | ((~x) & z); }
    function G(x,y,z) { return (x & z) | (y & (~z)); }
    function H(x,y,z) { return (x ^ y ^ z); }
    function I(x,y,z) { return (y ^ (x | (~z))); }

    function FF(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;

    string = Utf8Encode(string);

    x = ConvertToWordArray(string);

    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

    for (k=0;k<x.length;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=AddUnsigned(a,AA);
        b=AddUnsigned(b,BB);
        c=AddUnsigned(c,CC);
        d=AddUnsigned(d,DD);
    }

    var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);

    return temp.toLowerCase();
}

A: For a similar situation I used this PKCS #5: Password-Based Cryptography Standard from RSA laboratories. You can avoid storing password, by substituting it with something that can be generated only from the password (in one sentence). There are some JavaScript implementations.


Q: block inside interpolation with ruby I'm writing a simple program that asks the user for input for an array and spits out the array and its average. Really easy and I had no issues with it.
In the end I came up with: (in this example I'll just use a random array instead of the code for the user input)
array = [1,2,3]
sum = array.inject(:+)
average = sum.to_f/array.length
puts "The numbers you entered in the array were: #{array.join(" ")}"
puts "The average of those numbers are: #{average}"

The output is expected and gives me:
The numbers you entered in the array were: 1 2 3
The averages of those numbers are: 2.0

However, when I was first trying to code this I was trying to be real slick for an easy assignment and I tried doing an interpolation inside of an interpolation. I utilized this code:
For the fourth line in the above code I used:
puts "The numbers you entered in the array were: #{array.each{|num| print "#{num} "}}"

which outputted:
1 2 3 The numbers you entered in the array were: [1, 2, 3]

So I thought there might have been an issue with doing an interpolation inside a block that was inside of an interpolation.
So I then ran the following code to test for just a block inside interpolation.
puts "The numbers you entered in the array were: #{array.each{|num| print num}}"

which outputted:
123The numbers you entered in the array were: [1, 2, 3]

Can anyone explain the me why the proc is executed inside of the interpolation first, printed and then the puts happens. In addition, why did it puts the array in array.inspect form when I never called .inspect on the array.

A: The question you want answered
When you use variable interpolation, that value to interpolate is going to resolve before the original string.
In this case, your Array.each is doing it's thing and printing out "1" then "2" and finally "3". It returns the original Array of [1, 2, 3]
output> 123 # note new line because we used print

Now that your interpolation is resolved, the rest of the puts finishes up and uses the returned value of [1, 2, 3] and prints:
output> The numbers you entered in the array were: [1, 2, 3]\n

To get the final output of:
output> 123The numbers you entered in the array were: [1, 2, 3]\n

The question everyone WANTS to answer :)
http://www.ruby-doc.org/core-2.1.4/Array.html#method-i-each
When calling Array.each with a block, the return is self.
This is "bad" in your case, because you don't want self returned. It will always return the same thing, your original array.
puts "The numbers you entered in the array were: #{array.each{|num| num*2}}"
The numbers you entered in the array were: [1, 2, 3] # WAT?

As a Sergio Tulentsev said, use .map and .join
puts "The numbers you entered in the array were: #{array.map{|num| num*2}.join(' ')}"
The numbers you entered in the array were: 2 4 6


Q: Visual Basic 6 Dynamic Variables I am doing a program using vb6 which is stored datas from mouseclick in term of coordinates. I succeeded doing the first stage which is displaying the clicked coordinates. My problem now is I need to save the coordinate in term of variables so i can call them back to use for another purpose for example to find distance between two points.
if its just two coordinates its easier to find the distance. but when it comes to many coordinates I am stuck. I tried to do an array to stored the data inside loop
 1. InputX(ListNum, 0) = Int(x)
 2. InputY(ListNum, 1) = Int(y)
 3. ListNum=ListNum+1

when I try to call for InputX(2,0) = Text1.Text or Text1.Text=InputX(2,0) none of them working. It seems that the data will be erased after I do a mouseclick
Is there any way which I can set the dynamic variables which stored each my clicked coordinates such as Input1,Input2,Input3 ...InputN
I do this in VB6.

A: The problem you're having is that you're using a two dimensional array there. A two dimensional array looks like a table. That's not what you want though. You want a list of pairs of points. So, create a structure with two integers in it, x and y, and make an array of those structures:
'Right underneath your Class Form1 declaration:

Structure Point
    Dim x As Integer
    Dim y As Integer
End Structure
Dim length As Integer = 10
Dim Points(length) As Point

'When you want to start using your points put this in the method:

Points(0).x = 10
Points(0).y = 10
Points(1).x = 20
Points(1).y = 40

A: Dynamic variables in VB6
First you declare the variable without giving size:
Dim InputX() As String

Then you give for the first time size to your array using ReDim:
ReDim InputX(5)

If you want to preserve whatever data is already in your array you use ReDim Preserve:
ReDim Preserve InputX(10)

I hope this is what you need.

A: it appears that the first method
Text1.Text=InputX(2,0)
is working. I just need to declare x and y As Single


Q: Facebook app in IE - Sometimes getUser() returns 0 although the user already has been connected I using in PHP SDK and sometimes when I'm connecting to my FB app on Internet Explorer the function getUser() returns 0!
Someone knows this weird issue? After some attempts it is getting connected.
It seems that there are cases that facebook doesn't identify the user. Any advice?
$facebook = new Facebook(array(
 'appId'  => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET_KEY,
));

// Get User ID
$fbUserId = number_format($facebook->getUser(), 0, '', '');


Q: codeigniter 404_override I have set the $routes['404_override'] = 'city/switch_site'
now in my city controller
class City extends CI_Controller {
    function __construct() {
        parent::__construct();
    }

    function switch_site( ) {
        $this->load->helper('url'); // load the helper first
        $city = $this->uri->segment(1);
        $segment_cnt = 1;
        $valid_url = '';

        switch( $city ) {

            case 'pune':
                        $segments = $this->uri->segment_array(2);
                        foreach($segments as $value) {
                            if($segment_cnt > 1) {
                                $valid_url .= $this->uri->slash_segment($segment_cnt);
                            }
                            $segment_cnt++;
                        }
                        $this->config->set_item('cityid',1);
                        $this->config->set_item('cityname','pune');
                        echo APPPATH.'controllers/'.$valid_url;
                        include_once(APPPATH.'controllers/'.$valid_url);
                        break;
            case 'mumbai':
                        $segments = $this->uri->segment_array(2);
                        foreach($segments as $value) {
                            if($segment_cnt > 1) {
                                $valid_url .= $this->uri->slash_segment($segment_cnt);
                            }
                            $segment_cnt++;
                        }
                        $this->config->set_item('cityid',2);
                        $this->config->set_item('cityname','mumbai');
                        include_once(APPPATH.'controllers/'.$valid_url);
                        break;
            default:

        }
    }
}

how do i now pass the correct url to codeigniter router

A: I think you are going about this all wrong. Inside your switch instead of including other controllers which will not work use the redirect() to take them where they should go.


Q: Any ideas how to create auto-cutting file when it's size overflow some value? I have some primitive logger that writes information to file, but we have memory limitations with sending files to server, is there any practices to auto-cut file when it's size overflow some size value, for example, 2MB?


Q: How to exclude the transparent parts which are not rectangles when conducting Fourier analyses on PNG images? Some PNG images have transparent backgrounds. We can get maps of transparent degree from PNG images through imread.

It's easy to exclude the transparent parts in Fourier analysis if they are rectangles. However, how to exclude the transparent parts which are not rectangles in Fourier analysis (using fft2)?

In this case, how to use the maps of transparent degree in conducting Fourier analysis?


Q: JQuery: Dialog's current position after moving I got this little problem. I cant get the current position of JQuery after I move it.
Seems like it wont update its position. It just gives the first one.
Another problem I came up with was that the dragStop event wont work either..

A: $('#idOfYourDialog').dialog('widget').position();

use the 'widget' flag to get the ui-dialog (the div that is your dialog) to get it' parameters.
As for the dialog drag-stop - are you binding in the init or through bind? Can you post a code sample?

A: Hmmm... I have this ajax function that calls content from the server. That might be the problem.
I have it like:
            $.ajax({
                url: href,
                success: function(data) {

                    if(handleAjaxErrors(data)==false) {

                        openWindowsCount++;

                        $(data).dialog({


Q: How to implement Location Automation Field I am wondering how to go about implementing Location Automation Field, as suggested in this article: http://uxmovement.com/forms/new-form-techniques-proven-to-save-time-and-money/
Are there libraries or services that can help me figure out City/State given the zipcode? I know Google has the Geocoder/decoder or Google Places search that could potentially be useful but their Terms of Use mandate that you must use their services in conjunction with displaying the results on their map, which is a weird thing to do when the user is filling out billing info...

A: Cheers to you for observing TOS. That's good business.
You could use SmartyStreets. LiveAddress API supports city/state and ZIP code lookups. It now has auto-complete as you type an address, too.
I work at SmartyStreets. In fact, we developed the jQuery plugin which does address validation and auto-complete for you. It even supports freeform address fields.
Related question by yours truly, over on UX stack exchange: https://ux.stackexchange.com/questions/22196/combining-all-the-address-fields-into-one


Q: Swype gesture on scrollable area I'm trying to add swype support to my winjs applicaiton. It works great as long as the content has no scroll area. However as soon as the content overflows the page, the swype gestures don't work anymore.
If I set body { overflow-y: auto; } to hidden it works fine, but when there is a scrollbar, the swype gestures are not triggered anymore. Why?
Here is my sample:

    <meta charset="utf-8" />
    <title>PointerInput</title>
    <link href="gestures.css" rel="stylesheet" />

    <link href="/css/ui-themed.css" rel="stylesheet" />
    <link href="/css/default.css" rel="stylesheet" />

Hello world

Last swype was:

                Lorem ipsum dolor sit amet, usu no illum petentium. Deterruisset definitiones reprehendunt eu mei. Cum falli volutpat at. Diceret splendide sed in. Sint noster deseruisse quo in. Vix nihil iisque dissentias at, harum facilis eu vel.

                Pro eu dico decore consul. Ea posse incorrupte eam, ea affert verear dissentiunt eos. Mentitum intellegam at sit, stet repudiandae vel eu, sea error harum postea ut. Quod habeo tibique est an, vivendo salutatus pri an. Per tamquam tacimates in. Ut odio autem semper sed, cum ne quod aeterno praesent.

                Ut oblique adversarium vis, et commodo discere eloquentiam eum, impetus tritani detracto ius ea. Ne sea expetenda deterruisset. Ea has populo ornatus feugait, assum voluptua interesset cum et. Mel ad aliquip periculis, ad eam vide altera splendide, alienum explicari ut mel. Qui laoreet tibique expetenda eu.

                Mel nullam iuvaret ex, vix te tollit nullam. Illud quaestio reformidans cum et, et alia melius eam. Cum summo malorum ex. An decore nonumy appareat pro, alterum elaboraret concludaturque nec an. Ut vim aperiam oblique delectus. Duo et cibo labitur definiebas, ne affert rationibus sed, fuisset invenire vis ne.

                Ad discere dolores accusata vix, aperiam vivendo cu vel, quo id nominavi dignissim temporibus. Nec summo democritum in, porro nominavi appareat nec cu. Similique ullamcorper vim ad, at epicuri phaedrum pri, est no alii facilis definitionem. Possim numquam et duo, quo an partem urbanitas, eu efficiendi scripserit vim. Ius putant dolores at, ut assum delenit definiebas sed. Tamquam fabellas sed at, ad ius quem affert nominavi, id elit oratio accusamus eam. Quando nostrum platonem vim ex, per ut tation nonumy assueverit.

                Lorem ipsum dolor sit amet, usu no illum petentium. Deterruisset definitiones reprehendunt eu mei. Cum falli volutpat at. Diceret splendide sed in. Sint noster deseruisse quo in. Vix nihil iisque dissentias at, harum facilis eu vel.

                Pro eu dico decore consul. Ea posse incorrupte eam, ea affert verear dissentiunt eos. Mentitum intellegam at sit, stet repudiandae vel eu, sea error harum postea ut. Quod habeo tibique est an, vivendo salutatus pri an. Per tamquam tacimates in. Ut odio autem semper sed, cum ne quod aeterno praesent.

                Ut oblique adversarium vis, et commodo discere eloquentiam eum, impetus tritani detracto ius ea. Ne sea expetenda deterruisset. Ea has populo ornatus feugait, assum voluptua interesset cum et. Mel ad aliquip periculis, ad eam vide altera splendide, alienum explicari ut mel. Qui laoreet tibique expetenda eu.

                Mel nullam iuvaret ex, vix te tollit nullam. Illud quaestio reformidans cum et, et alia melius eam. Cum summo malorum ex. An decore nonumy appareat pro, alterum elaboraret concludaturque nec an. Ut vim aperiam oblique delectus. Duo et cibo labitur definiebas, ne affert rationibus sed, fuisset invenire vis ne.

                Ad discere dolores accusata vix, aperiam vivendo cu vel, quo id nominavi dignissim temporibus. Nec summo democritum in, porro nominavi appareat nec cu. Similique ullamcorper vim ad, at epicuri phaedrum pri, est no alii facilis definitionem. Possim numquam et duo, quo an partem urbanitas, eu efficiendi scripserit vim. Ius putant dolores at, ut assum delenit definiebas sed. Tamquam fabellas sed at, ad ius quem affert nominavi, id elit oratio accusamus eam. Quando nostrum platonem vim ex, per ut tation nonumy assueverit.

A: After some research, I found out that when an area has a scrolling area doesn't propergate touch events, if not specified otherwise. For eaxample, if an area has horzontal scrolling, I have to spezify, that vertical touch events are still allowed. This can be done with the touch-action property (http://msdn.microsoft.com/en-us/library/windows/apps/hh767313.aspx ).
This fixes my problem:


Q: What is the max possible length of a PID of a process? (64 bit) I have been working on AIX and see some of the process ID's running are 8 long....
I am using the PID as a concatenation with another char* value and am trying to work out what that MAX possible length of a PID if you were looking at it from a "char perspective"?
I have looked at the pid_t structure (for example t.html">http://dvbstreamer.sourceforge.net/api/structPID_t.html) and it has the PID as an INT...
On that note I assume a PID is a "signed int"....in that case what is a signed int's max length?
Thanks for the help
Lynton

A: The size in bytes is system dependent and should simply be queried like this:
unsigned int pidLength = sizeof(pid_t);

Edit: If you're worried about the length decimal representation as in printf("%d", myPID);, I suggest querying that, too. For example, the snprintf function returns the number of characters (without null-termination) it would have written if there were enough space. So you can do:
char tmpChar;
int representationLength = snprintf(&tmpChar, 1, "%d", myPID);
if (representationLength == -1) { handle_error(); }
char *finalString = malloc(representationLength + 1);
snprintf(finalString, representationLength + 1, "%d", myPID);

Maybe snprintf(NULL, 0, "%d", myPID) would work to query the length as well, but the Linux snprintf man page says this:

Concerning the return value of snprintf(), SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough.

A: The maximum number of digits in an 32-bit int is 10.
The maximum number of digits in a 64-bit signed int is 19.
The maximum number of digits in a 64-bit unsigned int is 20.
I don't know if AIX uses 32 or 64 bits, signed or unsigned, for its pid_t.
Edit: it's gotta be signed because fork can return -1.

A: Another approach could be to use (int)log10(pid) + 1.  Of course, you might need to include space for a terminating null character, but the above should give you the number of characters needed to represent the value as a string.