text:
Q: Editing scheduled pending intends I wrote an app to turn on/off WiFi at scheduled time choosen before.
The way it works is preety simple: Choose time from timepicker, then just add it. Programmatically it gets data from timepicker and sets and alarm.
I'd write down a code for my activity and broadcast receiver first, bellow this code I'll write my questions. Don't worry, I put comments inside the code to be more clear to read and understand
Wifi.class:
public class WiFi extends AppCompatActivity {
private final int TEMP_REQUEST_CODE = 1;
private AlarmManager alarmManager;
private TimePicker timePicker;
private PendingIntent pendingIntent;
private Intent intent;
private Context context;
private Calendar calendar;
Intent alarmIntent;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wifi_class);
    timePicker = (TimePicker) findViewById(R.id.timePicker1);
    timePicker.setIs24HourView(true);
    setTitle("Set WiFi off/on");
    //store context in global variable
    context = getApplicationContext();
    //creates an intent that will be used in pending intent
    initializeView();
    //creates pending intent
    createAlarmIntent();
    //checks if alarm exists and sets matching text on the screen
    checkAlarmExists();

}

// I got an add button in my toolbar that saves the alarm, same as to delete
an alarm
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.tick:
            Alarm();
            finish();
            return true;
        case R.id.dismiss:
            cancelAlarm();
        default:
            return super.onOptionsItemSelected(item);
    }
}
//this method initialize intent and stores it into variable,
WiFiService.class extends BroadcastReceiver
//and all what it has to do is to turn wifi on/off
private void initializeView () {
    intent = new Intent(context, WifiService.class);

    //creating global pendingIntent variable
     pendingIntent = PendingIntent.getBroadcast(context,
            0,
            intent,
            0);
    //creating global alarmManager variable
     alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
}
//this method gets selected time from timepicker and calls another method to
create an alarm
private void Alarm() {
     calendar = Calendar.getInstance();
    if (Build.VERSION.SDK_INT >= 23) {
        calendar.set(
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH),
                timePicker.getHour(),
                timePicker.getMinute(), 0
        );

    } else {
        calendar.set(
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH),
                timePicker.getCurrentHour(),
                timePicker.getCurrentMinute(),
                0);
    }
    setAlarm();
}

/**
 * This method sets Alarm that will be executed even in Doze mode and will
intent WifiServices class,
 * in the result it will turn wifi off or on
 *
 */
private PendingIntent createAlarmIntent() {
     alarmIntent = new Intent(this, WifiService.class);
    return PendingIntent.getBroadcast(this, TEMP_REQUEST_CODE,
            alarmIntent, 0);
}
private void setAlarm() {
//setting alarm
    PendingIntent intent = createAlarmIntent();
    if (Build.VERSION.SDK_INT >= 23) {
        alarmManager.setAlarmClock(new
AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(), pendingIntent),
intent);
}
    else {
        alarmManager.setExact(AlarmManager.RTC, calendar.getTimeInMillis(),
pendingIntent);
    }

    long AlarmMgs = calendar.getTimeInMillis() -
Calendar.getInstance().getTimeInMillis();
    Toast.makeText(context, "Alarm will be executed in " + AlarmMgs / 1000 /
60 + "min", Toast.LENGTH_SHORT).show();

}

/**
 * This method should cancel alarm that is being currently set. There is no
 if/else statement
 * because it always says that alarm exists (see next method)
 */
private void cancelAlarm() {

    alarmManager.cancel(createAlarmIntent());
    Toast.makeText(context, "Alarm dismissed", Toast.LENGTH_SHORT).show();
    checkAlarmExists();
}

/**
 * This method checks wrether alarm is set or not and assigns that into
 TextView
 * Unfortunately it always says it exists
 */
private void checkAlarmExists() {

    boolean alarmExists =
            (PendingIntent.getBroadcast(context,
                    0,
                    intent,
                    PendingIntent.FLAG_NO_CREATE)
                    != null);

    TextView alarmSetter = (TextView) findViewById(R.id.alarmSet);
    if (alarmExists) {
        alarmSetter.setText("Alarm is set");

    } else {
        alarmSetter.setText("Alarm is not set yet");
    }
}
    //TODO: (1): Create more than 1 alarm without replacing one before
    //TODO: (2): Cancel one of them, not all of them
    //TODO: (3): Edit those alarms
}

WifiService class:
public class WifiService extends BroadcastReceiver {

public static final String TAG = "WiFi";

@Override
public void onReceive(Context context, Intent intent) {
//        if
(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{

        WifiManager wifiManager = (WifiManager)
context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        Log.v("Wifi", "checked");
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
            Toast.makeText(context, "Turning wifi off",
Toast.LENGTH_SHORT).show();
            Log.v(TAG, "Turned off");
        } else {
            wifiManager.setWifiEnabled(true);
            Toast.makeText(context, "turning wifi on",
Toast.LENGTH_SHORT).show();
            Log.v(TAG, "turned off");
        }
//        }
    Log.v(TAG, "Works");
}

}

Okay, I left 3 TODOs in the code:
1. I want to create 1 or more alarms without replacing existing one, all I have to do is to set pending flag to update every time when I set an alarm?
2. If I create e.g 3 alarms, I want to cancel one of them, specified one. I will store those alarms in database anyway, so my way of thinking is that:
create an alarm --> add it to a database --> display in a list -->
if removed --> remove from the list --> disactivate
3. Editing alarms. I know how to edit items in database, but how to edit scheduled alarm? I mean to edit its time of fire. Is it all about recreating an alarm?
Could anyone answer for my questions? Thanks in advance.

A: When you set an alarm, you pass a PendingIntent to AlarmManager. The PendingIntent wraps an Intent. When you set an alarm, AlarmManager deletes any alarms it already has scheduled that match the PendingIntent. To determine if the PendingIntents match, the following are compared:

*

*The requestCode in the PendingIntent.getBroadcast() call

*The ACTION in the Intent

*The CATEGORIES in the Intent

*The DATA in the Intent

*The Component (package name, class name) in the Intent
NOTE: "extras" in the Intent are not compared
So, if we want to reschedule an alarm, you just need to create a PendingIntent with the same requestCode, ACTION and Component as the previous one and set the alarm again. AlarmManager will remove the previous one and set the new one.
If you want to have multiple alarms scheduled in parallel, you need to ensure that either the requestCodes, the Components or the ACTIONs are different, otherwise they will overwrite each other.


text:
Q: Where can I show the hybrid app to my client? I wonder if it exists a way to show to my client how the app looks like.. I mean a simulator in cloud or something like that, i'm doing the app with ionic.
Thanks

A: So Ionic (2+) app can potentially "be" available:
Locally:

*

*via ionic serve (web app)

*via device run type commands (hybrid with access to plugins) on target platforms (iOS/Android)

Remotely:

*

*via Ionic Pro / Ionic View - (~web-app with limited plugins access) -
gets depreciated very soon

*via platforms relevant store's test solution: testflight (iOS)
or Google Play's beta testing (via Google dev console)

*via remote access to devices (like Firebase's test lab or AWS
device farm)

So in your case it really depends on your app:
if you are using native plugins the most accessible would probably be an option via Android devices as Google is much less restrictive towards sideloading of apps to their devices. This still may require additional steps from you clients (like following installation instructions). If you client is not tech savvy it is probably best to look into Google Play's beta testing program that they offer (via their console)
if you are not using any native plugins - then it is fairly easy to deploy your app as progressive web app (upload it to a hosting like firebase hosting) and provide access to it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Social Icons are broken I have a card, with social icons on it, and one is under the other.
i've tried inline-block, inline, etc all of that stuff.
It still won't fix, though.
Inline-flex works, but then it breaks the card.
Please help.
I'm sorry if the code is messy.
Here is my code.
If you need more code or whatever, here is the Website it is on.
Thank you.

.nyrisoc {
    position:relative;
    letter-spacing: 20px;
    top:270px;
    left:96px;
    margin:0px;

  }
  .cardtitle {
    position: relative;
    left: 55px;
    top: 12px;
    text-decoration: underline solid transparent;
    transition: text-decoration 1s ease;
    margin-right: 0 0 0;
    width: 245px;
  }

  .center2 {
    position: absolute;
    top: 70px;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .cardtitle:hover {
    text-decoration: underline solid Currentcolor;
    cursor: pointer;
  }
  .center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  #cardlink {
    text-decoration: underline solid transparent;
    transition: text-decoration 1s ease;
    cursor:pointer;
  }
  .carddis {
    position: relative;
    top: -68px;
    right: 60px;
    color: gray;
    font-size: 17px;
  }
  .stuffyes {
    position: relative;
    bottom:194px;
  }
  .cardinfo {
    position: relative;
    bottom: 70px;
    left: 70px;
  }
  .allcrds {
    display:inline-table;
    position:relative;
    bottom:-30px;
    right:160px;
  }
  .card {
    width:269px;
    background-color: rgb(44, 44, 44);
    height:330px;
    border-radius:30px;
    font-family:roboto;
    filter: drop-shadow(0 0 0.75rem black);
    position:relative;
    left:20px;
    bottom:90px;
    margin: 27px;
  }
  .cname {
    color:white;
    filter: drop-shadow(0 0 0.75rem black);
    opacity:100%;
    font-family:roboto;
    text-align:center;
    position:relative;
    top:180px;
  }
  .fab {
    color:white;
    cursor:pointer;
    transition: color 1s ease;
  }
  .fab:hover {
    color:gray;
  }
  #cardlink:hover {
    text-decoration: underline solid currentColor;
  }
  .socials {
    position:relative;
    text-align:center;
    top:230px;
    display:inline-flex;
    letter-spacing: 20px;
    left:72px;
    top:270px;
  }
  .desctx {
    color:rgb(196, 192, 192);
    filter: drop-shadow(0 0 0.75rem black);
    text-align:center;
    font-family:roboto;
    position:relative;
    top:305px;
  }
  .pfpy {
    filter: drop-shadow(0 0 0.75rem black);
    width:100px;
    height:100px;
    position:relative;
    border-radius:50px;
  }
<!DOCTYPE html>

        <title>Credits | Discord Noir</title>
        <link rel="stylesheet" type="text/css" href="src/css/main.css">
        <link rel="stylesheet" type="text/css" href="src/css/cred.css">

Discolored

Nyria

A: try this
.nyrisoc > * {
  width: 20px;
  display: inline-block;
  height: 65px;
}

A: I don't have access to your background, so it won't look quite right, but this should be good enough to send y'all in the right direction.
Items that are positioned relatively don't need to be manually set using top,bottom,left or right. Also the heirarchy of your elements should follow what you want to be seen on the screen. So if the image is at the top of the card, the element containing the image should be at the top of the card, not the bottom. I fixed some other stuff that should help it be a bit more responsive and user-friendly, a bit too much to list, but if you have any questions, let me know and I'm happy to help / answer.

.nyrisoc {
    position:relative;
    letter-spacing: 20px;
    /* top:270px; */
    /* left:96px; */
    margin:0px;
  }
  .cardtitle {
    position: relative;
    left: 55px;
    top: 12px;
    text-decoration: underline solid transparent;
    transition: text-decoration 1s ease;
    margin-right: 0 0 0;
    width: 245px;
  }

  .center2 {
    position: absolute;
    /* top: 70px; */
    /* left: 50%; */
    /* transform: translate(-50%, -50%); */
  }
  .cardtitle:hover {
    text-decoration: underline solid Currentcolor;
    cursor: pointer;
  }
  .center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  #cardlink {
    text-decoration: underline solid transparent;
    transition: text-decoration 1s ease;
    cursor:pointer;
  }
  .carddis {
    position: relative;
    top: -68px;
    right: 60px;
    color: gray;
    font-size: 17px;
  }
  .stuffyes {
    position: relative;
    /* bottom:194px; */
  }
  .cardinfo {
    position: relative;
    bottom: 70px;
    left: 70px;
  }
  .allcrds {
    /* display:inline-table; */
    position:relative;
    /* bottom:-30px; */
    /* right:160px; */
  }
  .card {
    width:269px;
    background-color: rgb(44, 44, 44);
    height:330px;
    border-radius:30px;
    font-family:roboto;
    filter: drop-shadow(0 0 0.75rem black);
    position:relative;
    /* left:20px; */
    /* bottom:90px; */
    /* margin: 27px; */
    display: inline-block;
    margin: 0px 15px 30px;
    padding: 15px 0 30px;
    vertical-align: top;
  }
  .cname {
    color:white;
    filter: drop-shadow(0 0 0.75rem black);
    opacity:100%;
    font-family:roboto;
    text-align:center;
    position:relative;
    /* top:180px; */
  }
  .fab {
    color:white;
    cursor:pointer;
    transition: color 1s ease;
  }
  .fab:hover {
    color:gray;
  }
  #cardlink:hover {
    text-decoration: underline solid currentColor;
  }
  .socials {
    position:relative;
    text-align:center;
    /* top:230px; */
    display: block;
    /* letter-spacing: 20px; */
    /* left:72px; */
    /* top:270px; */
  }
  .desctx {
    color:rgb(196, 192, 192);
    filter: drop-shadow(0 0 0.75rem black);
    text-align:center;
    font-family:roboto;
    position:relative;
    /* top:305px; */
    height: 70px;
  }
  .pfpy {
    filter: drop-shadow(0 0 0.75rem black);
    width:100px;
    height:100px;
    position:relative;
    border-radius:50px;
    margin: 30px auto 0;
    display: block;
  }
  .socials div{
  display:inline-block;
  margin:0 5px;
  }

Home

Credits

Discord

Theme Warnings
Settings Icons

Snapperito

Discolored

Nyria


text:
Q: Convert yaml to json without struct Services:
-   Orders:
    -   ID: $save ID1
        SupplierOrderCode: $SupplierOrderCode
    -   ID: $save ID2
        SupplierOrderCode: 111111

I want to convert this yaml string to json, cause the source data is dynamic, so I can't map it to a struct:
var body interface{}
err := yaml.Unmarshal([]byte(s), &body)

Then I want to convert that interface to json string again:
b, _ := json.Marshal(body)

But an error occur:
panic: json: unsupported type: map[interface {}]interface {}

A: Foreword: I optimized and improved the below solution, and released it as a library here: github.com/icza/dyno. The below convert() function is available as dyno.ConvertMapI2MapS().

The problem is that if you use the most generic interface{} type to unmarshal into, the default type used by the github.com/go-yaml/yaml package to unmarshal key-value pairs will be map[interface{}]interface{}.
First idea would be to use map[string]interface{}:
var body map[string]interface{}

But this attempt falls short if the depth of the yaml config is more than one, as this body map will contain additional maps whose type will again be map[interface{}]interface{}.
The problem is that the depth is unknown, and there may be other values than maps, so using map[string]map[string]interface{} is not good.
A viable approach is to let yaml unmarshal into a value of type interface{}, and go through the result recursively, and convert each encountered map[interface{}]interface{} to a map[string]interface{} value. Both maps and slices have to be handled.
Here's an example of this converter function:
func convert(i interface{}) interface{} {
    switch x := i.(type) {
    case map[interface{}]interface{}:
        m2 := map[string]interface{}{}
        for k, v := range x {
            m2[k.(string)] = convert(v)
        }
        return m2
    case []interface{}:
        for i, v := range x {
            x[i] = convert(v)
        }
    }
    return i
}

And using it:
func main() {
    fmt.Printf("Input: %s\n", s)
    var body interface{}
    if err := yaml.Unmarshal([]byte(s), &body); err != nil {
        panic(err)
    }

    body = convert(body)

    if b, err := json.Marshal(body); err != nil {
        panic(err)
    } else {
        fmt.Printf("Output: %s\n", b)
    }
}

const s = `Services:
-   Orders:
    -   ID: $save ID1
        SupplierOrderCode: $SupplierOrderCode
    -   ID: $save ID2
        SupplierOrderCode: 111111
`

Output:
Input: Services:
-   Orders:
    -   ID: $save ID1
        SupplierOrderCode: $SupplierOrderCode
    -   ID: $save ID2
        SupplierOrderCode: 111111

Output: {"Services":[{"Orders":[
    {"ID":"$save ID1","SupplierOrderCode":"$SupplierOrderCode"},
    {"ID":"$save ID2","SupplierOrderCode":111111}]}]}

One thing to note: by switching from yaml to JSON via Go maps you'll lose the order of the items, as elements (key-value pairs) in a Go map are not ordered. This may or may not be a problem.

A: http://sigs.k8s.io/yaml is "a wrapper around go-yaml designed to enable a better way of handling YAML when marshaling to and from structs". Among other things, it provides yaml.YAMLToJSON method that should do what you want.

A: I was having the same issue and the icza's answer helped me.
Additionally I improved the convert() function a little bit, so it visits existing map[string]interface{} nodes to search for inherited map[interface{}]interface{} nodes deep inside.
func convert(i interface{}) interface{} {
    switch x := i.(type) {
    case map[interface{}]interface{}:
        m2 := map[string]interface{}{}
        for k, v := range x {
            m2[k.(string)] = convert(v)
        }
        return m2
    case map[string]interface{}:
        m2 := map[string]interface{}{}
        for k, v := range x {
            m2[k] = convert(v)
        }
        return m2
    case []interface{}:
        for i, v := range x {
            x[i] = convert(v)
        }
    }
    return i
}


text:
Q: How to pass event change to parent from child component I tried to follow up "Capture references to elements" to pass change to parent from child component and it didn't work url is https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.0#capture-references-to-elements
Could please help me with?
a) anything wrong in code?
b) where I could find "Console.WriteLine" info since I could not find it from vs output window.
1. ParentComponent.razor

@page "/parentcomponent"
@using BlazorApp.Components

Parent Component

ParentYear: @ParentYear

<ChildComponent @ref="ChildComponent1" @bind-Year="ParentYear" />

@code {
    private int ParentYear = 1978;

    ChildComponent ChildComponent1 = new ChildComponent();

    protected override void OnInitialized()
    {
        ChildComponent1.YearChanged += ChildFiredEvent;
    }

    public void ChildFiredEvent(int _year)
    {
        ParentYear = _year;
        Console.WriteLine(ParentYear.ToString());
        StateHasChanged();
    }

}

2. Childcomponent.razor

Child Component

ChildYear: @Year

<button class="btn btn-primary" @onclick="ChangeTheYear">Change Year to 1986</button>

@code {
    [Parameter]
    public int Year { get; set; }

    [Parameter]
    public Action<int> YearChanged { get; set; }

    private void ChangeTheYear()
    {
        Year = 1986;
        YearChanged?.Invoke(Year);
    }
}

A: In the child component, the YearChanged declaration should look like this:
public EventCallBack<int> YearChanged { get; set; }

And then you invoke it like this:
await YearChanged.InvokeAsync(newValue);

A: Thank you so much, Samer and David. I believe that I used previous blazor methods. Now it works fine with @ref. Cheers!!! here is code.
@page "/parentcomponent"
@using BlazorApp.Components

Parent Component

ParentYear: @ParentYear

<ChildComponent @ref="ChildComponent1" @bind-Year="ParentYear" />

@code {
    private int ParentYear = 1978;

    ChildComponent ChildComponent1 = new ChildComponent();
}

ChildYear: @Year

<button class="btn btn-primary" @onclick="ChangeTheYear">Change Year to 1986</button>

@code {
    [Parameter]
    public int Year { get; set; }

    [Parameter]
    public Microsoft.AspNetCore.Components.EventCallback<int> YearChanged { get; set; }
    enter code here
    private void ChangeTheYear()
    {
        Year = 1986;
        YearChanged.InvokeAsync(Year);
    }
}


text:
Q: Get value from attribute I got a XML tree:
<?xml version="1.0"?>
<tree>
    <message name="login_form_empty">Vergeten in te vullen</message>
    <message name="signup_form_empty">Vergeten in te vullen</message>
    <message name="forgotpass_form_empty">Vergeten in te vullen</message>
</tree>

Is it possible to get the value from example: login_form_empty?
Thanks!

A: Use xPath to access the XML values. Something like this xPath statement should work:
//tree/message/@name

A: Certainly, use a XML->object converter like SimpleXML and use xPath to find the right elements.
<?php
$string = '<?xml version="1.0"?>
<tree>
    <message name="login_form_empty">Vergeten in te vullen</message>
    <message name="signup_form_empty">Vergeten in te vullen</message>
    <message name="forgotpass_form_empty">Vergeten in te vullen</message>
</tree>';

$xml = simplexml_load_string($string);
$login_form_empty = $xml->xpath('/tree/message[@name="login_form_empty"]');

foreach ($login_form_empty as $result) {
    echo $result;
}

?>


text:
Q: Firefox ctrl+1, ctrl+n to open tab from speed dial I'm trying to migrate from Opera to Firefox, and I've found several add-ons to make it happen, but there is still one thing missing. Opera had the speed dial, so anywhere I was, if I hit Ctrl+1, it opened Gmail (for me), and Ctrl+2, it opened Facebook, etc, in order how they were on my homepage. Anyone has an idea to make it happen? Thanks!

A: Solution
Firefox uses Ctrl+1 to 8 to select tab 1-8, and Ctrl+9 to select the last tab.
You can override the default behavior by using the Speed Dial add-on by Josep del Rio; just make sure to enable the Load in blank new tabs option. Check the official manual for further information and customization options.
Tested with Firefox 27.0.1.
References

*

*Keyboard shortcuts - Perform common Firefox tasks quickly

*How to use hotkeys to open speed dial websites in Firefox and Chrome [Guide]

A: First of all I'm not familiar with speeddial in opera, but if it is like the speeddial I know for firefox this might do the trick: https://addons.mozilla.org/en-US/firefox/addon/fvd-speed-dial/ (not to sure about the ctrl + {1,2,..} function)
Also you can add a keyword to a bookmark (say fb for facebook). Type this keyword in your addressbar and hit enter and firefox will open de link you connected.
I hope this helps you.


text:
Q: Calculate coordinates of third point on a triangle I have two points coordinates, A (x,y) and B (x,y) and a distance L, that distance is AC and BC, I don't have the distance for AB, and I have to find the coordinates for the point C

A: 1) From $A(x_A, y_A)$ and $B(x_B, y_B)$, find $x_M$ and $y_M$, where M is the midpoint of AB.

2) Find $m_{AB}$, the slope of AB. Hence, find $m_{MC}$, the slope of the line perpendicular to AB.
3) Use point-slope form to setup the equation of MC.
4) Set up the equation of the circle (centered at $A(x_A, y_A)$, radius = L).
5) The x-roots obtained by solving the above two equations are $x_{C}$ and $x_{C'}$. They happen to be the x-coordinates of $C$ and $C'$.


text:
Q: Saving a downloaded ZIP file w/Python I'm working on a script that will automatically update an installed version of Calibre.  Currently I have it downloading the latest portable version.  I seem to be having trouble saving the zipfile. Currently my code is:
import urllib2
import re
import zipfile

#tell the user what is happening
print("Calibre is Updating")

#download the page
url = urllib2.urlopen ( "http://sourceforge.net/projects/calibre/files" ).read()

#determin current version
result = re.search('title="/[0-9.]*/([a-zA-Z\-]*-[0-9\.]*)', url).groups()[0][:-1]

#download file
download = "http://status.calibre-ebook.com/dist/portable/" + result
urllib2.urlopen( download )

#save
output = open('install.zip', 'w')
output.write(zipfile.ZipFile("install.zip", ""))
output.close()

A: You don't need to use zipfile.ZipFile for this (and the way you're using it, as well as urllib2.urlopen, has problems as well). Instead, you need to save the urlopen result in a variable, then read it and write that output to a .zip file. Try this code:
#download file
download = "http://status.calibre-ebook.com/dist/portable/" + result
request = urllib2.urlopen( download )

#save
output = open("install.zip", "w")
output.write(request.read())
output.close()

A: There also can be a one-liner:
open('install.zip', 'wb').write(urllib.urlopen('http://status.calibre-ebook.com/dist/portable/' + result).read())

which doesn't have a good memory-efficiency, but still works.

A: If you just want to download a file from the net, you can use urllib.urlretrieve:

Copy a network object denoted by a URL to a local file ...

Example using requests instead of urllib2:
import requests, re, urllib

print("Calibre is updating...")
content = requests.get("http://sourceforge.net/projects/calibre/files").content

# determine current version
v = re.search('title="/[0-9.]*/([a-zA-Z\-]*-[0-9\.]*)', content).groups()[0][:-1]
download_url = "http://status.calibre-ebook.com/dist/portable/{0}".format(v)

print("Downloading {0}".format(download_url))
urllib.urlretrieve(download_url, 'install.zip')
# file should be downloaded at this point

A: have you tryed
output = open('install.zip', 'wb') // note the "b" flag which means "binary file"


text:
Q: Sequelize Query - Count associated tables and count all for pagination this is my first question on stackoverflow, never used it before but this issue is making me tear my hair out.
I'm building an infinite scroll component for a react app I'm working on a I'm trying to make a Postgres DB query work.
I have 2 tables - Challenges, and UserChallenges.
Challenges have many User Challenges.
I need to get a subsection of Challenges (from start to end) with each Challenge having a count of the number of "participants" (number of associated UserChallenges), and also a count of all challenges.
Something like this:
{
rows: [Challenge, Challenge, Challenge],
count: n
}

Where each challenge includes the total number of userChallenges as "participants" and count is a count of all challenges.
Here is the query:
let json_query = {
    attributes: {
        include: [[Sequelize.fn("COUNT", Sequelize.col("user_challenges.id")), "participants"]]
    },
    include: [{
        model: UserChallenge, attributes: []
    }],
    order: [['timestamp', 'DESC']],
    offset: start,
    limit: end
  }

The start and end quantities are the start and end of the pagination.
I'm running this query as follows:
var challengeInstances = await Challenge.findAndCountAll(json_query)

This results in the following error:
name: 'SequelizeDatabaseError',

parent: error: missing FROM-clause entry for table "user_challenges"

and this is the sql it's saying it's running:
`SELECT "challenge".* FROM (SELECT "challenge"."id", "challenge".*, COUNT("user_challenges"."id"), "challenge"."participants" FROM "challenges" AS "challenge" GROUP BY "challenge"."id" ORDER BY "challenge"."end_date" DESC LIMIT '4' OFFSET '0') AS "challenge" LEFT OUTER JOIN "user_challenges" AS "user_challenges" ON "challenge"."id" = "user_challenges"."challenge_id" ORDER BY "challenge"."end_date" DESC;`,

Sequelize or raw queries are both good.
Do let me know if you need any more information and thank you so so much.

A: you can use sequelize literal like this & remove object from attributes just paste this code for attributes .
attributes: [
    [
        sequelize.literal(`(
        SELECT COUNT(id)
            FROM user_challenges
        WHERE
            // your condition of foreign key like (user_challenges.participants_id = participants.id)
    )`),
        'numberOfParticipants'
    ]
]


text:
Q: Error `Archive not supported` while opening extracted .js file in 18.04 I am getting this message from Archive Manager when trying to open a text file:

Could not open "users.js"
  Archive type not supported.

I've tried different archive managers but not one works!
List of application I have in my machine to extract:

*

*Archive Mounter

*Xarchier (just downloaded but not working)

*Archive Manager (default one)

This is the output of file users.js -> users.js: ASCII text, with CRLF line terminators

A: Archive manager programs are not designed to open plain text files.
It seems there is a bug somewhere with file associations that I've also encountered in Ubuntu 20.04 where the system defaults to opening .js files with archive-manager


text:
Q: Trying to parse values out of a string using ttp in Python I am trying to parse out some values from the results of an easysnmp SNMP query but it is not working as expected.
The following results in an error:
from ttp import ttp
a = "<SNMPVariable value='1' (oid='enterprises.4998.1.1.20.2.33.1.5.16.86.17.126.66.140.34214089.5', oid_index='', snmp_type='INTEGER')>"
t = "<SNMPVariable value='{{value}}' (oid='{{oid}}', oid_index='{{oid_index}}', snmp_type='{{snmp_type}}')>"
p = ttp(a,t)
Traceback (most recent call last):
  File "C:\Users\me\AppData\Local\Programs\Python\Python37\lib\site-packages\ttp\ttp.py", line 1168, in parse_template_XML
    template_ET = ET.XML(template_text)
  File "C:\Users\me\AppData\Local\Programs\Python\Python37\lib\xml\etree\ElementTree.py", line 1315, in XML
    parser.feed(text)
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 32

If I remove the wedges from the string I do not get an error, but I don't get the values I'm looking for:
from ttp import ttp
a = "SNMPVariable value='1' (oid='enterprises.4998.1.1.20.2.33.1.5.16.86.17.126.66.140.34214089.5', oid_index='', snmp_type='INTEGER')"
t = "SNMPVariable value='{{value}}' (oid='{{oid}}', oid_index='{{oid_index}}', snmp_type='{{snmp_type}}')"
p = ttp(a,t)
p.parse()
p.result()
[[{}]]

What I expect to get for output is:
[[{'value':'1', 'oid':'enterprises.4998.1.1.20.2.33.1.5.16.86.17.126.66.140.34214089.5', 'oid_index'='', 'snmp_type': 'INTEGER'}]]

I know I'm overlooking something obvious, but I cannot figure it out. Any suggestions?

A: This would parse it properly:
from ttp import ttp
a = "SNMPVariable value='1'(oid='enterprises.4998.1.1.20.2.33.1.5.16.86.17.126.66.140.34214089.5', oid_index='', snmp_type='INTEGER')"
t = "SNMPVariable value='{{value}}' (oid='{{oid}}', oid_index='{{oid_index | re('.*')}}', snmp_type='{{snmp_type}}')"
p = ttp(a,t)
p.parse()
p.result()

Notice in your data oid_index='', TTP by default uses \S+ as a regex for variables, but \S+ would not match emtpy ''
Alternatively you can use this template:
t = "SNMPVariable value='{{value}}' (oid='{{oid}}', oid_index={{oid_index | strip("'")}}, snmp_type='{{snmp_type}}')"

In that case oid_index={{oid_index | strip("'")}} (no single quotes) will match on '' but strip("'") would remove them.
Both approaches produce same output:
[
    [
        {
            "oid": "enterprises.4998.1.1.20.2.33.1.5.16.86.17.126.66.140.34214089.5",
            "oid_index": "",
            "snmp_type": "INTEGER",
            "value": "1"
        }
    ]
]


text:
Q: Allow only numeric or decimal data in asp.net textbox I have a textbox in asp.net in which I want to enter only either numeric or decimal data. The user should not be allowed to even enter any other data. I have tried it myself using the following code. But it does not allow user to enter decimal point for decimal data.
<script language="JavaScript">
function onlyNumbers(evt)
{
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}
</script>

I had modified the code as below so that it allows the decimal point (period) (code=190)
if (charCode != 190)
{ ((charCode > 31 && (charCode < 48 || charCode > 57)))
 return false; }
 return true;

But it doesn't work as well (Here i used 190 for period as defined standard). Moreover If someone can help me limit this textbox for user to enter only 6 characters.Can anyone please correct me. I will be really thankful.
Note: I had also tried this. It also works only for numbers and also allows entering of non-numeric data but displays an error message if non-numeric data is entered. But its not what I want. I don't want user to even enter non-numeric data.
<asp:TextBox ID="txtBasicPay" runat="server" Height="15px" Width="120px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="txtBasicPay" runat="server" ErrorMessage="Only numbers allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>

A: You can use following as
In ASPX:
<asp:TextBox ID="txtBasicPay" runat="server" Height="15px" Width="120px" onkeypress="return isFloatNumber(this,event);"></asp:TextBox>

Javascript:
function isFloatNumber(e, t) {
   var n;
   var r;
   if (navigator.appName == "Microsoft Internet Explorer" || navigator.appName == "Netscape") {
      n = t.keyCode;
      r = 1;
      if (navigator.appName == "Netscape") {
         n = t.charCode;
         r = 0
      }
   } else {
      n = t.charCode;
      r = 0
   }
   if (r == 1) {
      if (!(n >= 48 && n <= 57 || n == 46)) {
         t.returnValue = false
      }
   } else {
      if (!(n >= 48 && n <= 57 || n == 0 || n == 46)) {
         t.preventDefault()
      }
   }
}

A: Your regex is incorrect , It should be ^\d+$ not \d+.
You might not have hooked up keyup event that is why above one is not working.
But regex will work alone.


text:
Q: React TypeScript: Correct type for useLocation() from react-router-dom I'm struggling to find the right type for this situation. This is a simplified version of redirecting after login. The following produces a compiler error:
Property 'from' does not exist on type '{} | { from: { pathname: string; }; }'.

Adding as any to the use of location.state fixes the compiler error but it's ugly and the linter complains.
import React from "react";
import { useLocation } from "react-router-dom";

const AuthLayer: React.FC = (props) => {
  const location = useLocation();

  const { from } = location.state || { from: { pathname: "/" } };

  return

;
};

export default AuthLayer;

A: You can create a particular type or interface to describe your location state and then use it when calling a useLocation hook:
import React from "react";
import { useLocation } from "react-router-dom";

interface LocationState {
  from: {
    pathname: string;
  };
}

const AuthLayer: React.FC = (props) => {
  const location = useLocation<LocationState>();

  const { from } = location.state || { from: { pathname: "/" } };

  return

;
};

export default AuthLayer;

A: This will be a little type-safe since it will return undefined if from is not in the object instead of throwing an error.
import React from "react";
import { useLocation } from "react-router-dom";

type LocationState = {
  from: {
    path: string;
  }
}

const AuthLayer: React.FC = (props) => {
  const location = useLocation();

  //
  const from = (location.state as LocationState)?.from;

  return

;
};

export default AuthLayer;

A: export interface LocationParams {
  pathname: string;
  state: your_state_data_type;
  search: string;
  hash: string;
  key: string;
}

//...
const location = useLocation<LocationParams>()

or create a generic that u can use any where
// types.ts
export interface LocationParams<Data> {
  pathname: string;
  state: Data;
  search: string;
  hash: string;
  key: string;
}

// App.tsx
import { LocationParams } from './types.ts'

// ...
const location = useLocation<LocationParams<your_data_here>>()

A: Type Assertion would work here.
import React from "react";
import { useLocation } from "react-router-dom";

type LocationState = {
  from: {
    path: string;
  }
}

const AuthLayer: React.FC = (props) => {
  const location = useLocation();

  const { from } = location.state as LocationState;

  return

;
};

export default AuthLayer;

Also, remember to define the type, as per your requirements.
For example, you might be using navigate(state.from).
For this Define the type as -
type LocationState = {
  from : string;
}

A: You can use Location from 'history'.
import React from "react";
import { Location } from "history";
import { useLocation } from "react-router-dom";

const AuthLayer: React.FC = (props) => {
  const location = useLocation<Location>();

  const { from } = location.state || { from: { pathname: "/" } };

  return

;
};

export default AuthLayer;

A: In react-router-dom version 6, it can be done like that
const locationState = useLocation().state as {id: string};

const id = locationState.id;

A: If you send only one thing, What about using useParams instead of useLocation?
function routeDetails(id: string) {
    history.push({
      pathname: `/details/${pathname}`,
    });
  }

const { id } = useParams<{ id: string }>();

You can use useParams simply.
It has key 'id' that is from history pathname.


text:
Q: 'Id' is required when binding to CosmosDB input I'm currently creating a C# function app on Azure, activated by a timer trigger and with a CosmosDB input. For this app the function.json is
{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *"
    },
    {
      "type": "documentDB",
      "name": "documents",
      "databaseName": "database",
      "collectionName": "collection",
      "connection": "hellocloud_DOCUMENTDB",
      "direction": "in"
    }
  ],
  "disabled": false
}

and the function code is the following one
#r "Microsoft.Azure.Documents.Client"

using System;
using Microsoft.Azure.Documents;
using System.Collections.Generic;

public static void Run(TimerInfo myTimer, IReadOnlyList<Document> documents,
    TraceWriter log)
{
  log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
  log.Info("Documents modified " + documents.Count);
}

If I save this code I receive this error from the console log
2018-03-14T10:31:36.739 [Info] Compilation succeeded.

2018-03-14T10:31:37.425 [Error] Microsoft.Azure.WebJobs.Host: Error indexing
 method 'Functions.HelloCloudFunction'.
 Microsoft.Azure.WebJobs.Extensions.DocumentDB: 'Id'
 is required when binding to a IReadOnlyList`1 property.

Using the id in the binding I haven't this error but I think there is something wrong because I would like to select the whole collection not a single document. Anyone can help?

A: It looks like IReadOnlyList is not supported. Change your function to
public static void Run(TimerInfo myTimer, IEnumerable<Document> documents,
    TraceWriter log)
{
  log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
  log.Info("Documents modified " + documents.Count());
}


text:
Q: Selenium web tests don't run as expected I have never looked into this before but have an existing project that I would like to run and then add som extra features to.
I have installed as follows:
-Eclipse Kepler
-Java JDK
-Maven 3.3.9
-Maven plugin in Eclipse
-Selenium IDE in Firefox
-Cucumberplugin in Eclipse
The "project" is successfully built running for example "Eclipse -> Run As-> Maven clean" or "cmd -> mvn validate".
I can run the "project" with for example "Eclipse -> Run As-> Maven test".
When I run the "project":
-The .java class enters the @Before method which opens my browser of selection according to the WebDriver used.
-The .java class enters the @Given method and opens the correct URL.
After this there are a lot of @When and @Then and more @Given, but these never seem to be executed. For example, the next thing that should happen is that some input should be made and a button being clicked but nothing happens. When I close the browser the Eclipse -> Console shows all the features in the .feature file (Test Project/src/test/resources/com/company/test) followed by the error below.
java.lang.NullPointerException
    at org.openqa.selenium.support.ui.ExpectedConditions.elementIfVisible(ExpectedConditions.java:227)
    at org.openqa.selenium.support.ui.ExpectedConditions.access$100(ExpectedConditions.java:39)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:130)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:126)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)
    at com.company.test.WebTestSteps.AssertExists(WebTestSteps.java:81)
    at com.company.test.WebTestSteps.I_should_be_on_the_page(WebTestSteps.java:180)
    at ?.Then I should be on the "Please login using your account information" page(com/company/test/OpenAllWindows.feature:6)

org.openqa.selenium.WebDriverException: chrome not reachable
  (Session info: chrome=53.0.2785.116)
  (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 103 milliseconds
Build info: version: '2.41.0', revision: '3192d8a6c4449dc285928ba024779344f5423c58', time: '2014-03-27 11:29:39'
System info: host: 'Hafjall', ip: '192.168.2.204', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\Users\User~1\AppData\Local\Temp\scoped_dir7884_25604}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=53.0.2785.116, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 37a0d1f5514c5f53158d6742152a5337
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:595)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:610)
    at org.openqa.selenium.remote.RemoteWebDriver.close(RemoteWebDriver.java:459)
    at com.company.test.WebTestSteps.tearDown(WebTestSteps.java:139)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:34)
    at cucumber.runtime.Timeout.timeout(Timeout.java:13)
    at cucumber.runtime.Utils.invoke(Utils.java:30)
    at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:59)
    at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:221)
    at cucumber.runtime.Runtime.runHooks(Runtime.java:209)
    at cucumber.runtime.Runtime.runAfterHooks(Runtime.java:203)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:50)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:83)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:89)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:40)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:94)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

Tests run: 496, Failures: 0, Errors: 3, Skipped: 492, Time elapsed: 34.881 sec <<< FAILURE!
Then I should be on the "Please login using your account information" page(Scenario: Test)  Time elapsed: 0.006 sec  <<< ERROR!
java.lang.NullPointerException
    at org.openqa.selenium.support.ui.ExpectedConditions.elementIfVisible(ExpectedConditions.java:227)
    at org.openqa.selenium.support.ui.ExpectedConditions.access$100(ExpectedConditions.java:39)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:130)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:126)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)
    at com.company.test.WebTestSteps.AssertExists(WebTestSteps.java:81)
    at com.company.test.WebTestSteps.I_should_be_on_the_page(WebTestSteps.java:180)
    at ?.Then I should be on the "Please login using your account information" page(com/company/test/OpenAllWindows.feature:6)

Scenario: Test  Time elapsed: 0.007 sec  <<< ERROR!
java.lang.NullPointerException
    at org.openqa.selenium.support.ui.ExpectedConditions.elementIfVisible(ExpectedConditions.java:227)
    at org.openqa.selenium.support.ui.ExpectedConditions.access$100(ExpectedConditions.java:39)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:130)
    at org.openqa.selenium.support.ui.ExpectedConditions$4.apply(ExpectedConditions.java:126)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)
    at com.company.test.WebTestSteps.AssertExists(WebTestSteps.java:81)
    at com.company.test.WebTestSteps.I_should_be_on_the_page(WebTestSteps.java:180)
    at ?.Then I should be on the "Please login using your account information" page(com/company/test/OpenAllWindows.feature:6)

Scenario: Test  Time elapsed: 0.244 sec  <<< ERROR!
org.openqa.selenium.WebDriverException: chrome not reachable
  (Session info: chrome=53.0.2785.116)
  (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 103 milliseconds
Build info: version: '2.41.0', revision: '3192d8a6c4449dc285928ba024779344f5423c58', time: '2014-03-27 11:29:39'
System info: host: 'Hafjall', ip: '192.168.2.204', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\Users\User~1\AppData\Local\Temp\scoped_dir7884_25604}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=53.0.2785.116, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 37a0d1f5514c5f53158d6742152a5337
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:595)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:610)
    at org.openqa.selenium.remote.RemoteWebDriver.close(RemoteWebDriver.java:459)
    at com.company.test.WebTestSteps.tearDown(WebTestSteps.java:139)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:34)
    at cucumber.runtime.Timeout.timeout(Timeout.java:13)
    at cucumber.runtime.Utils.invoke(Utils.java:30)
    at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:59)
    at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:221)
    at cucumber.runtime.Runtime.runHooks(Runtime.java:209)
    at cucumber.runtime.Runtime.runAfterHooks(Runtime.java:203)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:50)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:83)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:89)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:40)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:94)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

Results :

Tests in error:
  Then I should be on the "Please login using your account information" page(Scenario: Test)
  Scenario: Test
  Scenario: Test: chrome not reachable(..)

Tests run: 496, Failures: 0, Errors: 3, Skipped: 492

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 38.085 s
[INFO] Finished at: 2016-09-16T09:15:16+02:00
[INFO] Final Memory: 19M/250M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project WebTests: There are test failures.
[ERROR]
[ERROR] Please refer to E:\WebTest\target\surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException


text:
Q: Change the temp directory for a user with Microsoft Word 2000 I have a project with a very strange architecture: several Microsoft Word are creating documents based on copy/paste of Excel graphs.
Each Word is running with its specific account at the same time.
The problem is that the copy/paste produces tmp and *.wmf files in c:\winnt\temp for all accounts.
Is there a way to specify Word and Excel to always use the account's temp directory and not the global Winnt\Temp?

A: Can you check if the TEMP and TMP variable for each Windows User is not pointing to C:\Winnit\Temp? Many IT teams set it to a single location like C:\Windows\TEMP to make it easier for them to clean the folder as and when necessary. If it is so, then all you need to do is change that to the std temp folder location in userprofile.


text:
Q: Unable to find a specification for `Google Places` I'm trying to add Google Places SDK to my xcode project but keep getting the error
Unable to find a specification for `GooglePlacePicker`

This is my pod file
# Uncomment the next line to define a global platform for your project
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'

target 'Restaurant' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for Restaurant
 pod 'GooglePlaces'
 pod 'GooglePlacePicker'
 pod 'GoogleMaps'

  target 'RestaurantTests' do
    inherit! :search_paths
    # Pods for testing

  end

  target 'RestaurantUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

The funny thing is, if I remove 'GooglePlaces' and 'GooglePlacePicker' it installs the 'GoogleMaps' perfectly fine.


text:
Q: How to call a stored proc using a generic DB connection in C#? I have to call stored procs in C# (.Net 2.0) sometimes using an ODBC connection, sometime with SQLClient. I the future we could have to communicate with Oracle as well.
My stored procedures have input/output parameters and a return value.
CREATE PROCEDURE myProc (@MyInputArg varchar(10), @MyOutputArg varchar(20) output) AS (...) return @@ERROR

My problem is I can't find a way to store a command which could be generic whatever the client. I'm using an IDbCommand object.
With an ODBC connection I must define:
objCmd.CommandText = "? = CALL myProc (?,?)";

In an SQLclient context:
objCmd.CommandText = "myProc";

I do not really want to parse my command, I'm sure there is a better way to have a generic one!
In order to help people to reproduce, you can find below how I made the generic DB connection. In my context, the provider object is defined from a configuration file.
// My DB connection string, init is done from a configuration file
string myConnectionStr = "";

// Provider which defined the connection type, init from config file
//object objProvider = new OdbcConnection(); //ODBC
object objProvider = new SqlConnection(); // SQLClient

// My query -- must be adapted switch ODBC or SQLClient -- that's my problem!
//string myQuery = "? = CALL myProc (?,?)"; // ODBC
string myQuery = "myProc"; // SQLClient

// Prepare the connection
using (IDbConnection conn = (IDbConnection)Activator.CreateInstance(typeof(objProvider), myConnectionStr ))
{
    // Command creation
    IDbCommand objCmd = (IDbCommand)Activator.CreateInstance(typeof(objProvider));
    objCmd.Connection = conn;

    // Define the command
    objCmd.CommandType = CommandType.StoredProcedure;
    objCmd.CommandTimeout = 30;
    objCmd.CommandText = myQuery;

    IDbDataParameter param;

    // Return value
    param = (IDbDataParameter)Activator.CreateInstance(typeof(objProvider));
    param.ParameterName = "RETURN_VALUE";
    param.DbType = DbType.Int32;
    param.Direction = ParameterDirection.ReturnValue;
    objCmd.Parameters.Add(param);

    // Param 1 (input)
    param = (IDbDataParameter)Activator.CreateInstance(typeof(objProvider));
    param.ParameterName = "@MyInputArg";
    param.DbType = DbType.AnsiString;
    param.Size = 10;
    param.Direction = ParameterDirection.Input;
    param.Value = "myInputValue";
    objCmd.Parameters.Add(param);

    // Param 2 (output)
    param = (IDbDataParameter)Activator.CreateInstance(typeof(objProvider));
    param.ParameterName = "@MyOutputArg";
    param.DbType = DbType.AnsiString;
    param.Size = 20;
    param.Direction = ParameterDirection.Output;
    objCmd.Parameters.Add(param);

    // Open and execute the command
    objCmd.Connection.Open();
    objCmd.ExecuteReader(CommandBehavior.SingleResult);
    (...) // Treatment
}

Thanks for your time.
Regards,
Thibaut.

A: You could create a wrapper around IDbCommand and implementations (but only if you want to :) ).
//Note the IDisposable interface
public class MultiSqlCommand : IDisposable
{
  //DbConnectionType  is a custom enum
  public MultiSqlCommand(DbConnectionType connType, DbConnection conn)
  {
    //initialize members
    ...
    switch(connType)
    {
      case ADO:
        _cmd = new SqlCommand(_connection);
        break;
      case ODBC:
        ...
    }
  }

  //As param name you pass the undecorated parameter name (no @, ?, etc.)
  public void AddParameter(string strippedName, object value)
  {
    //this should be an internal function which gives you an SqlParameter formatted for your specific DbConnectionType
    object parameter = GetSqlParam(strippedName, value);
    _cmd.Parameters.Add(object);
  }
}

After adding parameters you have your command ready for execution. You can either expose it through a property and execute it outside of this class or extend the API and add a few methods to execute it and get results. Whatever you find convenient.
Note: In your IDisposable implementation you should dispose the IDbCommand instance (if not null). This is very important, otherwise you'll leak memory.
If the suggestion is not clear, then let me know and I'll try to fill it up with more details.
The solution is simple, I would say. You could go further and create an abstraction layer on top of the entire ADO.NET commands and parameters support, but I don't think is really necessary here. It's not like you're not writing an entire data provider.


text:
Q: Pulled a Joomla site from live to local, getting 404 - Component not found Joomla is up to date. I downloaded a live site to set up locally. I am completely new to Joomla! but i have a lot of experience in wordpress. So i changed the redirect links so the local site would stop redirecting to live. However now i'm getting:
You may not be able to visit this page because of:
an out-of-date bookmark/favourite
a search engine that has an out-of-date listing for this site
a mistyped address
you have no access to this page
The requested resource was not found.
An error has occurred while processing your request.
Please try one of the following pages:
Home Page
If difficulties persist, please contact the System Administrator of this site and report the error below..
I have tried turning SEF off, is there any other solutions to fix this?
Cheers
Edit:
Stack trace:
Component not found.
Call stack
Function    Location
1   JApplicationCms->execute()  C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www\celtic\index.php:53
2   JApplicationSite->doExecute()   C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www\celtic\libraries\cms\application\cms.php:261
3   JApplicationSite->dispatch()    C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www\celtic\libraries\cms\application\site.php:229
4   JComponentHelper::renderComponent() C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www\celtic\libraries\cms\application\site.php:190


text:
Q: Apache HttpClient, form-based login, Doesn´t retrieve HTML content I am using Httpclient from apache to access another page behind form-based login authentication, but, I am receiving the same form-based login page as a result.
Should I do somenthing different?
public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://localhost/salvaurls/");

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(4);
    params.add(new BasicNameValuePair("return_url", "http://localhost/salvaurls/painel.php"));
    params.add(new BasicNameValuePair("action", "http://localhost/salvaurls/autenticacao.php?acao=login"));
    params.add(new BasicNameValuePair("login", "desenvolvimento@gmail.com.br"));
    params.add(new BasicNameValuePair("senha", "123"));
    UrlEncodedFormEntity entity_ = new UrlEncodedFormEntity(params, Consts.UTF_8);
    httppost.setEntity(entity_);

    //Execute and get the response.
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        try (InputStream is = entity.getContent()) {
            System.out.println("entrou");
            Thread.sleep(2000);

            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str ="";
            while ((str = br.readLine()) != null){
                System.out.println(""+str);
            }
        }
    }
}

index.html - login form that is displayed after run the code:

login Form

Salva URLs

Please enter your email and password

                <form id="Login" action="autenticacao.php?acao=login" method="post">

                        <input type="email" class="form-control" id="login" name="login"
                            placeholder="Email Address">

                        <input type="password" class="form-control" id="senha" name="senha"
                            placeholder="Password">

                        Forgot password?

                    <button type="submit" class="btn btn-primary">Login</button>
                </form>

A: You are not calling the login url at all. Change the HttpPost url to http://localhost/salvaurls/autenticacao.php?acao=login and remove the action parameter from the list.
HttpPost httppost = new HttpPost("http://localhost/salvaurls/autenticacao.php?acao=login");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("return_url", "http://localhost/salvaurls/painel.php"));
params.add(new BasicNameValuePair("login", "desenvolvimento@gmail.com.br"));
params.add(new BasicNameValuePair("senha", "123"));

Normally the server sends a cookie if you had authenticated successfully. For further requests you may need a cookie store.
CookieStore cookieStore = new BasicCookieStore();
HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
HttpClient client = HttpClients.createDefault();

HttpPost httppost = new HttpPost("http://localhost/salvaurls/autenticacao.php?acao=login");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("return_url", "http://localhost/salvaurls/painel.php"));
params.add(new BasicNameValuePair("login", "desenvolvimento@gmail.com.br"));
params.add(new BasicNameValuePair("senha", "123"));
UrlEncodedFormEntity entity_ = new UrlEncodedFormEntity(params, Consts.UTF_8);
httppost.setEntity(entity_);

HttpResponse response = client.execute(httppost, context);
String response = EntityUtils.toString(response.getEntity());

If you are doing further authenticated requests you need to use the HttpClientContext with the cookie store every time. Hope that helps.


text:
Q: how to statically obtain filename and line numbers that lead to a variable setting in C? I have a large software system written in C. I have all the sources. I am trying to find a tool that can help me determine (preferably via static analysis) the functions and line numbers that can set a variable that is of interest to me. Example:
void func_a(int q) {
   int z;
   ...
   z = q*2;
   ....
   func_b(z);   //  I NEED TO FIND OUT ALL LINES in ALL FILES that can set "z"
}

int main(int argc, char *argv[]) {
     int x;
     ...
     x = 38;
     ...
     func_a(x);
}

I would like to be told:
main()   x = 38;
func_a(x);
void func_a(int q);
func_a() z = q*2;

Above 4 lines determine value of z that I am about to send to func_b().
I have examined clang, gtags (with --idutils), and some others. I can not determine if this is something that is supported. Naturally main() and func_a() can be in different .c files and have lots of other lines unrelated to my variable of interest (its a large software system.)
Any hints appreciated.

A:
I have a large software system written in C. I have all the sources. I am trying to find a tool that can help me determine (preferably via static analysis) the functions and line numbers that can set a variable that is of interest to me.

This problem is unsolvable. See Rice's theorem
The intuition is that if you have some automatic variable x, you could pass its address &x elsewhere, and arbitrarily. You'll have complex pointer aliasing.
However, you could consider using Frama-C (with manually added annotations in ACSL) or Clang static analyzers, and debuggers. Notice that GDB provide watchpoints.
If your C compiler is a recent GCC, you might code your own GCC plugin to help you (and analyze the GIMPLE representation of your program). Expect a few weeks or months of work. With old versions of GCC, the unmaintained GCC MELT (which I wrote) might be useful.


text:
Q: Using regex to detect words that might have an apostrophe, encoded in ASCII? Working in Python, I'm trying to create a function that takes in a stock ticker as a string and returns the company name using html data scraped from Yahoo! Finance. I've got it working for all companies except one that contains an apostrophe. I inspected the html code and found that the apostrophe is encoded as such - I'm pretty sure it's encoded in ASCII. Here's a modified version of the html code:
 html = '<!DOCTYPE html><html id="atomic" class="NoJs featurephone" lang="en-US"><head prefix="og: http://ogp.me/ns#"><script>window.performance && window.performance.mark && window.performance.mark(\'PageStart\');</script><meta charset="utf-8"/><title>Dick's Inc (DKS) Company Profile & Facts'

What I would want to return is "Dick's". What I'm getting back is just "Dick". I'm using the re module and re.search. Here's my code:
 company_name = (re.search(r'(?<=</script><meta charset="utf-8"/><title>)\w+', html).group(0))

I've tried to include the apostrophe to make sure it doesn't stop there, but since that's not part of the html code, it doesn't find it anywhere. Should I be using something other than re.search? I've looked into re.findall but that wouldn't be solving my problem of finding and including the "'" but presented as an apostrophe.

A: Sure you don't want Dick's, Inc (DKS) or something more? Just wonder if you're getting the full names as expected. To get Dick's, you'll need to unescape your HTML then change your regex. The new one will look for one or more word characters or apostrophes in sequence.
import html

html_string = '<!DOCTYPE html><html id="atomic" class="NoJs featurephone" lang="en-US"><head prefix="og: http://ogp.me/ns#"><script>window.performance && window.performance.mark && window.performance.mark(\'PageStart\');</script><meta charset="utf-8"/><title>Dick's Inc (DKS) Company Profile & Facts'
html_string = html.unescape(html_string)
company_name = (re.search(r'(?<=</script><meta charset="utf-8"/><title>)[\w\']+', html_string).group(0))

Result:
"Dick's"


text:
Q: USB Host controller: xhci-hcd Event TRB with no TDs queued spam during audio playback I'm on a system with Linux Kernel v5.10.4, and facing an issue where during audio playback through ALSA (aplay). The kernel spams the following log for the duration of the playback and no audio is heard:
xhci-hcd f2500000.usb3: WARN Event TRB for slot 3 ep 1 with no TDs queued?
xhci-hcd f2500000.usb3: WARN Event TRB for slot 3 ep 1 with no TDs queued?
xhci-hcd f2500000.usb3: WARN Event TRB for slot 3 ep 1 with no TDs queued?
...

*

*I've tried resetting (power off/on) the USB audio card, but the xhci-hcd is in the same error state.

*The issue resolves if I reset the USB hub.

*The issue resolves if I reboot the system.

*I'm able to reproduce the issue by doing speaker-test for more than 4 periods. The issue doesn't occur with shorter periods.

I do not know how to troubleshoot whether this is a driver issue or a hardware issue.

*

*Do I need a xhci driver update to fix the issue?

*Any mitigation to restart / recover the driver (without rebooting or resetting the entire USB hub)?

Warn log in source driver v5.10.4
snd-usb-audio is present in the kernel.
Found a related post but the mentioned fix was done in kernel v4.15

A: Have you tried changing the sample rate of the file you're playing?


text:
Q: USB backlit keyboard power consumption Does someone know the power consumption of an USB backlit keyboard like the SteelSeries Apex? I'd like to connect it to a Keyboard/Mouse USB Switch that goes to PC by one USB 2.0 cable. The mouse I'm going to use is the SteelSeries Rival. Do I risk to "break" the USB port?
I tried googling, but I haven't found any power consumption specification.

Edit 1:
Do you think that with the 500 mA of the USB 2.0 I will be able to "feed" the keyboard and the mouse? In case, if I plug the USB 2.0 switch to an USB 3.0 port, is it able to draw 900 mA? (My USB hub is powered by just the PC's USB port)

Edit 2:
The keyboard has a USB Y cable, but the producer doesn't say if it's necessary to the keyboard alimentation, or if it's eventually necessary to the keyboard's USB hub(it has a 2 port USB 2.0 hub)

Edit 3:
I've finally found something about backlit keyboard power consumptions: http://www.ctielectronics.com/pdf/811675-Industrial-Keyboard-Backlight-Instensity-Adjustment.pdf
"Power requirements for the backlit keyboard are less than 100mA @ 5VDC (typical), and all power required for backlighting is taken from the keyboard port of the Host PC": even if the one referred by the link is smaller than the one(so less LEDs) I specified I think that I should be able to feed keyboard and mouse with less than 500mA

Edit 4:
I have received the objects, plugged them to the hub and they work correctly.

A: Measure it yourself! USB ammeters are useful little tools.
"Charger Doctor" is one brand of USB ammeter, targeted at seeing how much power a USB charger is actually supplying, but it works on any USB device. However, be aware that it's not the most precise ammeter, it will read zero for very low power devices, such as keyboards. (With my plain keyboard, it reads zero, even when actively typing.)

https://www.google.com/search?q=Charger+Doctor
http://www.amazon.com/dp/B00GC9I61I

A: The power consumption is negligible, less than the 500 mA  which is where USB 2 is rated. As a comparison, your keyboard probably uses some blue LEDs, they are not going to draw more than 80 mA each, and more likely to draw somewhere between 20 and 40.
If your USB hub is powered, then the keyboard is not going to draw any power from your PC. USB keyboards and mice are made for USB, and they do not usually break anything.

A: USB devices start out as "low powered" (drawing a maximum of one unit load of power, which is 100 mA in USB 2.0, see 7.2.1 Classes of Devices, page 171), and can negotiate "high power" mode in which the device can draw up to 500 mA in plain USB 2.0. At USB's 5 V DC, 500 mA provides 2.5 W of power, plus or minus tolerances.
The operative word here is negotiate. The host is fully within its rights to refuse a USB device switching to high power mode if such amounts of power are not available for any reason, and the device must deal gracefully with failure to switch to high power mode. Likely, it will appear as though it is shut down if the negotiation to high power fails, or in the case of a backlit keyboard the keyboard might work but the backlight might remain turned off if sufficient power for that feature is not available.
As has been pointed out by arch-abit, the power consumption of the keyboard (or even the keyboard and mouse combined) is likely to be significantly lower than the 2.5 W allowed for by USB. Based on Journeyman Geek's back-of-the-envelope calculations in another answer to this question, depending on the specific LEDs used and their light output, it might quite possibly fit well inside the 0.5 W (100 mA) allowed for by the initial low power mode. LEDs are very power-efficient; a few watts into a LED lightbulb is enough to provide general lighting for a small room, so a keyboard certainly shouldn't need more than a few hundred milliwatts (a few tenths of a watt) for its background illumination, and quite possibly significantly less than that. After all, we are talking about background illumination to help you see the letters printed on the keys in otherwise dark conditions, not general illumination.
If all devices involved are USB 2.0 certified and can be used without weird constructs like USB Y cables for power, you likely don't need to worry at all. If the switch has an external power supply (functions as a powered USB hub) then you almost certainly don't need to worry. The worst that is likely to happen is that something won't function, or will function only erratically (depending on the instantaneous power-up ordering, for example).

A: Why not check yourself? Many computer motherboards are able to tell you the power consumption of a usb port via the control panel.
Go into the control panel, system > device manager and find the USB port or hub in question in the list. You'll then see power consumption figures like this:

A: I don't have the power consumption figures, but the keyboard is USB certified which means it will only draw what its allowed to draw.  So there is no risk of 'breaking' the port.
You 'could' run into issues with portable/travel switches that don't have external power, but not you wont damage things.

A: A bit of back of the envelope calculations, and common sense might help here.
From a little research the LEDs on a keyboard are similar to these flangeless 3mm leds. Based off the specifications there - it would be 3.5V at 20ma, o7 or ~7mW per key. Assuming a 101 key keyboard its 700mW for the leds alone. Considering USB 2.0 does up to 2.5 amps, You should have quite a bit of headroom

A: I am going to go by memory over here.
From what I can remember, the average USB keyboard should require approximately 120 ma to about 140 ma.  This is with the standard 3 LED's (Cap Lock, Scroll Lock, and Num Lock) lit up. These LEDs require very little power since they are only simple indicators.
The lit keyboards have various designs depending on the manufacture for the lighting technique. They use a number of LEDs placed around under the transparent keys. The LED light is spread by using various optical design technics. The total power consumption in these types of keyboards can approach 160 ma to 200 ma depending on the design.
A USB optical mouse can require about 80 ma to 100 ma when there is mouse activity. The small defused laser LED and imaging device on the underside can require about 30 ma alone.
The cordless mouse and keyboard adapter that works on the USB port can require about 30 ma to maybe 50 ma.
A USB2 port can safely provide up to 500 ma at its limit range. A USB3 port can safely provide up to 900 ma by specs.
The old PS2 keyboards from the late 1970 to about 2000 before USB was popular can require in to the range of 150 ma.

A:
Do I risk to "break" the USB port? I tried googling, but I haven't
  found any power consumption specification.

(As usual, the problem with the answers here is that they provide silly textbook answers while ignoring hard realities...)
If you always believe what you read, then the USB spec says you're fine and that no device will ever exceed or 'overload' the board, however, reality...

However, there are a few problems with this.
I looked a bit into the spec and market reality a mess. 100mA is
  supposed to be always required initially (which might explain a lot of
  '100mA' on device managers) but then after that initial negation a
  device is free to ask up to 500mA. Now whether that is truly what is
  drawn or if the OS accurately reports that or waits for the device for
  confirmation of a new current I do not know.
What is certain is that there's tons of dodgy implementation in the
  market; devices drawing tons of power above that specified and the
  icing: "Devices" that aren't even negotiating anything electronically;
  just drawing current, like lamps and fans and vacuum cleaners (yes).
What's interesting is that it appears there's is little control - at
  least proactively - by the host bus: Devices can usually pump whatever
  they want without negotiating it.
It appears what made it worse was the requirement of the bus to act as
  a charger supply so lots of devices (manufacturers) would whine that
  there's too much work needed before they are able to pump the juice.
  So there appears to be little future for restricting it, more likely
  is the opposite, to give even more freedom to chargers.
tl;dr: have a powered hub ready if you suspect power issues, USB spec
  itself won't easily protect you.

(source: https://geekhack.org/index.php?topic=44092.0  ...only because it says it better and more succintly than I could myself)
So, here is my advice, if you have an older computer, one built with cheaper components (or a cheaper off brand keyboard) and there is any question in your mind that your computer "may not be able to handle it" then you should look into buying a separate usb hub which is externally and separately powered. (not a y connector)
Even if, the usb is correctly implemented and there is no danger from overload, if you know that you like to have many usb devices plugged in at once, it is a good idea to buy a powered usb hub since Without the external power source, you might get a "USB Power limit exceeded" warning on your computer. (again, I'm not going to argue maths, because it won't help you, how often have I made the mistake of trusting what I read, only to find this or that exception the rule, too many.)
(sadly, there are risks with this solution because of some lazy motherboard manufacturers, you may or may not have issues recognizing the hub at startup)


text:
Q: Store All Input Data Acrobat Form I have an Acrobat form for work that our salesmen use to create proposals for jobs and their corresponding estimates.
The problem I am facing is that the form only stores data for one customer at a time. I am trying to get it to where they can type in a customers name (or job number, etc.) and it pull up all the form data used for that customer when that exact estimate was done (no matter how long ago it was).
How can I get my PDF form to do this (save current and all previous inputs) and not just save the current data in each editable field at a time?
I currently use Omniform and it does all of this; however, we are trying to switch over to Adobe and I am not too familiar with the software and how I can accomplish this!
Thank you in advance!

A: If you want to do all the processing local (without server roundtrip) you would have to embed all data in the PDF itself. There are several ways to do this but I would recommend using JavaScript. You would declare this at the document level. You would handle the blur event of the customer name (or other key field), find a match among the multiple customers and populate the secondary fields.
Assuming the data sits somewhere in a database, you would have to generate such a PDF or manipulate an existing template programmatically using a library. Not sure if you are looking to a programming solution or a tool.
Here is more info on JavaScript for Acrobat:
http://www.adobe.com/devnet/acrobat/javascript.html


text:
Q: What type of join do I need to use in the below sql query to retrieve the correct results? I want to return the appropriate information about a user from three different tables in my database using SQL joins and a group concat function. Which joins are appropriate for what I am trying to achieve?
I have three tables I want to use in the table:
users
user_events
Events
Current SQL code:
SELECT users.username, users.user_firstname, users.user_lastname,
       users.user_role, user_events.Event_ID
FROM users
LEFT JOIN user_events ON users.id = user_events.id

This returns all users, there details and the ID of the event they have signed up to, but this event id is duplicated if they've signed up to one or more.
If I update my query to the below how would I join on the Events table to get the event name?
SELECT users.username, users.user_firstname, users.user_lastname,
       users.user_role,
       GROUP_CONCAT(Events.Event_Name) AS Event_Names
FROM users
LEFT JOIN user_events ON users.id = user_events.id

My output from the first query is as follows:
| username    | user_firstname | user_lastname | user_role | event_id.
| M@gmail.com | jo             | mccann        | employee  | 8
| M@gmail.com | jo             | mccann        | employee  | 15

Expected output:
| username    | user_firstname | user_lastname | user_role | Event_Name
| M@gmail.com | jo             | mccann        | employee  | baking,run

A: Just add one more outer join & do aggregation :
SELECT users.username, users.user_firstname, users.user_lastname,
       users.user_role,
       GROUP_CONCAT(Events.Event_Name) AS Event_Names,
       COUNT(Events.Event_Name) AS Event_count
FROM users LEFT JOIN
     user_events
     ON users.id = user_events.id LEFT JOIN
     Events
     ON Events.id = user_events.event_id
GROUP BY users.username, users.user_firstname, users.user_lastname, users.user_role;

Use DISTINCT inside COUNT() in case of any duplicate events.

A: SELECT users.username, users.user_firstname, users.user_lastname,
       users.user_role,
       GROUP_CONCAT(ev.Event_Name) AS Event_Names
FROM users
LEFT JOIN user_events ON users.id = user_events.id
JOIN events ev ON ev.event_id = user_events.event_id


text:
Q: K8s OPA Gatekeeper doesn't block DELETE operation I'm using K8s OPA to enforce policies.
From the official document debugging section (https://open-policy-agent.github.io/gatekeeper/website/docs/debug), I created constraintTemplate as below.
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8sdenyall
spec:
  crd:
    spec:
      names:
        kind: K8sDenyAll
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sdenyall

        violation[{"msg": msg}] {
          msg := sprintf("REVIEW OBJECT: %v", [input.review])
        }

I also created the constraint below.
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDenyAll
metadata:
  name: deny-all-namespaces
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Namespace"]

I thought that every operations regarding namespace would be denied. However, whereas kubectl create ns test1 is denied successfully, kubectl delete ns test2 isn't denied. Any ideas on why? I'm experiencing this issue not only with namespace, but with other k8s resources such as pods.

A: Sounds like you need to Enable Validation of Delete Operations?

To enable Delete operations for the validation.gatekeeper.sh admission webhook, add "DELETE" to the list of operations in the gatekeeper-validating-webhook-configuration ValidatingWebhookConfiguration [..]

operations:
  - CREATE
  - UPDATE
  - DELETE

You can now check for deletes.


text:
Q: Update state if response is ok So I have kind of a different problem here. My react app has a reducer that updates the state of a cart when a product is added. As i works right now i send this updated state to an API endpoint so save it to the database.
  const addToCart = (item, quantity = 1) => {
    dispatch({
      type: 'ADD_ITEM',
      payload: { item: item, quantity: quantity },
    });
  };

My api endpoint is called by a useEffect on this function.
  useEffect(() => {
    updateCart(state);
  }, [removeFromCart, addToCart]);

So basically what I am doing is that I send the state to the db for removing and adding items to cart. But this comes with a problem. If a user adds many items to cart very rapidly the state and what is saved inn the database is out of sync.
Then I was thinking to revert the state if the response is not ok from the API endpoint. But a little unsure on how to do this. Anybody have any tips on how to solve this problem?

A: You should debounce the call to updateCart.
There's a lot of ways to implement a debounce on the useEffect. You can either use a library that already implements that hook or create a hook and manage the debounce yourself.
To get an overall ideia of what is debounce, you can look at this question.
To understand how it works with react and useEffect, you can look at this question
A simple way is just using useDebounce from react-use and do:
useDebounce(() => {
  updateCart(state);
}, 1000, [removeFromCart, addToCart])

Where 1000 is the time for the debounce.
This way you remove the problem of having the user add and remove a lot of items and having the db out of sync and there's no need to check if the response is ok from the server.


text:
Q: How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?I tried the already available answers How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?Im using selenium 4.0.How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

A: check webelement class to know available methods:
in java:
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebElement.html
   WebDriver driver = new ChromeDriver();
   driver.get("https://stackoverflow.com/questions/66021499/how-to-capture-the-screenshot-of-a-specific-element-rather-than-entire-page-usin?noredirect=1#comment116730378_66021499");
   WebElement element = driver.findElement(By.cssSelector("#submit-button"));
   JavascriptExecutor js = (JavascriptExecutor) driver;

   File a = new File("a.png");
   js.executeScript("arguments[0].scrollIntoView()",element);
   File b = element.getScreenshotAs(OutputType.FILE);
   FileUtils.copyFile(b, a);

in python :
https://www.selenium.dev/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webelement.html
element.screenshot(filename)


text:
Q: CALayer mask Layer animating I want to mask CALayer with another layer whose frame I want to keep changing in every draw call thereby animating. Is it possible to do change the frame of mask layer in every draw call rather than making a new mask layer?

A: Try the following code. This code will run on Cocoa App for macOS. Kindly change the classes accordingly if you are going for Cocoa Touch for iOS. I hope this works for you.
//  ViewController.h
import
@interface ViewController : NSViewController{
CALayer * maskLayer;
CALayer * Layer;

}
//  ViewController.m
@implementation ViewController
-(void)viewDidLoad{
[super viewDidLoad];

maskLayer = [CALayer layer];
Layer = [CALayer layer];

Layer.backgroundColor = [[NSColor blueColor] CGColor];
Layer.frame = CGRectMake(20, 20, 720, 900);
Layer.contents = [NSImage imageNamed:@"bg1"];

maskLayer.frame = CGRectMake(20, 20, 720, 900);
maskLayer.opacity = 0.5;
[maskLayer mask];

maskLayer.contents = [NSImage imageNamed:@"bg"];

[self.view.layer addSublayer:Layer];
[self.view.layer addSublayer:maskLayer];

[self maskLayerAnimation];

}
-(void)maskLayerAnimation{
[CATransaction begin];
CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnim.fromValue = [NSNumber numberWithFloat:1.0];
fadeAnim.toValue = [NSNumber numberWithFloat:0.0];
fadeAnim.duration = 5.0;

[CATransaction setCompletionBlock:^{
    NSLog(@"animation completed");
    maskLayer.frame = CGRectMake(20, 20, 720, 700);
    maskLayer.contents = [NSImage imageNamed:@"bg2"];
}];;

[maskLayer addAnimation:fadeAnim forKey:@"opacity"];
[CATransaction commit];

}


text:
Q: ASP.Net AJAX UpdatePanel not working with Repeater and RadioButtons I have a repeater which includes a radio button in each item, and the whole thing sites inside an update panel.  When I select a radio button the whole page reloads.  Why is it not just updating the update panel.  I've reduced this to a pretty simple example to avoid clutter.  Code here...
ASPX...

<asp:ScriptManager ID="SM1" runat="server" />
<asp:UpdatePanel ID="up1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Repeater runat="server" ID="history">
            <ItemTemplate>
                <asp:RadioButton runat="server" ID="radioButton" AutoPostBack="true" GroupName="HistoryGroup" OnCheckedChanged="RadioButton_CheckChanged" />

            </ItemTemplate>
        </asp:Repeater>

<asp:Literal runat="server" ID="output" />

    </ContentTemplate>
</asp:UpdatePanel>

Code...
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < 20; i++)
                list.Add(i);
            history.DataSource = list.ToArray();
            history.DataBind();
        }
    }

    protected void RadioButton_CheckChanged(Object sender, EventArgs e)
    {
        output.Text = DateTime.Now.ToString();
    }
}

A: Setting ClientIDMode=Auto on the RadioButton should fix it (it's an infamous .NET bug, http://connect.microsoft.com/VisualStudio/feedback/details/584991/clientidmode-static-in-updatepanel-fails-to-do-async-postback)

A: please add up1.Update() after output.Text = DateTime.Now.ToString(). Your  RadioButton is not the trigger for updatepanel

A: Turns out the solution was to remove the GroupName from the RadioButton.  When I remove this tag it fires asynchronously and just updates the panel.  I don't actually need this tag anyway (due to the known bug where GroupName doesn't work on RadioButtons in Repeaters) as I handle the grouping within my click event (i.e. uncheck any other RadioButtons of the same name in other repeater items).


text:
Q: Should I create a settings provider implementing an interface for each handler? Let's say I got a series of services that are handled by a central hub, part of the behavior of the application is controlled by a series of settings that are stored on a file. Right now when I get a request and create the handler for it I inject an ApplicationSettings object that would allow the object to access the setting that matter to it; of course I could provide these values on the constructor, but then some constructors would accept a long list of strings, which does not seem very readable to me. Would it make sense to create an interface for each handler to provide access only the settings that are of handler's concern?

A:
Would it make sense to create an interface for each handler to provide
  access only the settings that are of handler's concern

I would generally say yes. If each object takes a generic config then that makes life very easy for you (the programmer), but the user/client is only going to discover missing configuration during runtime. I would rather have the construction parameters to be explicit.
If you have a huge number of these params, perhaps your object is doing more than it should be? Can you package related config items into smaller objects encapsulating a configuration for a subsystem?

I could provide these values on the constructor, but then some
  constructors would accept a long list of strings, which does not seem
  very readable to me

Another option here is to make use of the builder pattern, which will simplify the constructor.


text:
Q: macOS 10.12.3 "file not found" in TexMaker when viewing as PDF I have the problems of viewing as PDF and it shows File not Found.
I looked through all these similar problems, but mine on macOS still can not be solved. It would be very nice of you to help me out.
TexMaker - "File not found" when viewing as pdf

A: The configuration of pdflatex does not make sense.
Instead of giving the location of texmaker, you should enter the location of pdflatex, something like /usr/local/texlive/2016/bin/x86_64-darwin/pdflatex, so replace the line
 "/Applications/texmaker.app" -interaction=nonstopmode %.tex

with something like
"/usr/local/texlive/2016/bin/x86_64-darwin/pdflatex" -interaction=nonstopmode %.tex

A: One has to compile it first by Tools > Quick Build (or F1 if it is not used for other system function like mine).


text:
Q: SurfaceView blinks the screen for first time - Android I want to use SurfaceView for animation to show the live camera preview. It is working fine. But when it loads for first time it flickering for first time.

A: This is common issue with android surface view.
Window was destroyed then re-created when the SurfaceView was adding, and the Window's pixel format was changed mean while, that guided me to the answer, the pixel format of the SurfaceView and the Activity was different so Window Manager forced the re-created.
To resolve it, just added one line in onCreate() to set pixel format, as below:
getWindow().setFormat(PixelFormat.TRANSLUCENT);

A: Adding a 0px height blank surfaceView to the first layout of the activity might solve the issue. It is a crazy solution, but it solved the issue for me.
You could also check the following query which has a full explanation of answer.
"SurfaceView flashes black on load"


text:
Q: Laravel: Unable to update column by plus current value of column in Laravel Eloquent I am trying to update column value by plus new value with current value of column using laravel eloquent, query executing successfully but query do not insert any record in database.
PurchaseController.php:
$insertPurchase = [];
$insertPurchase['godown_id'] = Auth::user()->id;
$insertPurchase['bill_id'] = $bill_id;
if ($value['exist'] == 0) {
    $this->insertProductIntoRetailProduct($value);
}
$insertPurchase['item_id'] = $value['item_id'];
$insertPurchase['mrp'] = $value['mrp'];
$parsed = Carbon::parse($value['expiry_date']);
$insertPurchase['expiry'] = $parsed->format('Y-m-d');
$insertPurchase['sale_price'] = $value['sale_price'];
$insertPurchase['purchase_price'] = $value['purchase_price'];
$insertPurchase['qty'] = $value['qty'];
$insertPurchase['free_barcode'] = $value['free_barcode'];
$insertPurchase['free_name'] = $value['free_name'];
$insertPurchase['free_qty'] = $value['free_qty'];
$insertPurchase['product_vat'] = (isset($value['product_vat'])) ? $value['product_vat'] : 0;
$insertPurchase['sku'] = $value['sku'];
$insertPurchase['vat_status'] = $billDetails['vat'];
$PurchaseList = new PL($insertPurchase);
$PurchaseList->save();
unset($insertPurchase['qty']);
$GodownStock = GodownStock::firstOrNew(['item_id' => $value['item_id']])
    ->increment('qty', $value['qty'], $insertPurchase);

Model: PurchaseList.php:
public function increment($column, $amount = 1, array $extra = array()){

    $wrapper = $this->grammar->wrap($column);

    $columns = array_merge(array($column => $this->raw("$wrapped + $amount")), $extra);

    return $this->update($columns);
}

I just want to increment qty if item is already exist otherwise simply insert new row.
can any one tell me whats wrong with my code?