text:
Q: Swift Ios 8 MKPolylineRenderer to trace location Hi so i am having trouble with trying to create this MKPolyline for my ios 8 app. This is suppose to trace the users's location and draw a line where ever it goes. I have been looking at tutorials online and they are using ios 7 or 6. Any help would be great. Thank in advance .
    import UIKit
    import MapKit
    import CoreLocation
    class SecondViewController: UIViewController , CLLocationManagerDelegate , MKMapViewDelegate{
    @IBOutlet weak var map: MKMapView!
    let locationManager = CLLocationManager()
    override func viewDidLoad() {
        super.viewDidLoad()
            var currentLocation  = CLLocation()
            self.locationManager.delegate = self
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.locationManager.requestWhenInUseAuthorization()
            self.locationManager.startUpdatingLocation()
        var pinLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude , locationManager.location.coordinate.longitude)
        var objectAnnotation = MKPointAnnotation()
        objectAnnotation.coordinate = pinLocation
        objectAnnotation.title = "Current Location"
        self.map.addAnnotation(objectAnnotation)
}
    func addPolyLineToMap(locations: [CLLocation!])
    {
        var coordinates = locations.map({ (location: CLLocation!) -> CLLocationCoordinate2D in
            return location.coordinate
        })
        var geodesic = MKGeodesicPolyline(coordinates: &coordinates[0], count: 2)
        map.addOverlay(geodesic , level: MKOverlayLevel.AboveRoads )
    }
    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        if overlay is MKPolyline {
            var polylineRenderer = MKPolylineRenderer(overlay: overlay)
            polylineRenderer.strokeColor = UIColor.blueColor()
            polylineRenderer.lineWidth = 4
            return polylineRenderer
        }
        return nil
    }
        func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
        {
            println("Error: " + error.localizedDescription)
        }

   func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        //centering location

        let location = locations.last as CLLocation

        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
    var latDelta:CLLocationDegrees = 0.01

        var longDelta:CLLocationDegrees = 0.01

        var theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
    `var pointLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude , location.coordinate.longitude)
       map.setRegion(region, animated: true)

    addPolyLineToMap(location)

    }

    }


text:
Q: Maximum number of edge-disjoint cycles vs minimum number of edges in a cut Let $G = \langle V,E \rangle$ be a directed graph, let $C(G)$ denote the maximal number of edge-disjoint cycles that can be packed into $G$, and let $D(G)$ denote the minimal size of a set $E' \subset E$ whose removal from $E$ results in an acyclic graph.
Clearly, $D(G) \geq C(G)$, because we must remove at least one edge from each cycle and the cycles counted by $C(G)$ are edge-disjoint. Is it true that $C(G) = D(G)$?
Seeing no reason why this should be true, I tried to construct a counterexample. Since I haven't been able to construct a counterexample, I suspect that the equality holds, but I have no idea how to prove it.

A: Alas! I found a counterexample with six vertices and nine edges.
Let $V = \{1,2,3,4,5,6\}$ and take $E = \{(1,2),(2,4),(4,3),(3,1),(3,5),(5,6),(6,4),(2,5),(6,1)\}$.
To see that this is a counterexample, first note that each vertex has total degree three, so no vertex can participate in more than one edge-disjoint cycle. Since the shortest cycle has length 4, this means that $C(G)=1$.
On the other hand, the three cycles $(1,2,4,3),(3,5,6,4),(1,2,5,6)$ don't have a common edge, and so you need at least to remove at least 2 edges to kill them off. Thus, $D(G) \geq 2$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP date_format() expects parameter 1 to be DateTimeInterface I want to convert the string to date time, but it's not working
<?php
$date = date_create_from_format('d_m_Y_H_i_s', '29_11_2016_5_0_15');
echo date_format($date, 'Y-m-d');

return
Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given ...

what is the solution ??

A: date_create_from_format() returns false when it fails, or a new DateTime instance when it succeeds.
Yours is failing because minutes are two-digits, not single-digits. Using 29_11_2016_5_0_15 as a timestring would yield the following error

A two digit minute could not be found

So simply, you'll need to use 29_11_2016_5_00_15 as the timestring instead, like this
// Try to create the datetime instance
if ($date = date_create_from_format('d_m_Y_H_i_s', '29_11_2016_5_00_15')) {
    echo date_format($date, 'Y-m-d');
} else {
    // It failed! Errors found, let's figure out what!
    echo "<pre>";
    print_r(date_get_last_errors());
    echo "</pre>";
}

The output from the above snippet would be 2016-11-29, live demo: https://3v4l.org/6om9g
Using date_get_last_errors() you'll be able to get the errors given in your DateTime instance.

A: You must use minutes with two chars, in your code is just one where shoud with leading 0.
so just pad it with leading 0.
<?php
$string = '29_11_2016_5_0_15';
$array = explode('_', $string);
$array[4] = str_pad($array[4], 2, 0, STR_PAD_LEFT);
$string = implode('_', $array);
$date = date_create_from_format('d_m_Y_H_i_s', $string);
echo date_format($date, 'Y-m-d');

A: I format date:
echo date("d/m/Y  H:i:s a", strtotime($row['timestamp']));


text:
Q: How to customize bootstrap subthemes in Drupal? I'm testing the Bootstrap theme using Drupal 7.30, its awesome and all is ok, but if I want to create a custom page using tpl.php files like customnamepage.tpl.php, where can I put this kind of files and make them work in order to create my custom pages?

A: A proper answer requires more information on which exact condition customnamepage.tpl.php should be used instead of the usual page.tpl.php.
As an example, if the system path to the page is node/100 and you wanted to have a custom template only for this page, then you could define it in page--node--100.tpl.php. This works, if you have this file just somewhere in the bootstrap theme directory, but do remember to clear the cache before trying.
There are many ways to implement this, the best solution depends on the nature of the pages to which the customization should be applied.


text:
Q: Azure AD B2C access claim/information from incoming login request Currently, using B2C with custom policies having moved from Auth0. It was possible within Auth0 to access the scope claim/property of an incoming login request from the UI and then use that value within Rules to apply some logic. This doesn't seem to be easily do-able in B2C
My user journey allows a user to login using their Azure / Office 365 login via an AD Connector, then enrich the user's claim by calling one of my APIs to get more information about that user account before returning the updated claims to the UI. This all works fine.
What I want to do is expand the enrichment request to include the Audience value from the incoming login request. I have multiple front-end applications that use B2C and want different extra info included in the claims sent back to the UI so filtering on Client ID of the Azure AD APP used by the UI would be good. I would also like to see/access the Scope from the incoming login request as it has some information I would like send to the backend API.
I've tried the following but it doesn't like aud or audience as a claim name and scope is always null.
<TechnicalProfile Id="REST-API">
<DisplayName>Enrich User</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<!-- Set the ServiceUrl with your own REST API endpoint -->
<Item Key="ServiceUrl">https://xxx.mydomain.com/users/b2c</Item>;
<Item Key="SendClaimsIn">Body</Item>
<!-- Set AuthenticationType to Basic or ClientCertificate in production environments -->
<Item Key="AuthenticationType">ApiKeyHeader</Item>
<Item Key="AllowInsecureAuthInProduction">false</Item>
</Metadata>
<CryptographicKeys>
<Key Id="Authorization" StorageReferenceId="B2C_1A_RestApiKey" />
</CryptographicKeys>
<InputClaims>
<!-- Claims sent to your REST API -->
<InputClaim ClaimTypeReferenceId="email" />
<InputClaim ClaimTypeReferenceId="givenName" />
<InputClaim ClaimTypeReferenceId="surname" />
<InputClaim ClaimTypeReferenceId="aud" />
<InputClaim ClaimTypeReferenceId="scope" />
<InputClaim ClaimTypeReferenceId="scp" />
<InputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
</InputClaims>
<OutputClaims>
<!-- Claims parsed from your REST API -->
<OutputClaim ClaimTypeReferenceId="isEnabled" />
<OutputClaim ClaimTypeReferenceId="userId" />
<OutputClaim ClaimTypeReferenceId="accountCode" />
<OutputClaim ClaimTypeReferenceId="role" />
<OutputClaim ClaimTypeReferenceId="env" />
</OutputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>

A: You can get scope with claims resolvers.
Ensure you set the settings.
A more generic way is this.


text:
Q: Reversing words in Arabic I have codes for fixing Arabic problem in my project, but I'm having some problems with the code,
for example, my code does connect Arabic letters together so they would look fixed, but the main problem it doesn't reverse them, so it only show them connected but not reversed so it will not make since in Arabic.
I had another file which has the reverse and connecting letters thing, but it doesn't work with my the file i'm trying to make fixes in it, so I had the other code which connect the words but not reversing them.
Here is the code :
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ArabicConv
{
private static final char ALF_UPPER_MDD = 0x0622;
private static final char ALF_UPPER_HAMAZA = 0x0623;
private static final char ALF_LOWER_HAMAZA = 0x0625;
private static final char ALF = 0x0627;
private static final char LAM = 0x0644;

private static final char ARABIC_GLPHIES[][] = new char[][]
        {
                {'\u0622', '\uFE81', '\uFE81', '\uFE82', '\uFE82', 2},
                {'\u0623', '\uFE82', '\uFE83', '\uFE84', '\uFE84', 2},
                {'\u0624', '\uFE85', '\uFE85', '\uFE86', '\uFE86', 2},
                {'\u0625', '\uFE87', '\uFE87', '\uFE88', '\uFE88', 2},
                {'\u0626', '\uFE89', '\uFE8B', '\uFE8C', '\uFE8A', 4},
                {'\u0627', '\u0627', '\u0627', '\uFE8E', '\uFE8E', 2},
                {'\u0628', '\uFE8F', '\uFE91', '\uFE92', '\uFE90', 4},
                {'\u0629', '\uFE93', '\uFE93', '\uFE94', '\uFE94', 2},
                {'\u062A', '\uFE95', '\uFE97', '\uFE98', '\uFE96', 4},
                {'\u062B', '\uFE99', '\uFE9B', '\uFE9C', '\uFE9A', 4},
                {'\u062C', '\uFE9D', '\uFE9F', '\uFEA0', '\uFE9E', 4},
                {'\u062D', '\uFEA1', '\uFEA3', '\uFEA4', '\uFEA2', 4},
                {'\u062E', '\uFEA5', '\uFEA7', '\uFEA8', '\uFEA6', 4},
                {'\u062F', '\uFEA9', '\uFEA9', '\uFEAA', '\uFEAA', 2},
                {'\u0630', '\uFEAB', '\uFEAB', '\uFEAC', '\uFEAC', 2},
                {'\u0631', '\uFEAD', '\uFEAD', '\uFEAE', '\uFEAE', 2},
                {'\u0632', '\uFEAF', '\uFEAF', '\uFEB0', '\uFEB0', 2},
                {'\u0633', '\uFEB1', '\uFEB3', '\uFEB4', '\uFEB2', 4},
                {'\u0634', '\uFEB5', '\uFEB7', '\uFEB8', '\uFEB6', 4},
                {'\u0635', '\uFEB9', '\uFEBB', '\uFEBC', '\uFEBA', 4},
                {'\u0636', '\uFEBD', '\uFEBF', '\uFEC0', '\uFEBE', 4},
                {'\u0637', '\uFEC1', '\uFEC3', '\uFEC2', '\uFEC4', 4},
                {'\u0638', '\uFEC5', '\uFEC7', '\uFEC6', '\uFEC6', 4},
                {'\u0639', '\uFEC9', '\uFECB', '\uFECC', '\uFECA', 4},
                {'\u063A', '\uFECD', '\uFECF', '\uFED0', '\uFECE', 4},
                {'\u0641', '\uFED1', '\uFED3', '\uFED4', '\uFED2', 4},
                {'\u0642', '\uFED5', '\uFED7', '\uFED8', '\uFED6', 4},
                {'\u0643', '\uFED9', '\uFEDB', '\uFEDC', '\uFEDA', 4},
                {'\u0644', '\uFEDD', '\uFEDF', '\uFEE0', '\uFEDE', 4},
                {'\u0645', '\uFEE1', '\uFEE3', '\uFEE4', '\uFEE2', 4},
                {'\u0646', '\uFEE5', '\uFEE7', '\uFEE8', '\uFEE6', 4},
                {'\u0647', '\uFEE9', '\uFEEB', '\uFEEC', '\uFEEA', 4},
                {'\u0648', '\uFEED', '\uFEED', '\uFEEE', '\uFEEE', 2},
                {'\u0649', '\uFEEF', '\uFEEF', '\uFEF0', '\uFEF0', 2},
                {'\u0671', '\u0671', '\u0671', '\uFB51', '\uFB51', 2},
                {'\u064A', '\uFEF1', '\uFEF3', '\uFEF4', '\uFEF2', 4},
                {'\u066E', '\uFBE4', '\uFBE8', '\uFBE9', '\uFBE5', 4},
                {'\u0671', '\u0671', '\u0671', '\uFB51', '\uFB51', 2},
                {'\u06AA', '\uFB8E', '\uFB90', '\uFB91', '\uFB8F', 4},
                {'\u06C1', '\uFBA6', '\uFBA8', '\uFBA9', '\uFBA7', 4},
                {'\u06E4', '\u06E4', '\u06E4', '\u06E4', '\uFEEE', 2},
                {'\u0686', '\uFB7A', '\uFB7C', '\uFB7D', '\uFB7B', 4},
                {'\u067E', '\uFB56', '\uFB58', '\uFB59', '\uFB57', 4},
                {'\u0698', '\uFB8A', '\uFB8A', '\uFB8B', '\uFB8B', 2},
                {'\u06AF', '\uFB92', '\uFB94', '\uFB95', '\uFB93', 4},
                {'\u06CC', '\uFEEF', '\uFEF3', '\uFEF4', '\uFEF0', 4},
                {'\u06A9', '\uFB8E', '\uFB90', '\uFB91', '\uFB8F', 4},
        };
private static final Map<Character, char[]> ARABIC_GLPHIES_MAP;

private static final char HARAKATE[] = {
        '\u064B', '\u064C', '\u064D', '\u064E', '\u064F', '\u0650', '\u0651',
        '\u0652', '\u0653', '\u0654', '\u0655', '\u0656'};

private static final char LAM_ALEF_GLPHIES[][] =
        {
                {15270, 65270, 65269},
                {15271, 65272, 65271},
                {1573, 65274, 65273},
                {1575, 65276, 65275}
        };

static
{
    Map<Character, char[]> arabivGlphiesMap = new HashMap<Character, char[]>();
    for(char[] forms : ARABIC_GLPHIES)
    {
        arabivGlphiesMap.put(forms[0], forms);
    }
    ARABIC_GLPHIES_MAP = Collections.<Character, char[]>unmodifiableMap(arabivGlphiesMap);
}

private static char getLamAlef(char AlefCand, char LamCand, boolean isEnd)
{
    int shiftRate = 1;
    if(isEnd)
    {
        shiftRate++;
    }

    if(LAM == LamCand)
    {
        switch(AlefCand)
        {
        case ALF_UPPER_MDD:
            return LAM_ALEF_GLPHIES[0][shiftRate];
        case ALF_UPPER_HAMAZA:
            return LAM_ALEF_GLPHIES[1][shiftRate];
        case ALF_LOWER_HAMAZA:
            return LAM_ALEF_GLPHIES[2][shiftRate];
        case ALF:
            return LAM_ALEF_GLPHIES[3][shiftRate];
        }
    }
    return 0;
}

private static final char getReshapedGlphy(char ch, int off)
{
    char[] forms = ARABIC_GLPHIES_MAP.get(ch);
    if(forms != null)
    {
        if(ch != forms[0])
        {
            throw new RuntimeException();
        }
        return forms[off];
    }
    return ch;
}

private static final char getGlphyType(char ch)
{
    char[] forms = ARABIC_GLPHIES_MAP.get(ch);
    if(forms != null)
    {
        if(ch != forms[0])
        {
            throw new RuntimeException();
        }
        return forms[5];
    }
    return 2;
}

private static String shapeArabic0(String src)
{
    if(src.isEmpty())
        return "";

    switch(src.length())
    {
        case 0:
            return "";
        case 1:
            return new String(new char[] { getReshapedGlphy(src.charAt(0), 0) });
        case 2:
        {
            final char lam = src.charAt(0);
            final char alif = src.charAt(1);
            final char lam_alif = getLamAlef(alif, lam, true);

            if(lam_alif > 0)
                return new String(new char[]{ lam_alif });

            break;
        }
    }

    char[] reshapedLetters = new char[src.length()];

    char currLetter = src.charAt(0);
    reshapedLetters[0] = getReshapedGlphy(currLetter, 2);

    for(int i = 1; i < src.length() - 1; i++)
    {
        final char lam_alif = getLamAlef(src.charAt(i), currLetter, true);
        if(lam_alif > 0)
        {
            if((i - 2 < 0) || ((i - 2 >= 0) && getGlphyType(src.charAt(i - 2)) == 2))
            {
                reshapedLetters[i - 1] = 0;
                reshapedLetters[i] = lam_alif;
            }
            else
            {
                reshapedLetters[i - 1] = 0;
                reshapedLetters[i] = getLamAlef(src.charAt(i), currLetter, false);
            }
        }
        else
        {
            if(getGlphyType(src.charAt(i - 1)) == 2)
                reshapedLetters[i] = getReshapedGlphy(src.charAt(i), 2);
            else
                reshapedLetters[i] = getReshapedGlphy(src.charAt(i), 3);
        }
        currLetter = src.charAt(i);
    }

    final int len = src.length();
    final char lam_alif = getLamAlef(src.charAt(len - 1), src.charAt(len - 2), true);
    if(lam_alif > 0)
    {
        if(len > 3 && getGlphyType(src.charAt(len - 3)) == 2)
        {
            reshapedLetters[len - 2] = 0;
            reshapedLetters[len - 1] = lam_alif;
        }
        else
        {
            reshapedLetters[len - 2] = 0;
            reshapedLetters[len - 1] = getLamAlef(src.charAt(len - 1), src.charAt(len - 2), false);
        }
    }
    else
    {
        if(getGlphyType(src.charAt(len - 2)) == 2)
            reshapedLetters[len - 1] = getReshapedGlphy(src.charAt(len - 1), 1);
        else
            reshapedLetters[len - 1] = getReshapedGlphy(src.charAt(len - 1), 4);
    }

    StringBuilder sb = new StringBuilder();
    for(char ch : reshapedLetters)
    {
        if(ch != 0)
            sb.append(ch);
    }
    return sb.toString();
}

public static boolean isArChar(char ch)
{
    char[] form = ARABIC_GLPHIES_MAP.get(ch);
    return form != null;
}

public static String shapeArabic(String src)
{
    StringBuilder sb = new StringBuilder();
    for(int i = 0, len = src.length(); i < len; i++)
    {
        if(isArChar(src.charAt(i)))
        {
            final int arStart = i;
            for(; i < len && isArChar(src.charAt(i)); i++);
            sb.append(shapeArabic0(src.substring(arStart, i)));
            if(i < len)
            {
                sb.append(src.charAt(i));
            }
        }
        else
        {
            sb.append(src.charAt(i));
        }
    }
    return sb.toString();
}

public static final void main(String ... args)
{

    System.out.println(shapeArabic("adfaорфывلاشستيالاشسريلشر شلصاير لريص"));
    System.out.println(shapeArabic("awdhgb شلشس لسشhgasvрпфымв لرشس2323يلسشار"));
    System.out.println(shapeArabic("dashdاتلاي تاسي تاي اتشسر صعغ غلي    ضغعليصض dsaugd"));
}

}

I want to make it to reverse the words then connect them, what should I do ? if the other code which reverse the letters needed, please ask, it might have something to give you an idea about what I need.
thank you in advance guys.

A: change this:
for(int i = 0, len = src.length(); i < len; i++)

to
for(int i = src.length(), len = 0; i > len; i--)

A: StringBuilder has a reverse() method, so instead of sb.toString() you can use sb.reverse().toString().
But in general, you shouldn't need to do so much processing to get Arabic strings to render right. Simply reversing a left-to-right input should be all you need:
public static final void main(String... args) {

    String[] arCharsList = new String[]{"م", "ا", "ل", "س"};

    System.out.println(String.join("", arCharsList)); // مالس

    Collections.reverse(Arrays.asList(arCharsList));
    System.out.println(String.join("", arCharsList)); // سلام

    Collections.reverse(Arrays.asList(arCharsList)); // change back to original

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < arCharsList.length; ++i) {
        sb.append(arCharsList[i]);
    }
    System.out.println(sb.toString()); // مالس
    System.out.println(sb.reverse().toString()); // سلام
}

UPDATE
Per the comment below, apparently the issue is that the full words are in the wrong order, not the individual characters. In that case, once you have your string, you can reverse it like this:
    String back = "سعيد وقت قضاء لكم نتمنى بالخادم بكم أهلا";
    String[] backList = back.split(" ");
    Collections.reverse(Arrays.asList(backList));
    String fixed = String.join(" ", backList);
    System.out.println(fixed); // أهلا بكم بالخادم نتمنى لكم قضاء وقت سعيد


text:
Q: How to move N lines from one file to another I want to download multiple files, so I decided to create 4 text files that are handled with a script.
toDownload.txt | this file will hold a list of links to download.
inQueue.txt    | the files currently downloading will move here and if failed we can continue later using wget -c flag.
downloaded.txt | this file will hold file links that have finished downloading.
failed.txt     | this file will hold links that failed to start downloading for example if the URL returns 404.

how can I move the first x number of links from a file and move it to another file?

A: #!/bin/sh

lines=3
head -n $lines file1.txt >> file2.txt
sed -i -e "1,$lines d" file1.txt

This will append the first three lines from file1.txt to file2.txt
and then delete the lines 1…3 from file1.txt effectively
moving the first 3 lines from file1.txt to the end of file2.txt.


text:
Q: Trying to make separate divs line up at the bottom of the page using CSS For the site I'm currently making, on the right side is a sidebar with some content that extends to the bottom of the page. To the left is the main content of the site, separated into several bootstrap rows and columns, which also go to the bottom of the page.
However, these two sides of the page do not end at the same spot, making it look like this:
I scratched out the name in the picture.
I had a fix in mind, but I wanted to ask here before I can implement it tomorrow morning if it'd work. If I set a specific height for the sidebar on the right, and then set specific heights for the containers on the left that add up to that same height on for the content on the right, would that fix this issue in all browsers? I'm hiding the right side content on mobile and tablets, so it's not an issue there. Any help would be appreciated.
Relevant code below, this is for the sidebar on the right, on the left are several rows and columns using bootstrap.
I've tried several things to fix this, like playing with the spacing, but it's clear that will never work on every browser. Please let me know if you need any more information.

Testimonials & Reviews

"Sed iaculis et enim at aliquet. Fusce eget lorem vel odio aliquam vulputate ut consectetur nisi. Morbi sagittis quis dolor sagittis posuere. Duis porta tellus luctus diam tristique, in sodales odio pretium. Fusce feugiat, neque fringilla auctor mattis,
    lectus mi condimentum diam, et posuere felis ante ut risus. Quisque eget nisi sed ipsum varius interdum. Cras eget diam volutpat, euismod massa id, lobortis erat. Phasellus venenatis pretium urna vitae tempor. Aliquam pharetra orci id blandit posuere."

-Name

"Sed iaculis et enim at aliquet. Fusce eget lorem vel odio aliquam vulputate ut consectetur nisi. Morbi sagittis quis dolor sagittis posuere. Duis porta tellus luctus diam tristique, in sodales odio pretium. Fusce feugiat, neque fringilla auctor mattis,
    lectus mi condimentum diam, et posuere felis ante ut risus. Quisque eget nisi sed ipsum varius interdum. Cras eget diam volutpat, euismod massa id, lobortis erat. Phasellus venenatis pretium urna vitae tempor. Aliquam pharetra orci id blandit posuere."

-Name

"Sed iaculis et enim at aliquet. Fusce eget lorem vel odio aliquam vulputate ut consectetur nisi. Morbi sagittis quis dolor sagittis posuere. Duis porta tellus luctus diam tristique, in sodales odio pretium. Fusce feugiat, neque fringilla auctor mattis,
    lectus mi condimentum diam, et posuere felis ante ut risus. Quisque eget nisi sed ipsum varius interdum. Cras eget diam volutpat, euismod massa id, lobortis erat. Phasellus venenatis pretium urna vitae tempor. Aliquam pharetra orci id blandit posuere."

-Name

"Sed iaculis et enim at aliquet. Fusce eget lorem vel odio aliquam vulputate ut consectetur nisi. Morbi sagittis quis dolor sagittis posuere. Duis porta tellus luctus diam tristique, in sodales odio pretium. Fusce feugiat, neque fringilla auctor mattis,
    lectus mi condimentum diam, et posuere felis ante ut risus. Quisque eget nisi sed ipsum varius interdum. Cras eget diam volutpat, euismod massa id, lobortis erat. Phasellus venenatis pretium urna vitae tempor. Aliquam pharetra orci id blandit posuere."

Name

"Sed iaculis et enim at aliquet. Fusce eget lorem vel odio aliquam vulputate ut consectetur nisi. Morbi sagittis quis dolor sagittis posuere. Duis porta tellus luctus diam tristique, in sodales odio pretium. Fusce feugiat, neque fringilla auctor mattis,
    lectus mi condimentum diam, et posuere felis ante ut risus. Quisque eget nisi sed ipsum varius interdum. Cras eget diam volutpat, euismod massa id, lobortis erat. Phasellus venenatis pretium urna vitae tempor. Aliquam pharetra orci id blandit posuere."

Name

"Sed iaculis et enim at aliquet. Fusce eget lorem vel odio aliquam vulputate ut consectetur nisi. Morbi sagittis quis dolor sagittis posuere. Duis porta tellus luctus diam tristique, in sodales odio pretium. Fusce feugiat, neque fringilla auctor mattis,
      lectus mi condimentum diam, et posuere felis ante ut risus. Quisque eget nisi sed ipsum varius interdum. Cras eget diam volutpat, euismod massa id, lobortis erat. Phasellus venenatis pretium urna vitae tempor. Aliquam pharetra orci id blandit posuere."

-Name

A: Did you perhaps want to make something like this? (two div have same height, and will follow the height of the higher div, run the code snippet below)
then you can use flex. that if you don't need to support older IE version. if you want to support older IE, then you need to do it via javascript.

.wrapper {
  display: flex;
  width: 100vw;
  font-size: 0;
}

.right-content {
  width: 20%;
  display: inline-block;
  font-size: 16px;
  background-color: green;
}

.left-content {
  width: 80%;
  display: inline-block;
  font-size: 16px;
  vertical-align: top;
  background-color: red;
}

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

 Name

A:
*Apply a display:flex to the .container

*Remove the float property on .test-container

* Remove the margin top on .test-container

* Take out the red experimental border  on .content-container
fiddle is here


text:
Q: Is there a possibility to do reviews on a mobile phone? I know the API and the smartphone App of Stack Exchange doesn't support everything that is possible on the webpage.
And I also know I can do reviews on my mobile using the webbrowser and the desktop version of the page.
Is there another way like a specific app or something for doing reviews on the go?


text:
Q: How to get date in following format "2017-06-06T07:00:00.000Z" in Python? I would like to get current date/time in the following format "2017-06-06T07:00:00.000Z" in Python. I have JSON that contains this date formatting and I would like to imitate this. Any idea if this a standard (ISO) format or how I can get this format? I couldn't find this format on StackOverflow.

A: Yes, it is ISO format (see ISO 8601) and you can produce it in Python in several ways, in particular using time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()).


text:
Q: How can i show my plan message in asp.net? I read this link for alert message:
http://tympanus.net/Development/ModalWindowEffects/

I want use that message box for my asp.net project,how can i use that link in my asp.net project?for example i have one asp.net button on my project and i want when user press that button ,show the up link message to user.thanks.

A: I think you need to call javascript from code behind, assuming that you are using c# as the code behind, just write this code where you want to show the message:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "thanks msg", "alert('Thanks');", true);

you can replace alert('Thanks'); with your jquery or javascript code.


text:
Q: Prove or find a counterexample
Suppose $f(x)$ is bounded and differentiable on $[0,\infty)$. Consider the statement:
If $\lim_{x\to \infty}f(x)=0 $, then $\lim_{x\to \infty}f'(x)=0 $.
Prove it if it's right or show a counterexample.

I think it's not true and trying to find a counterexample by using functions containing $\cos(\frac{1}{x})$ or $e^{-x}$ or other things. The final goal is to find something make it's derivative' limit at infite doesn't exist. Since if it exists, it must equals zero or $f(x)$ will not be bounded.

A: You can take $f(x)=e^{-x}\sin(e^x)$, for instance. Note that $f'(x)=-e^{-x}\sin(e^x)+\cos(e^x)$ and that therefore the limite $\lim_{x\to+\infty}f'(x)$ does not exist.


text:
Q: How to reduce overly-redundant for loops I am currently developing a Chess game and ran into a problem with code redundancy in my Bishop class. I am trying to create a function that will get all possible moves of a bishop. To do that, I would create a for loop that evaluates all diagonals of the bishop, and break the loop when it hits the end of the board or a piece. The problem with this code is it is redundant, since to evaluate all diagonals a Bishop can go, I must have 4 for loops. A simplified version of the code looks like this
var list = [1,0,0,0,1,0,0,1]; // 1d list
var index = 5; // position of "bishop"
for (let i = index, j = list.length; i < j; i++) {
    if (list[i] === 1) { // if true, return instance of 1 and break loop
        console.log("first instance of 1 going right, found at " + i);
        break;
    }
}
for (let i = index; i >= 0; i--) {
    if (list[i] === 1) { // if true, return instance of 1 and break loop
        console.log("first instance of 1 going left, found at " + i);
        break;
    }
}

Though this code works, when dealing with a bishop that can move in 4 directions, this is pretty repetitive and can lead to issues in the future. Is there a way that I am able to reduce the 4 for loops (or 2 in the example above) down to 1 without the cost of efficiency? Because the answer requires the correct concept, there isn't much to show my attempts at this problem.

A: I would recommend using a function to replace the loops.
This makes it so the same loop can be re-used without copy-pasting it.
Here is a code sample:
// Board width and height.
const boardSize = 8;
// The chess board (2d array, x index first).
const board = [[0,0,1, ...],[1,0,1, ...], ...];

// Get the maximum distance a piece can travel in a direction.
function findTravelDistance(x,y,dirX,dirY) {
    for (let n = 0;; n++) {
        // Calculate the position from moving n spaces.
        var newX = x + n*dirX,
            newY = y + n*dirY;

        // Return if the piece is off the board.
        if (newX < 0 || newX >= boardSize || newY < 0 || newY >= boardSize)
            return n - 1;

        // Return if the piece hits a one.
        if (board[newX][newY] === 1)
            return n;
    }
}

// Array containing all directions a bishop can move.
const bishopDirections = [[1,1], [1,-1], [-1,1], [-1,-1]];

// Take x and y as starting position.
// Return an array of distances corresponding to directions in bishopDirections
function findBishopTravelDistances(x,y) {
    var distances = [0,0,0,0];
    // Calculate distances for all directions.
    for (let i = 0; i < bishopDirections.length; i++)
        distances[i] = findTravelDistance()
    return distances;
}

A: How about a left and right iterator to combine both loops and look both directions at the same time.
var list = [1,0,0,0,1,0,0,1];
var index = 5;
var left = index - 1;
var right = index + 1;
while(left >= 0 || right < list.length)
{
  if(list[left] === 1) {
    console.log("first instance of 1 going left, found at " + left);
    break;
  }

  if(list[right] === 1) {
    console.log("first instance of 1 going right, found at " + right);
    break;
  }

  if(left >= 0)
    left--;

  if(right < list.length)
    right++;
}


text:
Q: Ethernet problems on ASIX AX88772B USB 2.0 Ethernet adapter I have some problems with ethernet on Linux chrubuntu 3.13.0-29-generic.
Network manager shows  the network is connected and the device is recognized, but there is no internet.
Interestingly it sometimes opens google.com and I am able to input queries, but they are very slow and nothing else works.
Here is some info:
user@chrubuntu:~$ sudo ifconfig -a
[sudo] password for user:
eth0      Link encap:Ethernet  HWaddr 72:b1:b1:c1:d8:46
          inet addr:129.118.162.17  Bcast:129.118.163.255  Mask:255.255.254.0
          inet6 addr: fe80::70b1:b1ff:fec1:d846/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:18700 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2122 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2138423 (2.1 MB)  TX bytes:404200 (404.2 KB)

    user@chrubuntu:~$ lshw -C network
    WARNING: you should run this program as super-user.
      *-network
           description: Wireless interface
           product: AR9462 Wireless Network Adapter
           vendor: Qualcomm Atheros
           physical id: 0
           bus info: pci@0000:01:00.0
           logical name: wlan0
           version: 01
           serial: 14:2d:27:b3:2a:6f
           width: 64 bits
           clock: 33MHz
           capabilities: bus_master cap_list rom ethernet physical wireless
           configuration: broadcast=yes driver=ath9k driverversion=3.13.0-29-generic firmware=N/A latency=0 link=no multicast=yes wireless=IEEE 802.11abgn
           resources: irq:16 memory:e0400000-e047ffff memory:e0480000-e048ffff
      *-network
           description: Ethernet interface
           physical id: 1
           logical name: eth0
           serial: 72:b1:b1:c1:d8:46
           size: 100Mbit/s
           capacity: 100Mbit/s
           capabilities: ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation
           configuration: autonegotiation=on broadcast=yes driver=asix driverversion=22-Aug-2005 duplex=full firmware=ASIX AX88772B USB 2.0 Ethernet ip=129.118.162.17 link=yes multicast=yes port=MII speed=100Mbit/s
    WARNING: output may be incomplete or inaccurate, you should run this program as super-user.

UPD (netstat-rn and tracepath -n 8 8 8 8):
 user@chrubuntu:~$ netstat -rn
 Kernel IP routing table
 Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
 0.0.0.0         129.118.163.254 0.0.0.0         UG        0 0          0 eth0
 129.118.162.0   0.0.0.0         255.255.254.0   U         0 0          0 eth0

 user@chrubuntu:~$ tracepath -n 8.8.8.8
 1?: [LOCALHOST]                                         pmtu 1500
 1:  129.118.163.254                                       1.894ms
 1:  129.118.163.254                                       1.899ms
 2:  129.118.251.29                                        1.994ms
 3:  129.118.4.246                                         2.197ms
 4:  129.118.4.233                                         2.707ms asymm  5
 5:  129.118.4.238                                         2.932ms
 6:  12.249.227.125                                       10.755ms asymm  7
 7:  no reply
 8:  no reply
 9:  no reply
10:  no reply
11:  no reply
12:  no reply
13:  no reply
14:  no reply
15:  no reply
16:  no reply
17:  no reply
18:  no reply
19:  no reply
20:  no reply
21:  no reply
22:  no reply
23:  no reply
24:  no reply
25:  no reply
26:  no reply
27:  no reply

I tried to update the driver (downloaded the latest one from ASIX website) , but it seems I updated it to an older version (22-Aug-2005) and it did not help.
When I Ping 8.8.8.8 all the packages are lost.
Exactly the same internet cord works on another computer(desktop) running standard Ubuntu 14.04.It also works on the same chromebook when I use Chrome OS.
Any thoughts?

A: Looks like the problem is with your ISP. The packets are leaving your computer/network and then get dropped half way through. Call up your provider and tell them to fix their stuff


text:
Q: Laravel eloquent firstOrNew method doesn't update or insert I have a problem with firstOrNew() method of the Laravel eloquent class. the problem is that when I give the method some attributes and values and call save() on the model, it doesn't get saved (inserted or updated).
PHP :
<?

$flightModel = Flight::firstOrNew([
    'arrival' => $flightData['arrival'],
    'plane' => $flightData['plane']
]);

$flightModel->departure = $flightData['departure'];

$flightModel->save();//this doesn't save any data

But when I try this with a new model it gets saved :
<?

$flightModel = new Flight();
$flightModel->arrival = $flightData['arrival'];
$flightModel->plane = $flightData['plane'];
$flightModel->departure = $flightData['departure'];

$flightModel->save();

Thanks for helping.


text:
Q: ValueError: Input strings must be a multiple of 8 in length when input utf-8 in python 3.6 def get_encrypt_param(params):
    _salt = b"\xA9\x9B\xC8\x32\x56\x35\xE3\x03"
    _iterations = 2
    data = []
    for i in params:
        data.append("{}={}".format(i, params[i]))
    str_param = "&".join(data)
    print(str_param)
    padding = 8 - len(str_param) % 8
    str_param += chr(padding) * padding
    print(str_param)
    hasher = MD5.new()
    hasher.update(apikey.encode())
    hasher.update(_salt)
    result = hasher.digest()
    for i in range(1, _iterations):
        hasher = MD5.new()
        hasher.update(result)
        result = hasher.digest()
    encoder = DES.new(result[:8], DES.MODE_CBC, result[8:16])

    encrypted = encoder.encrypt(str_param)
    encryptParam = base64.b64encode(encrypted)
    return res

When I input chinese character,
params = {
    "name": u"张三",
    "idCard": "123456199001011233",
    "mobile": "13800138000"
}
print(get_encrypt_param(params))

ValueError: Input strings must be a multiple of 8 in length.
But it' ok when I input english character.
Please help me.
I try to :
for i in params:
    data.append("{}={}".format(i, params[i].encode("utf-8")))

But the str_param is :
mobile=b'13800138000'&name=b'\xe5\xbc\xa0\xe4\xb8\x89'&cardno=b'123456199001011233'

it's bytes and others can't recognise the decrypt params.

A: use another package:pyDes
Code:
import pyDes

def get_encrypt_param(params):
    """对参数进行加密封装"""
    _salt = b"\xA9\x9B\xC8\x32\x56\x35\xE3\x03"
    _iterations = 2
    data = []
    for i in params:
        data.append("{}={}".format(i, params[i]))
    str_param = "&".join(data)

    hasher = MD5.new()
    hasher.update(apikey.encode())
    hasher.update(_salt)
    result = hasher.digest()
    for i in range(1, _iterations):
        hasher = MD5.new()
        hasher.update(result)
        result = hasher.digest()

    despy = pyDes.des(result[:8], pyDes.CBC, padmode=pyDes.PAD_PKCS5, IV=result[8:16])
    encrypt_data = despy.encrypt(str_param.encode())
    return base64.b64encode(encrypt_data)

so you can encrypt chinese character without encoding("utf-8).


text:
Q: Java array turning to zeros after exiting a for loop I'm using an FFT class I found online to compute the FFT of an image. Here's the code to compute the FFT.
w (width) and h (height) are the same value in this instance.
FFT2 fft = new FFT2(w);
double[] realRow = new double[w];
double[] imagRow = new double[w];
double[][] realVals1 = new double[w][h];
double[][] imagVals1 = new double[w][h];

for (int y = 0; y < h; y++)
    {
        for (int x = 0; x < w; x++)
        {
            pixel = bmporiginal.getPixel(x, y);
            R = (int) (Color.red(pixel));
            G = (int) (Color.green(pixel) );
            B = (int) (Color.blue(pixel));

            I = ((R+G+B)/3);
            I *= Math.pow(-1, (x+y) % 2.0 );
            realRow[x] = I;
            imagRow[x] = 0.0;
        }
            fft.fft(realRow, imagRow);
            realVals1[y] = realRow;
            imagVals1[y] = imagRow;
    }

The values I need are being stored in realVals and ImagVals. I can print these values within the for loop and get good values. After leaving the for loops I print them again, and get nothing!!! What could be the problem? I appreciate your help!

A: You're reusing the same row arrays for every iteration of the loop.
So at the end of the two loops, your realVals1 and imagVals1 will each have h references to the same array. You need to create a new array on each iteration of the outer loop:
for (int y = 0; y < h; y++)
{
    double[] realRow = new double[w];
    double[] imagRow = new double[w];

    for (int x = 0; x < w; x++)
    {
        ...
    }
    fft.fft(realRow, imagRow);
    realVals1[y] = realRow;
    imagVals1[y] = imagRow;
}

Additionally, I believe your declarations for realVals1 and imagVals1 are a) inefficient and b) the wrong way round. I suspect you want:
double[][] realVals1 = new double[h][];
double[][] imagVals1 = new double[h][];

You're going to be replacing the elements anyway, so there's no point in populating a bunch of empty rows...

A: You're reusing the same array realRow and imagRow each time through the inner loop.  Since Java works with references, when you assign realVals1[y]=realRow, you assign a reference.  Since you always use the same array, you assign all the rows to the same array reference.  Which is not what you want.  You need to recreate realRow and imagRow to a new double[] at the top of the outer for loop.


text:
Q: Вывести ноль вместо пустой строки в запросе Есть запрос, который выводит номер отдела магазина и сумму товаров, проданных в нем. Проблема в том, что если сумма равна 0, то этот отдел не выводится вообще, то есть нет строки №отдела - '0'. Попробовал так -
 CASE
 WHEN SUM(total) IS NULL
 THEN '0'
 END SUM(total)

не получилось.
Можете подсказать еще варианты?
UPDATE (перенесено из комментария):
USE laba1

SELECT DEPARTMENT.department_id [отдел], SUM(SALES_ORDER.total) [сумма]
FROM SALES_ORDER
INNER JOIN CUSTOMER ON SALES_ORDER.customer_id = CUSTOMER.customer_id
INNER JOIN EMPLOYEE ON CUSTOMER.salesperson_id = EMPLOYEE.employee_id
INNER JOIN DEPARTMENT ON EMPLOYEE.department_id = DEPARTMENT.department_id
WHERE order_date BETWEEN '19881231' AND '19900101'
  AND DEPARTMENT.department_id = 14
GROUP BY DEPARTMENT.department_id


text:
Q: extract some data from all sheet et copy in another sheet sheet client capture erreur code
i need to extract the text in the  cells names "_mailclient" when i can find ref previously enter.
the code need to :
-find in all sheet the reference, put in the messge box
-if he find the the word, he extrait the cells "_mailclient" of the sheet with the ref and put him in another sheet and pass to the next sheet
-if not he pass to the next sheet.
-repet the code for evely sheet.
Thanks for your time
Sub recherche_mail()

Dim feuille As Worksheet
Dim valeurtrouve As Range
Dim recherche As String
Dim nomclient As String

'Intéger reference for FIND
recherche = InputBox("Pour quel réparation doit je extraire les clients ?", "référence de la
réparation")

'for every sheet in ThisWorkbook.Worksheets
For Each feuille In ThisWorkbook.Worksheets

'affect the variable to valeurtrouve
Set valeurtrouve = feuille.Range("C8:C10000").Find(recherche, , xlValues, xlWhole)

'if valeur trouve was find copy it
If valeurtrouve.Value = recherche.Value Then

'and paste in another sheet
Sheets.Add.Name = "liste client"
Sheets("listeclient").Range("A1").Cells.Range("_mailclient").Copy
Range("A2").Select
End If
Next feuille

'if isn't find next sheet
If Not valeurtrouve Is Nothing Then Exit For
Next feuille

'if no more sheet exit and message box and sub
If Not valeurtrouve Is Nothing Then
MsgBox (" la liste a été créer "), True
Else

'if no people was find message box and sub
MsgBox "Personne n'a cette rèf ... va falloir bosser un peu plus", vbInformation
End If

End Sub

I hope it's clear, i'm a begginer please be indulgent :')

A: Based on your information, I have modified your code and allow add new sheet multiple times using same name, and if new sheet added then will display successful message :
Sub recherche_mail()

Dim feuille As Worksheet, newWb As Worksheet
Dim valeurtrouve
Dim recherche As String

Dim i As Long, colNum As Long
Dim searchResult As Boolean

'Intéger reference for FIND
recherche = InputBox("Pour quel réparation doit je extraire les clients ?", "référence de la réparation ")
searchResult = False

colNum = 1

'for every sheet in ThisWorkbook.Worksheets
For Each feuille In ThisWorkbook.Worksheets

    'affect the variable to valeurtrouve
    valeurtrouve = feuille.Range("C8:C10")

If searchResult = True Then
        For i = LBound(valeurtrouve) To UBound(valeurtrouve)
        If InStr(CStr(valeurtrouve(i, 1)), recherche) > 0 Then
            feuille.Range("B1:B4").Copy newWb.Cells(1, colNum)
            colNum = colNum + 1
        End If
    Next
End If

If searchResult = False Then
    For i = LBound(valeurtrouve) To UBound(valeurtrouve)
        If InStr(CStr(valeurtrouve(i, 1)), recherche) > 0 Then
            Sheets.Add.Name = "liste client"
            Set newWb = ThisWorkbook.Worksheets("liste client")
            feuille.Range("B1:B4").Copy newWb.Cells(1, colNum)
            colNum = colNum + 1
            searchResult = True

        End If
    Next
End If

Next feuille

If searchResult = False Then
    MsgBox (" No record is found "), vbOKOnly
Else
    MsgBox "People found and new sheet created"
End If

End Sub

Let say if you key in RVA in the input box, new sheet will be added by copy `Range A1:B4' else nothing will happen, please try and adjust it for your need:
Combine Sheet

A: Feuil client

*

*i need a message boxe to put the reference, i will search

*when the reference was enter, the code will see on one sheet if the reference was here:
if yes : the copy it and paste it in a new sheet.
if not he pass to the next one

*next sheet : same action.
if he find something he copy it and past in the same sheet than the last step
if not he pass to the next one

*at the end :
if he have found something put a message boxe : sheet create
if not :" no client found")


text:
Q: IntelliJ IDEA 2017 - Connection error with database I clicked on View -> Tool Windows -> Database and I was trying to connect through Data Sources. Then I entered name of host, database, user, password and URL. I remembered to do downloading convenient driver, but when I want to make the test I see "failed" next to the button Test Connection and the following error:
Cannot run program "A:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\jre64\bin\java" (in directory "A:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\bin"): CreateProcess error=2, Nie można odnaleźć określonego pliku.
java.lang.RuntimeException: com.intellij.execution.ExecutionException: Cannot run program "A:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\jre64\bin\java" (in directory "A:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\bin"): CreateProcess error=2, Nie można odnaleźć określonego pliku
"Nie można odnaleźć określonego pliku." It means in Polish: "File cannot be found."
I updated IntelliJ and I was trying to connect with PostgreSQL and MySQL but unfortunately the problem is the same... Anyone have any similar error?


text:
Q: Float function return value I am writing my object first app and i can't understand why compiler gives my errors.
(With int codes works... )
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // 1st var
        NSLog(@"Hi, %f World!", res(1.0f, 2.0f, 3.0f));

    }
    return 0;
}
float res (float a, float b, float c)
{
    float res=a+b+c;
    return res;
}

A: Try declaring res before main, so that it is known to the compiler when it founds it in main. If you don't declare it beforehand, what happens is:

*

*the compiler first encounters res in main body;

*it makes up an "implicit declaration" for res, based on what it can infer from the way res is called inside of main; this implies an int return type, according to C conventions;

*when the real res is found later on, a mismatch between the inferred signature (i.e., return type) and the real one triggers the compilation error.
To fix it:
float res (float a, float b, float c);

int main(int argc, const char * argv[])
{
  @autoreleasepool {

    // 1st var
    NSLog(@"Hi, %f World!", res(1.0f, 2.0f, 3.0f));
  }
  return 0;
}

float res (float a, float b, float c)
{
  float res=a+b+c;
  return res;
}

A: You are just forgetting to declare function, just put
float res (float a, float b, float c);

before your int main
hope it helps you!

A: Try:
#import <Foundation/Foundation.h>

float res (float a, float b, float c)
{
    float res=a+b+c;
    return res;
}

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // 1st var
        NSLog(@"Hi, %f World!", res(1.0f, 2.0f, 3.0f));

    }
    return 0;
}


text:
Q: initialize castle container from a stream (not file) Is it possible to initialize a castle container (windsor) by passing a stream to
the XmlInterpreter somehow? It appears that the current implementation only supports
files.
thanx,
-tzurs

A: Inherit from AbstractStreamResource, then you can do:
var c = new WindsorContainer(new XmlInterpreter(new MyStreamResource(...)));

See FileResource for guidance.


text:
Q: Using Google OAuth2 API with Ruby on Rails I have a system with multiple customers accounts, each account has at least one website that has a Google Analytics account.
I need my clients authorize my system to access Google Analytics accounts so I can generate an automatic monthly report page views and present them this information with other information of my system. I would like to do this without the need for the customers to authorize my application to their Google Analytics account again.
When the client authorizes access to Google Analytics, it runs for about 1 hour (which I believe to be the session time token expires_in: 3600). After this time I cannot access Google Analytics client. As you can see in the code I already have tried to use the access_type:: offline and update the client token with client.update_token! but I do not know how to do this. Could anyone tell me if what I'm trying to do is possible and show me how to do this so I can generate monthly reports without the client authorize my application again?
I created some methods in my controller (I know the code isn't good, it's just a test and maybe I should encrypt the access token before writing it to my database).
class ContractedProductsController < ApplicationController

    def analytics_connection
        client_info = {
                client_id: Rails.configuration.x.google_api['client_id'],
                client_secret: Rails.configuration.x.google_api['client_secret'],
                authorization_uri: Rails.configuration.x.google_api['authorization_uri'],
                scope: Google::Apis::AnalyticsV3::AUTH_ANALYTICS_READONLY,
                redirect_uri: url_for(action: :analytics_callback),
                state: Base64.encode64('{ "account": ' + params[:account_id] + ', "contracted_product": ' + params[:id] + ' }'),
                additional_parameters: { access_type: :offline, approval_prompt: :force }
        }
        client = Signet::OAuth2::Client.new(client_info)

        redirect_to client.authorization_uri.to_s
    end

    def analytics_callback
        client_info = {
                client_id: Rails.configuration.x.google_api['client_id'],
                client_secret: Rails.configuration.x.google_api['client_secret'],
                token_credential_uri: Rails.configuration.x.google_api['token_credential_uri'],
                redirect_uri: url_for(action: :analytics_callback),
                code: params[:code]
        }
        client = Signet::OAuth2::Client.new(client_info)
        response = client.fetch_access_token!

        session[:google_api] = response
        state = JSON.parse(Base64.decode64(params[:state]), object_class: OpenStruct)

        redirect_to account_contracted_product_analytics_list_path(state.account, state.contracted_product)
    end

    def analytics_list
        client = Signet::OAuth2::Client.new(access_token: session[:google_api]['access_token'])
        service = Google::Apis::AnalyticsV3::AnalyticsService.new
        service.authorization = client

        @account_summaries = service.list_account_summaries
    end

    def analytics_save
        api_integrations = [
                {
                        entity_type: ContractedProduct.name,
                        entity_id: @contracted_product.id,
                        key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:access_token],
                        value: session[:google_api]['access_token']
                },
                {
                        entity_type: ContractedProduct.name,
                        entity_id: @contracted_product.id,
                        key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:refresh_token],
                        value: session[:google_api]['refresh_token']
                },
                {
                        entity_type: ContractedProduct.name,
                        entity_id: @contracted_product.id,
                        key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:profile_id],
                        value: params[:profile_id]
                }
        ]
        @api_integration = ApiIntegration.create(api_integrations)

        respond_to do |format|
            if @api_integration
                format.html { redirect_to [@account, @contracted_product], notice: I18n.t('controllers.contracted_products.analytics_data_successfully_saved', default: 'Analytics data was successfully saved.') }
                format.json { render :show, status: :ok, location: [@account, @contracted_product] }
            else
                format.html { render :analytics_save, status: :ok, location: [@account, @contracted_product] }
                format.json { render json: @contracted_products_service.errors, status: :unprocessable_entity }
            end
        end
    end

    def analytics_report
        entity_conditions = { entity_type: ContractedProduct.name, entity_id: @contracted_product.id }
        api_integration_access_token = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:access_token])
        # api_integration_refresh_token = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:refresh_token])
        api_integration_profile_id = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:profile_id])

        client = Signet::OAuth2::Client.new(access_token: api_integration_access_token.value)
        service = Google::Apis::AnalyticsV3::AnalyticsService.new
        service.authorization = client
        profile_id = 'ga:' + api_integration_profile_id.value
        start_date = Date.today.at_beginning_of_month.last_month.to_s
        end_date = Date.today.at_beginning_of_month.last_month.to_s
        metrics = 'ga:pageviews'
        dimensions = {
                dimensions: 'ga:date'
        }

        @report = service.get_ga_data(profile_id, start_date, end_date, metrics, dimensions)
    end

end

A: That was easy but I think I was not putting the token_credential_uri in the call to the API in my tests.
Observing this answer "How do I refresh my google_oauth2 access token using my refresh token?
" I found the right way to do it.
I just added the following params to the API call: client_id, client_secret, token_credential_uri and refresh_token.
def analytics_report
    entity_conditions = { entity_type: ContractedProduct.name, entity_id: @contracted_product.id }
    api_integration_refresh_token = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:refresh_token])
    api_integration_profile_id = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:profile_id])

    client_info = {
            client_id: Rails.configuration.x.google_api['client_id'],
            client_secret: Rails.configuration.x.google_api['client_secret'],
            token_credential_uri: Rails.configuration.x.google_api['token_credential_uri'],
            refresh_token: api_integration_refresh_token.value
    }
    client = Signet::OAuth2::Client.new(client_info)
    service = Google::Apis::AnalyticsV3::AnalyticsService.new
    service.authorization = client
    profile_id = 'ga:' + api_integration_profile_id.value
    start_date = Date.today.at_beginning_of_month.last_month.to_s
    end_date = Date.today.at_beginning_of_month.last_month.to_s
    metrics = 'ga:pageviews'
    dimensions = {
            dimensions: 'ga:date'
    }

    @report = service.get_ga_data(profile_id, start_date, end_date, metrics, dimensions)
end


text:
Q: Limit of $\mathbf{tan}^2(\theta)[1-\mathbf{sin}(\theta)]$ Evaulate the limit of $\mathbf{tan}^2(\theta)[1-\mathbf{sin}(\theta)]$.

$$\lim \limits_{\theta \to \frac{\pi}{2}} \mathbf{tan}^2(\theta)[1-\mathbf{sin}(\theta)] $$

I have attempted the problem by direct substitution and get:
$$\mathbf{tan}^2(\frac{\pi}2)[1-\mathbf{sin}(\frac{\pi}2)] $$
$$\infty^2 \cdot [0]$$
$$\infty \cdot 0$$
I do not know whether to state that it is zero, but I graphed it and got $\frac{1}{2}$.  The limit has to be evaluated algebraically.

A: $$\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \tan } ^{ 2 }(\theta )[1-{ \sin }(\theta )]=\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \tan } ^{ 2 }(\theta )\frac { 1-\sin ^{ 2 }{ (\theta ) }  }{ 1+{ \sin }(\theta ) } =\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \tan } ^{ 2 }(\theta )\frac { \cos ^{ 2 }{ (\theta ) }  }{ 1+{ \sin }(\theta ) } =\\ =\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \frac { \sin ^{ 2 }{ (\theta ) }  }{ 1+{ \sin }(\theta ) }  } =\frac { 1 }{ 2 } $$
Another way is to apply L'hospital's rule
$$\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \tan } ^{ 2 }(\theta )\left[ 1-\sin { \left( \theta  \right)  }  \right] =\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \frac { 1-\sin { \left( \theta  \right)  }  }{ \cot ^{ 2 }{ \left( \theta  \right)  }  }  } =\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \frac { -\cos { \left( \theta  \right)  }  }{ 2\cot { \left( \theta  \right) \left( -\frac { 1 }{ \sin ^{ 2 }{ \left( \theta  \right)  }  }  \right)  }  }  } =\frac { 1 }{ 2 } $$

A: Hint:
Multiply and divide by $1+\sin\theta$ and simplify.

A: If you make a substitution: $\sin\theta = \dfrac{x}{1}$ then $\tan\theta =\dfrac{x}{\sqrt{1-x^2}}$.

As $\theta \to \dfrac{\pi}{2}$, we have $\sin\theta = x\to 1$.
$$\lim_{\theta\to\pi/2} \tan^2(\theta)[1-\sin\theta] \ =\  \lim_{x\to 1} \ \dfrac{x^2}{1-x^2}[1-x]$$
$$= \lim_{x\to 1} \ \dfrac{x^2}{(1-x)(1+x)}[1-x] \ = \  \lim_{x\to 1} \ \dfrac{x^2}{(1+x)} = \dfrac{1^2}{1+1} = \dfrac{1}{2}$$
I know this is now what was intended for this exercise, but I thought it would be helpful.
When making substitutions like these you do need to be careful. I chose $\sin\theta$ because it is continuous at $\dfrac{\pi}{2}$.

A: $$\lim_{\theta \to \frac{\pi}{2}} (\tan^2\theta) (1-\sin\theta)$$
$$\lim_{\theta \to \frac{\pi}{2}} \left(\dfrac {\sin^2 \theta}{\cos^2{\theta}} \right) (1-\sin\theta)$$
$$\lim_{\theta \to \frac{\pi}{2}} \left(\dfrac {\sin^2 \theta}{1-\sin^2 \theta} \right) (1-\sin\theta)$$
$$\lim_{\theta \to \frac{\pi}{2}} \dfrac {\sin^2 \theta}{(1-\sin \theta)(1+\sin \theta)}  (1-\sin\theta)$$
$$\lim_{\theta \to \frac{\pi}{2}} \dfrac {\sin^2 \theta}{1+\sin \theta}  $$
Direct substitution now yields $\dfrac 12$.

A: Another way to do it.
Just as @zhw. answered
$$\lim _{ \theta \to \frac { \pi  }{ 2 }  }{ \tan } ^{ 2 }(\theta )[1-{ \sin }(\theta )]=\lim_{t\to 0}\, \cot^2(t)(1-\cos (t))$$ Now, use Taylor series built around $t=0$ $$\cos(t)=1-\frac{t^2}{2}+O\left(t^4\right)$$ $$1-\cos(t)=\frac{t^2}{2}+O\left(t^4\right)$$ $$\cot(t)=\frac{1}{t}-\frac{t}{3}-\frac{t^3}{45}+O\left(t^4\right)$$ $$\cot^2(t)=\frac{1}{t^2}-\frac{2}{3}+\frac{t^2}{15}+O\left(t^3\right)$$ $$\cot^2(t)(1-\cos (t))=\left(\frac{t^2}{2}+O\left(t^4\right) \right)\left(\frac{1}{t^2}-\frac{2}{3}+\frac{t^2}{15}+O\left(t^3\right) \right)=\frac{1}{2}-\frac{t^2}{3}+O\left(t^3\right)$$ which shows the limit and how it is approached.
Just for fun, plot on the same graph functions $f(t)=\cot^2(t)(1-\cos (t))$ and $g(t)=\frac{1}{2}-\frac{t^2}{3}$ for $-1 \leq t \leq 1$; you will be surprised to notice how close they are to eachother. Suppose now that you need to solve for $t$ equation $f(t)=\frac 14$. Using $g(t)$ as an approximation will give $t=\pm \frac{\sqrt{3}}{2}\approx \pm 0.866$ while the exact solution (much more difficult to obtain) would be $t=\pm \cos ^{-1}\left(\frac{1}{8} \left(1+\sqrt{17}\right)\right) \approx \pm 0.876$.

A: If we let $\theta = \pi/2-t,$ we are looking at
$$\lim_{t\to 0}\, \tan^2(\pi/2-t)(1-\sin(\pi/2-t)) = \lim_{t\to 0}\, \cot^2(t)(1-\cos t).$$
This is the same as
$$\lim_{t\to 0}\,\cos^2t\cdot\frac{t^2}{\sin^2 t}\cdot\frac{1-\cos t}{t^2} = 1\cdot 1^2\cdot (1/2) = 1/2.$$


text:
Q: Charged body in hollow conductor : what is the role of insulators and how does the charge distribution change if insulators vs conductors are used? Question as written in textbook: "Figure 1 illustrates a nested arrangement of four cylindrical conductors (seen side-on in cross-section) in which the cylinders are separated by electrical insulators. A body carrying a charge of –Q is suspended in the smallest cylinder."
Figure 1

This results in the following charge distribution (answer from textbook):
Figure 2

(note, the charges are meant to be on the surface of the conductor)
My question: How does having insulators between the conducting cylinders affect the problem, and what (if anything) would be different about the answer shown in Figure 2 if the material marked insulator was replaced with a conductor?

My thought process:

*

*I initially thought the insulator would result in only the inside cylinder (separated from the charged sphere without any insulators in the way) becoming charged, and the insulator that separates the first cylinder from the second would stop any polarization of the second cylinder. But due to the answer shown in  Figure 2, this is not the case.

*If I replaced the conducting cylinders and insulators with one big conductor, I would get the same result as Figure 2.

The insulator behaves as per the image below: But is this any different to how a conductor would behave (i.e. if the insulator in the question was replaced with a conductor?)

*

*The picture shows for the conductor the side near the negative charge will become positive, and the side opposite the negative charge will become positive.

*Similarly, for the insulator, the side near the negative charge will become positive, and the side opposite the negative charge will become positive (however, this occurs in small segments as the electrons are not free to move like in a metal)

(Image Source)

A: What the insulator does in this problem is keeping the shells electrically neutral.  So that any positive charge built on the inner wall will be balanced with the negative charge on the outer wall.  And your figure (unlabeled) of replacing the incubator layers with conductors is correct.

A: An insulator can be thought of as an extreme form of a dielectric. It does not result in decreasing the net electric field due to displacement of charge/ polarisation. So, the main reason the question mentions insulation is that you don't need to consider cancellation of the electric field in the region at all. Just pure E from the cylinders.
Connecting all the cylinders to form a block is correct, but what the question wants you to understand is how each part contributes to net polarisation of a bulk conductor.


text:
Q: Sort output from ls command I'm trying to sort the output from ls. The order that I'm going for is this:

*

*any directories with names that begin with _

*any directories with names that begin with +

*all soft links (which may include some dot files)

*all remaining .files

*all remaining .directories

*everything else

Everything is sorted alphabetically within these 'sublists'. At the moment I'm using the find command a number of times to find files meeting the criteria above. Following that I pipe the output from find to sort and then pass the entire sorted list to ls:
#!/bin/bash

find1=`find . -maxdepth 1 -name "_*" -type d -printf "%f\n" | sort`
find2=`find . -maxdepth 1 -name "+*" -type d -printf "%f\n" | sort`
find3=`find . -maxdepth 1 -type l -printf "%f\n" | sort`
find4=`find . -maxdepth 1 -name ".*" -type f -printf "%f\n" | sort`
find5=`find . -maxdepth 1 \( ! -name "."  \) -name ".*" -type d -printf "%f\n" | sort`
find6=`find . -maxdepth 1 \( ! -name "_*" \) \( ! -name "+*" \) \( ! -name ".*" \) \( ! -type l \) -printf "%f\n"`
find="$find1 $find2 $find3 $find4 $find5 $find6"
ls -dfhlF --color=auto $find

This doesn't handle any names that contain spaces, and overall seems a bit excessive. I'm sure there is a better way to do this. Any ideas?

A: Will this work for you?  It prints the files in the order you specified, but it won't print them in color.  In order to do that, you'd need to strip the ANSI codes from the names before pattern-matching them.  As it is, it will handle filenames with embedded spaces, but not horribly pathological names, like those with embedded newlines or control characters.
I think the awk script is fairly self-explanatory, but let me know if you'd like clarification.  The BEGIN line is processed before the ls output starts, and the END line is processed after all the output is consumed.  The other lines start with an optional condition, followed by a sequence of commands enclosed in curly brackets.  The commands are executed on (only) those lines that match the condition.
ls -ahlF --color=none | awk '
  BEGIN { name_col = 45 }
  { name = substr($0, name_col) }
  name == "" { next }
  /^d/ && substr(name, 1, 1) == "_" { under_dirs = under_dirs $0 "\n"; next }
  /^d/ && substr(name, 1, 1) == "+" { plus_dirs = plus_dirs $0 "\n"; next }
  /^l/ { links = links $0 "\n"; next }
  /^[^d]/ && substr(name, 1, 1) == "." { dot_files = dot_files $0 "\n"; next }
  /^d/ && substr(name, 1, 1) == "." { dot_dirs = dot_dirs $0 "\n"; next }
  { others = others $0 "\n" }
  END { print under_dirs plus_dirs links dot_files dot_dirs others }
'


text:
Q: Understanding special type of access C++/C array I have the following code snippet:
int ndigit[10] = {0,0,0,0,0,0,0,0,0,0};

void count() {
    char c;
    while (cin.get(c)) {
    if (c>='0' && c<='9') {
        ndigit[c-'0']++;
    }
}

So c has to be between 0 and 9 (with 0 and 9), so why it is necessary to index the array like ndigit[c-'0'] instead of just ndigit[c] ?
If I am right, in both cases a c value can occur more then once, so a the value of ndigit[c-'0'] gets overwritten anyway...
I appreciate your wisdom!

A: when you type the character 0 as input to this program you will get a byte with the hex value x30 (see http://www.asciitable.com/)
To access the first element of the array you need x00 (binary 0). Subtracting x30 from the typed char will give you 0.
The logic works because the ASCII codes for 0-9 are x30,x31,..x39. So subracting 0x30 (or '0' same thing) will give you 0-9

A:
"So c has to be between 0 and 9"

No! c has to be between '0' and '9', and it makes the difference.
Every character has appropriate numeric value (ASCII code), e. g.:

*

*'A' has 65

*'B' has 66

*'a' has 98

In C language characters are simply numbers, e. g. 'A' + 'B' is a perfectly valid expression and means 65 + 66.
If we want display or read a digit (0, 1, ..., 9), we actually use its symbolic representation, i. e. an character ('0', '1', ..., '9'). And these characters amazingly have not ASCII values 0, 1, ..., 9, but 48, 49, ... 57 - they are all shifted by 48.
So for converting a digit symbol, e. g. '7' (which has ASCII value 55 - as 7 + 48) into a number which we people see in it (i. e. 7 - without apostrophes), we need simply subtract this shifting number 48 from its ASCII value:
    (7 + 48) - 48

which is the same as to subtract '0' (= 48) from '7' (=55):
    '7' - '0'

and witch is exactly what does the expression
    c - '0'

in your code.


text:
Q: Will Service Worker Query Cache Algorithm Allow Expression Matching URL paths? I discovered a use case for matching Request urls using an expression that ignores part of a url path (path not ignoreSearch).
The use case is for an image processing service used in a responsive design where the dimensions of the image are encoded in the url path. This is sort of common among these kinds of services (Cloudinary, Firesize, even Lorempixel).
I noticed every once in a while, one of the dimension components will request will be off by one pixel. The required dimensions are calculated from the client - source of the error is rounding here - But the service worker cache could be an elegant solution for this variation.
However, this rounding problem results in a cache miss because I can't specify that part of the url path can be ignored.
Will url expression matching ever become part of the spec?
In general, is it ok that the 'fetch with url A, cache put/match with url B' pattern grow?
I get that the work around for this is the same as the current work around for ignoreSearch (until its implementation), wherein you fetch with one url but cache with another. I'm just wondering if url path expression matching will ever become part of the spec, or if an url expression matching use case has been considered. I don't see any evidence of this in the authoritative spec.
Thanks in advance for any words of insight.

A: It might be considered at some point in the future if it becomes a dominant pattern in many applications. Usually if something is fairly common it'll eventually be included in the standard so it can be made faster and more reliable. I wouldn't count on it happening anytime soon though and without many libraries having support for it.


text:
Q: Can not get IMSI and IMEI with AT commands I am using a raspberry pi to communicate with an SL8092 modem from Sierra. I am able to communicate with the device via the /dev/ttyUSB4 using minicom.
Sending AT commands returns the following answers:
> AT
< OK
> AT+CSQ
< +CSQ: 30,99
>AT+COPS
<+COPS: 2

But when sending AT+CIMI or AT+CGSN, I am expecting to get the IMSI and the IMEI. Unfortunately it's not the case - the only answer I get is just "OK".
Am I missing something?

A: Have you checked this document?
http://source.sierrawireless.com/resources/airprime/minicard/2130617_ac_ap_umts_supported_at_command_reference/
Free signup on sierrawireless if you don't have login.
From document:
!GRELIMEI
Return the modem's production TAC (Type Allocation Code).
(TAC is first 8 characters,then padded with zeroes).
For example, if IMEI is 289258158732085, the TAC is 289258150000000.
Usage:

*

*Query: AT!GRELIMEI?

*Response: [TAC] OK

*Purpose: Return the [TAC] assigned to the modem.

*Parameters: [TAC] 15-character string. (TAC is the first 8 characters, and remainder of string is zeropadded.)

Example:
If the modem's IMEI is 289258158732085, !GRELIMEI returns 289258150000000.

A: You can try using these AT commands and find out which are valid with your device. This is for the phone so I am not sure it works with your Pi.

*

*API

*AT+IMEINUM

*AT+DEVCONINFO

*AT%IMEI?

You can find out some useful AT commands here: https://atcommands.org/atdb/


text:
Q: OpenSSH libaudit.so missing I have a server running CentOS 6.3. I want to re-install openssh on my server.
When I use yum install openssh-server I get this error:
Error: Package: openssh-server-6.1p1-5.el5.1.x86_64 (CentALT)
           Requires: libaudit.so.0()(64bit)
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

I can't find a fix on the internet, how can I fix this?
Note:
Audit-libs is running the latest version
Thanks

A: From your error message it appears that you were using the CentOS / RHEL 5 version of the CentALT repo, but you say you are using CentOS 6.3.  You should remove the CentALT 5 repository from your system (found in /etc/yum.repos.d/) and switch to version 6 as described here: http://mirror.neu.edu.cn/CentALT/readme.txt
Note: according to this page, http://tecadmin.net/top-5-yum-repositories-for-centos-rhel-systems/ , CentALT is no longer active.


text:
Q: Get the value of static properties from static methods in JavascriptMVC I'm working on my first project with JavascriptMVC.
I have a class Foo.
$.Class('Foo',{
    // Static properties and methods
    message: 'Hello World',
    getMessage: function() {
        return Foo.message;
    }
},{});

This works fine. But what if I don't know the class name?
I want something like this:
$.Class('Foo',{
    // Static properties and methods
    message: 'Hello World',
    getMessage: function() {
        return this.message;
    }
},{});

but I can't use this in a static property.
So, how can I get the current class name from a static method.
From a prototype method it is easy:
this.constructor.shortName/fullName.

but how to do it in a static method?

A: The truth is, that I was wrong. It is possible to use this in a static method.
Here is a little code snippet that can help to understand how JavascriptMVC's static and prototype methods and properties work, also the scope of this in both of them.
$.Class('Foo',
{
  aStaticValue: 'a static value',
  aStaticFunction: function() {
    return this.aStaticValue;
  }
},
{
  aPrototypeValue: 'a prototype value',
  aPrototypeFunction: function() {
    alert(this.aPrototypeValue); // alerts 'a prototype value'
    alert(this.aStaticValue); // alerts 'undefined'
    alert(this.constructor.aStaticValue); // alerts 'a static value'
  }
});

alert(Foo.aStaticFunction()); // alerts 'a static value'
var f = new Foo();
alert(f.aPrototypeValue); // alerts 'a prototype value'
f.aPrototypeFunction();


text:
Q: Django - Object of type FloatField is not JSON serializable I have a service in django, and I am trying to get the list of all vital signs, but when I run it, it throws me the following error.

This is the model "SignoVital".
from django.db import models

from .paciente import Paciente

class SignoVital(models.Model):
    oximetria = models.FloatField()
    frecuenciaRespiratoria = models.FloatField()
    frecuenciaCardiaca = models.FloatField()
    temperatura = models.FloatField()
    presionArterial = models.FloatField()
    glicemia = models.FloatField(),
    paciente = models.ForeignKey(
        Paciente,
        on_delete=models.CASCADE,
        unique=False,
        blank=True,
        null=True
    )

This is serializer "SignoVitalSerializer".
from rest_framework import serializers
from hospiApp.models.signoVital import SignoVital

class SignoVitalSerializer(serializers.ModelSerializer):
    class Meta:
        model = SignoVital
        fields = ['oximetria', 'frecuenciaRespiratoria', 'frecuenciaCardiaca', 'temperatura', 'presionArterial', 'glicemia', 'paciente']

This is View "SignoVitalTodosView".
from rest_framework import generics,status, views
from rest_framework.response import Response
from rest_framework.views import APIView

from hospiApp.models.signoVital import SignoVital
from hospiApp.serializers.signoVitalSerializer import SignoVitalSerializer

class SignoVitalTodosView(generics.ListCreateAPIView):
    queryset = SignoVital.objects.all()
    serializer_class = SignoVitalSerializer
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)

This is urls.py
from django.contrib import admin
from django.urls import path
from hospiApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('signoVitalTodos/', views.SignoVitalTodosView.as_view()),
]

A: Remove the comma after the glicemia = models.FloatField(), line in the SignoVital model and then create the migrations again and apply them using the following commands.
python manage.py makemigrations

python manage.py migrate

This will fix the issue.


text:
Q: Excel 2013 - Sum with a date range Good day, I have finally decided to ask for help. I have 1 workbook, multiple worksheets. The formula gives me #Value! which I am understanding that it has a wrong datatype. I am simply wanting look at a range within 1 column of dates, then add a column of numbers in 2 separate columns and divide those 2 columns and multiply by 30. It amounts to this. SUM(D31/C31)*30. This small formula works great when just using the numbers. I am taking total hours divided by amount of production multiplied by 30 dollars per hour. Obviously I will do this for each month of the year.
The 2 sheets are labeled as follows. This formula below resides on sheet "Monthly". It is referencing sheet "Overall Cost". I am hoping I have given you enough information that perhaps you might have the time to assist me. Note: I have the range pretty long because this is supposed to work for the whole year so I made it 10,000 rows deep.
Formula:
=SUMPRODUCT(('Overall Cost'!$B$3:$B$10000<=DATE(2015,9,30))*('Overall Cost'!$B$3:$B$10000>=DATE(2015,9,1)),SUM(('Overall Cost'!$D$3:$D$10000)/SUM('Overall Cost'!$C$3:$C$10000))*30)

Sample data:
               "B"      "C"    "D"
                       SQ FT   Hours
              Date       OH     OH
Wednesday   8/10/15     3427    232
Thursday    8/11/15     5536    232
Friday      8/12/15     2364    232
Monday      8/1/15      6408    232
Tuesday      9/4/15     2499    232
Wednesday    9/5/15     870     232

A: You cannot use a SUM function within a SUMPRODUCT function like that. The SUMPRODUCT is trying to process each row by row and the SUM is totalling all of the rows into a single figure.
You are also going to get a number of #DIV/0! errors due to SUMPRODUCT's strong calculation mode. Your extra rows ranging down to 10000 can be truncated to the extent of the dates in column B. Since they are the criteria, it stands to reason that no numbers in column C and D would be significant in rows beyond the last date.
=SUMPRODUCT(('Overall Cost'!B$3:INDEX('Overall Cost'!B:B, MATCH(1E+99, 'Overall Cost'!B:B ))<DATE(2015, 10, 1))*
            ('Overall Cost'!B$3:INDEX('Overall Cost'!B:B, MATCH(1E+99, 'Overall Cost'!B:B ))>=DATE(2015, 9, 1)),
             'Overall Cost'!$D$3:INDEX('Overall Cost'!D:D, MATCH(1E+99,'Overall Cost'!B:B)),
          30/'Overall Cost'!$C$3:INDEX('Overall Cost'!C:C, MATCH(1E+99,'Overall Cost'!B:B )))

I've also adjust your maths hierarchy a bit. Multiplying the division of columns C and D was the same as multiplying column D by the fraction created by 30 over column C.

Providing you have no zero values in column C you should be alright. If you do then an IFERROR function or additional criteria may have to be brought in. This formula also limits calculation only to exactly what is needed with no blank 'safety-zone' of blank cells.
If yo are still receiving #DIV/0! errors then there must be blank cells or cells with 0 in column C. A #DIV/0! error is literally that; you are trying to divide a number by zero.
This can be solved with the IFERROR function but an extra layer of processing is required so you need to use Ctrl+Shift+Enter↵ to finalize the following formula.
=SUMPRODUCT((oc!B$3:INDEX(oc!B:B, MATCH(1E+99, oc!B:B ))<DATE(2015, 10, 1))*
               (oc!B$3:INDEX(oc!B:B, MATCH(1E+99, oc!B:B ))>=DATE(2015, 9, 1)),
             oc!$D$3:INDEX(oc!D:D, MATCH(1E+99,oc!B:B)),
             IFERROR(30/oc!$C$3:INDEX(oc!C:C, MATCH(1E+99,oc!B:B )), 0))

This can be mimicked with a non-CSE formula by forcing the numerator to zero and the denominator to one when encountering a #DIV/0! situation.
=SUMPRODUCT((oc!B$3:INDEX(oc!B:B, MATCH(1E+99, oc!B:B ))<DATE(2015, 10, 1))*
              (oc!B$3:INDEX(oc!B:B, MATCH(1E+99, oc!B:B ))>=DATE(2015, 9, 1))*
              (oc!$C$3:INDEX(oc!C:C, MATCH(1E+99,oc!B:B ))<>0),
             oc!$D$3:INDEX(oc!D:D, MATCH(1E+99,oc!B:B)),
         30/(oc!$C$3:INDEX(oc!C:C, MATCH(1E+99,oc!B:B ))+
              (oc!$C$3:INDEX(oc!C:C, MATCH(1E+99,oc!B:B ))=0)))


text:
Q: What's the difference between example.com and www.example.com? I'm a developer and I'm having trouble setting up some hosting, and I hope you guys can help me out.
I've got a domain I'm setting up for a friend. URLs work fine when I use the short form, like http://example.com. That is, the pages render properly and I get HTTP/200 responses. When I try http://www.example.com, however, I get a HTTP/502 error. Pinging it gives me,

Ping request could not find host www.example.com. Please check the name and try again.

I'm stumped, because I don't know enough terminology to  formulate a good keyword search. Can anyone give me some info on what I might need to do to set up some kind of alias so that the standard www. form will work? I don't know whether to talk to my registrar or my hosting company, what to ask them for, or where to look in the various control panels.
Any help at all — even just naming the different pieces — would be helpful. I don't know my TLDs from my domain aliases from my CNAMEs.

A: It would seem that you don't (or your friend) doesn't have a DNS record for 'www' in his domain, this would account for the problem of not being able to resolve the address.
To resolve this it should be as easy as creating a new A record (also known as a HOST record) for 'www' and mapping it to the IP address of his web server, with his DNS provider.
A list of DNS record types can be found at http://en.wikipedia.org/wiki/List_of_DNS_record_types

A: There's really no difference in these two names other than the fact that one has a subdomain prepended to it and the other doesn't.  You can set up resource records to take advantage of an almost unlimited amount of subdomains once you own a domain name.
There are at least 30 different types of resource records.  For now you can probably get by with focusing on two:

*

*aname ("a" record - primary address record)

*cname (Alias of one name to another)

www is by far the most common subdomain but there are many others. Take a look at the following examples:

*

*gmail.google.com

*my.yahoo.com

What you need to understand is that google.com and yahoo.com are domain names. Anything before that is referred to as a host name or a subdomain.  As long as you take the necessary steps to set up your DNS resolution to resolve these subdomains to either their own IP address (use A Name) or as an alias (use a Cname) and you set up your webserver to understand such requests you'll be set.
In your case you should use a cname to point www.domainname.com to domainname.com.  A cname is more appropriate as an answer only if you intend to point both to the same IP.  That way if you need to change your IP in the future, you'll only need to adjust one record.
As for getting your webserver to understand both requests there are lots of examples for both Apache and IIS on serverfault.  Do a search and you'll find everything you need.  Look for virtual hosts.
Edit:  Here's a cross reference about cnames.  They have their place too.  Use the tool that best suites your circumstances.

A: What's the difference between domainname.com and www.domainname.com?
A host record ( also known as an A record ).
You could also use an alias (what's known as a CNAME) although this would require the client to do two DNS lookups, so your better off with an A record.

A: Technically example.com and www.example.com are different domain names. One could have 2 completly different websites on them (although that's quite bad practice).
What you need to do is set up a new record for www to point to the same host (ie computer/server/machine/whatever) as example.com.


text:
Q: What to use instead of explicit recursion in Haskell? Write a function that doubles other number beginning with the 2nd number from the right:
Example:
doubleEveryOther   [8,7,6,5]
=> [16,7,12,5]

doubleEveryOther     [1,2,3]
=> [1,4,3]

O(n) solution:
doubleEveryOther :: Num a => [a] -> [a]
doubleEveryOther xs0 =
    let (_,r)   = deo xs0
        deo xs1 = case xs1 of
            []     -> (False, [])
            (x:xs) -> let (b, xs') = deo xs in ((not b), (if b then 2*x else x) : xs')
    in r

The use above of explicit recursion is generally considered poor Haskell style (e.g., use fold*, scan, etc where possible).
QUESTIONS

*

*what Haskell library functions cover the above case?

*what would be a more concise/idiomatic Haskell solution that is still O(n)?

*is there a name for the above type of recursion (where we use the value from a deeper recursion to make a decision the next level up)?

A: You can use foldr to do this kind of recursion from the right:
doubleEveryOther = snd . foldr go (False, [])
    where go x (b, xs) = (not b, (if b then 2*x else x) : xs)

A: Another way to define this function by using standard library functions:
doubleEveryOther ls = reverse $ zipWith (*) (cycle [1,2]) (reverse ls)

Or in pointfree style
doubleEveryOther = reverse . zipWith (*) (cycle [1,2]) . reverse

A: Lots of useful answers here, but no one yet mentioned the rarely seen function mapAccumR from Data.List which fits this particular use case almost perfectly:
doubleEveryOther :: Num a => [a] -> [a]
doubleEveryOther = snd . mapAccumR step False
  where
    step False x = (True, x)
    step True  x = (False, 2*x)

A: As to question 1 and 2, with lens you can define the function in a declarative manner:
import Control.Lens

doubleEveryOther :: Num a => [a] -> [a]
doubleEveryOther = reversed . traversed . indices odd *~ 2

Operationally, this involves reversing the list, then modifying, then reversing again, but of course it's still O(N) with any constant number of reversals.

A: An alternative is to use the
lens package.
This allows you to avoid explicit recursion and remain very flexible on what data structures you can operate on.
You can use the elements traversal.  It takes a Int -> Bool function to decide what indices to act on.
Double even indices or odd indices.
> over (elements even) (*2) [8,7,6,5]
[16,7,12,5]
> over (elements odd) (*2) [8,7,6,5]
[8,14,6,10]

Or double every third element:
> over (elements (\n -> mod n 3 == 0)) (*2) [8,7,6,5]
[16,7,6,10]

Not just lists
This technique will work for any datatype that has a Traversable instance.
For example take the standard tree datatype for the
containers.
> import Data.Tree
> let tree = Node 1 [Node 2 [Node 3 [], Node 4 []], Node 5 [Node 6 []]]
> let prettyTree = putStrLn . drawTree . fmap show
> prettyTree tree
1
|
+- 2
|  |
|  +- 3
|  |
|  `- 4
|
`- 5
   |
   `- 6
> prettyTree $ over (elements even) (*2) tree
2         --   1
|         --   |
+- 2      --   +- 2
|  |      --   |  |
|  +- 6   --   |  +- 3
|  |      --   |  |
|  `- 4   --   |  `- 4
|         --   |
`- 10     --   `- 5
   |      --      |
   `- 6   --      `- 6

Your questions.

*

*The lens package has a number of functions that help with handling recursion with out being explicit.

*The lens is concise, though some do not yet considered it idiomatic.  I have not tested the bigO of the above functions.  My understanding is that it will depend on the bigO of the traversable instance for the datatype you are using.
The list instance in the Traversable module looks straightforward and should meet your expectations.:
instance Traversable [] where
    {-# INLINE traverse #-} -- so that traverse can fuse
    traverse f = Prelude.foldr cons_f (pure [])
          where cons_f x ys = (:) <$> f x <*> ys

*I am not sure what you are asking for here.

A: You can use map as well:
Prelude> let f ns = map (\(a,b) -> if (even (length ns) && even b) || (odd (length ns) && odd b) then a else a * 2) $ zip ns [1..]

Prelude> f [8,7,6,5]
[16,7,12,5]

Prelude> f [8,7,6]
[8,14,6]

A: My solution using mutual recursions
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther xs
    | even n =  doubleOdd xs
    | otherwise = doubleEven xs
  where n = length xs

-- | use mutual recursion
doubleEven :: Num a => [a] -> [a]
doubleEven (x:xs) = x : doubleOdd xs
doubleEven [] = []

doubleOdd :: Num a => [a] -> [a]
doubleOdd (x:xs) = (2*x) : doubleEven xs
doubleOdd [] = []

A: For the sake of completeness, here is your solution encoded as a recursion-schemes zygomorphism, as anticipated by András Kovács's remark:
{-# LANGUAGE LambdaCase #-}

import Data.Functor.Foldable

doubleEveryOther :: Num a => [a] -> [a]
doubleEveryOther = zygo flagAlg emitAlg
    where
    flagAlg = \case
        Nil -> False
        Cons _ b -> not b
    emitAlg = \case
        Nil -> []
        Cons x (b, xs) -> (if b then 2*x else x) : xs


text:
Q: firefox web extension tutorial: script repeat itself I've followed the following guide to train myself at firefox addon:
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
Then I started tweaking the code to add my own functions, keeping the same architecture/logic.
But then I noticed that my functions, when launched by clicking in the menu, execute sereval times, actually the number of times I've clicked in the addon menu since I loaded the page.
example: I created a menu option called Repeat Test that links to a function called "Repeat Test" that is just console.log('1');
- first click, I get 1
- second click, I get 1 / 1
- third click, I get 1 / 1 / 1
where can that come from ?
my code:
beast.html
<!DOCTYPE html>

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

Remove Model Map

Color Formulas

Image Overlay

Repeat Test

choose_beast.js:
   function optionSelection(myvar) {

  switch (myvar) {
    case "Remove Model Map":
      return "modelMap";
    case "Color Formulas":
      return "colorFormulas";
    case "Image Overlay":
        return "imageOverlay";
    case "Repeat Test":
      return "repeatTest";
  }
}

document.addEventListener("click", function(e) {
  if (!e.target.classList.contains("beast")) {
    return;
  }

  var clickedOption = e.target.textContent;
  var optionActivated = optionSelection(clickedOption);

  chrome.tabs.executeScript(null, {
    file: "/content_scripts/beastify.js"
  });

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {option: optionActivated});

  });

});

and finally, beastify.js:
function myaddon(request, sender, sendResponse) {

  switch (request.option){
    case "modelMap": removeModelMap();
    case "colorFormulas" : colorFormulas();
    case "imageOverlay" : overlay();
    case "repeatTest" : repeatTest();
  }

}

function repeatTest()
{
  console.log('1');
}

chrome.runtime.onMessage.addListener(myaddon);

A: I've found the issue here. this code
chrome.tabs.executeScript(null, {
    file: "/content_scripts/beastify.js"
  });

is contained into the click event manager, so every time you click, the script is executed, which adds to the fact that later on a message is sent to the script every time a click is made.
I don't know if this is a mistake or not (it's actually like this on the mozilla website):
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
but it was quite annoying for me. I'll notify them.


text:
Q: How to save server responses to a dynamic variable datasets_uids <- c("b0ozQvcc7nP","D9CrlbX7KBV")
servers <- c("url1","url2")
for (i in 1:length(datasets_uids)) {

  for(j in 1:length(servers)){

    assign(paste("postOrgUnitsToDataset",j,sep="_"),httr::POST(paste0(servers[j],"dhis/api/dataSets/",datasets_uids[i],"/organisationUnits"),                                       body=httr::upload_file("file.json"),
                                      httr::verbose(),
                                      httr::authenticate("username","password", type = "basic"),
                                      httr::content_type("application/json"),
                                      httr::progress("up"),
                                      httr::set_config(httr::config(ssl_verifypeer = 0L))
    ))
  }
}

 I want all the four responses to be saved as below
postOrgUnitsToDataset_1=response1
postOrgUnitsToDataset_2=response2
postOrgUnitsToDataset_3=response3
postOrgUnitsToDataset_4=response4

But the responses are being overwritten and saved in two responses as below
postOrgUnitsToDataset_1=response3
postOrgUnitsToDataset_2=response4

So how do I modify my code above to have all the responses saved in postOrgUnitsToDataset_1,postOrgUnitsToDataset_2,postOrgUnitsToDataset_3,postOrgUnitsToDataset_4

A: It's generally a bad idea to create global variables with assign. It's much easier to work with data in lists in R. One way to iterate to create a list is lapply. Here we first create all the URLs and then send a request for each
datasets_uids <- c("b0ozQvcc7nP","D9CrlbX7KBV")
servers <- c("url1","url2")

requests <- expand.grid(uid=datasets_uids, server=servers) |>
  transform(url=paste0(server,"dhis/api/dataSets/",uid,"/organisationUnits"))

postOrgUnitsToDataset <- lapply(requests$url, function(url) {
  httr::POST(url,
     body=httr::upload_file("file.json"),
     httr::verbose(),
     httr::authenticate("username","password", type = "basic"),
     httr::content_type("application/json"),
     httr::progress("up"),
     httr::set_config(httr::config(ssl_verifypeer = 0L))
)})

Then all the data will be in postOrgUnitsToDataset[[1]], postOrgUnitsToDataset[[2]], etc. It will be in the same order as the records are shown in the requests data.frame


text:
Q: In sitecore, where can I add my own custom CSS? Our sitecore developer quit suddenly and I need to make a small change. I'm a front end developer and have no real experience with the sitecore backend. I just need to add some CSS styles to the main style.css file or I need to add my own file. I've got full access to the CMS, but no access to the hosting account. I'm trying to find the main CSS file through the CMS browser, but I'm not having any luck.
Can you help me either:
A) Locate the main CSS file so I can add some classes (preferred)
B) Add my own link in the tag to my own CSS file hosted on another domain
C) Use the home page link to CSS file where I can add some classes
A note about OPTION C... I'm in the CMS and I see there is a system folder and in that a CSS folder where I can add a custom.css file. Then I go to the home page and I can actually call that CSS file from a field in the home page BUT, when the site loads, even though it's calling this file, it comes over as .aspx and it's blank so no styles I set are applied.

A: you can find the location of file as suggested by Maciej or use firebug or any other developer tools to find the location of main style.css. Once you get the location you can browser the physical file on server by going to Sitecore start menu -> All Application ->File explorer . Download file using File explorer make your changes and upload it back, make sure you check override existing file when you upload. Also make sure you upload file to delivery server once you test your changes, typically you will be accessing Sitecore using  Authoring Server so instance you are accessing might not be same as CD server.

A: You could right-click in your browser to figure out where your css is coming from relative to the server root. Although not completely fool-proof, this method may give you a quick answer.
According to documentation for sitecore 6.2, style sheet location is determined by the developer so it could be anywhere that the developer has chosen.
Take a look at this answer for more details.

A: You should also be wary of how code gets built and deployed. Most Sitecore developers have very specific methodologies for how they include code (including front end) in their solutions.
Make sure you're aware of any deployment methodologies your developer used, so that your work doesn't get overwritten in a future deployment.
Did they use a source control management solution (like Git or TFS)? Did they use an automated tool to do deployments (like Octopus Deploy)?

A: If you can find main CSS file in physical location, you can update the file with new CSS styles.
If you want to add your own CSS as an additional CSS style, you might need to create a new template for css link and use that template when you create new page with your own CSS.

A: Just for future reference, by default the location of the used css files is described in Sitecore.config like this:
    <!--  WEB SITE STYLESHEET
        CSS file for HTML content of Sitecore database.
        The file pointed to by WebStylesheet setting is automatically included in Html and Rich Text fields.
        By using it, you can make the content of HTML fields look the same as the actual Web Site
  -->
<setting name="WebStylesheet" value="/default.css"/>

Paths are relative to the root of your sitecore installation, you can find default.css in the root of the sitecore application on the webserver.

A: In Chrome Browser, Inspect element and select source tab
and open required css file and make changes.