text:
Q: Using the Mod Operator for paginating multiple arrays? I have a number of arrays that I need to pull values from depending on the page that is being requested. Each page needs to be assigned a unique combination of data, so for example:
let numbers = ['One', 'Two']
let fruits  = ['Apples', 'Oranges']
let colours = ['Red', 'Green']
let names   = ['John', 'Jane']

None of the arrays would ever be empty, and so the number of available pages would be the length of all arrays multiplied by each other (so in this case, totalPages would be 16
let totalPages = numbers.length * fruits.length * colours.length * names.length

For every page requested, I need to return a unique set of indices so that every page shows a different group of values, and never more than one from each group.
I currently have nested for-loops (example below) but I was wondering if there's a neater way using the mod operator or something, so that I don't need to rely on the for-loops because at some point I may need to introduce extra arrays and I hate how the nested loops look...
let page = 4 // The requested page (not zero-based index)

let nPage = 1
for(let numberIndex = 0; numberIndex < numbers.length; numberIndex ++) {
    for(let fruitIndex = 0; fruitIndex < fruits.length; fruitIndex ++) {
        for(let colourIndex = 0; colourIndex < colours.length; colourIndex ++) {
            for(let nameIndex = 0; nameIndex < names.length; nameIndex ++) {
                // If the loop iteration matches the requested page,
                // return the combination of indexes as array
                if(page === nPage) {
                    return [numberIndex, fruitIndex, colourIndex, nameIndex]
                }
                nPage ++
            }
        }
    }
}

Thanks in advance for any ideas/suggestions :o)

A: This is really a math/algorithm question (which are always fun!). So a good approach is to see if you can figure out the pattern. E.g., given 3 arrays, [1,2,3,4], [x,y,z], and [11,12], you expect
1 x 11
2 x 11
3 x 11
4 x 11

1 y 11
2 y 11
3 y 11
4 y 11

1 z 11
2 z 11
3 z 11
4 z 11

1 x 12
2 x 12
3 x 12
4 x 12

1 y 12
2 y 12
3 y 12
4 y 12

1 z 12
2 z 12
3 z 12
4 z 12

The pattern should be clear now, it's just counting, like you count 1,2,3,...9,10,11...99,100,101.... But in traditional counting, all digits start at 0 and wrap at 10. Whereas in our example, the first digit starts at 1 and wraps around at 4; the 2nd digit starts at 'x' and wraps around at 'z', and the 3rd starts at '11' and wraps at 12.
If someone asks you to find the n-th digit (from the right) of the m-th decimal number 4 digits long (e.g. the 3rd digit of 1234 is 2), you could truncate with temp = floor(m / 10 ** (n-1)), which would give you 1234, 123, 12, 1. Then temp % 10 would give the last digit of each: 4, 3, 2, 1.
In our case, our digits aren't base 10, so we replace the 10's with the appropriate calculations:

let numbers = ['1', '2', '3'];
let fruits = ['a', 'b', 'c'];
let colours = ['x', 'y', 'z'];
let names = ['11', '12', '13'];

let getPage = i =>
    [
        numbers[i % numbers.length],
        fruits[Math.floor(i / numbers.length) % numbers.length],
        colours[Math.floor(i / numbers.length / fruits.length) % colours.length],
    ];

// print only the first 40 pages, otherwise stackoverflow will truncate the console
for (let i = 0; i < 40; i++)
    console.log(getPage(i).join(' '));

And if you have a dynamic set of arrays (e.g. you don't know ahead of time which of these arrays you will use):

let numbers = ['1', '2', '3'];
let fruits = ['a', 'b', 'c'];
let colours = ['x', 'y', 'z'];
let names = ['11', '12', '13'];

let getPage = (pageI, arrays) => {
    // `pageCounts[i]` is the # of combinations that can generated from the 1st `i` arrays.
    let pageCounts = arrays.map((values, j) => arrays
        .filter((_, k) => k < j)
        .map(a => a.length)
        .reduce((a, b) => a * b, 1));
    return arrays.map((values, j) => values[Math.floor(pageI / pageCounts[j]) % values.length]);
};

// print only the first 40 pages, otherwise stackoverflow will truncate the console
for (let i = 0; i < 40; i++)
    console.log(getPage(i, [numbers, fruits, colours, names]).join(' '));

A: I find a cartesian generator would work really well here, as it lets you calculate every combination and stop at the n-th value without calculating ahead. Here's an example using an implementation from this answer.

let numbers = ['One', 'Two']
let fruits  = ['Apples', 'Oranges']
let colours = ['Red', 'Green']
let names   = ['John', 'Jane']

let totalPages = numbers.length * fruits.length * colours.length * names.length

// Function from https://stackoverflow.com/a/44338759
function* cartesian(head, ...tail) {
  let remainder = tail.length ? cartesian(...tail) : [[]];
  for (let r of remainder) for (let h of head) yield [h, ...r];
}

function getPage(n) {
    const combinations = cartesian(numbers, fruits, colours, names);
    for (let i = 0; i < (n-1) % totalPages; i++) combinations.next();
    return combinations.next().value;
}

// loops back, so 1 is the same as 17
console.log(getPage(1))
console.log(getPage(17))

On a side note, I would advise you to refactor your code use an array instead of separate variables as it will make it more maintainable.
const pages = [numbers, fruits, colours, names];

const totalPages = pages.length ? pages.reduce((a,b) => a * b.length, 1) : 0;

...

function getPage(n) {
  const combinations = cartesian(...pages);
  ...


text:
Q: RSpec::Expectations::ExpectationNotMetError in simple example I try to do some simple script
steps.rb file
Given(/^I am on the YouTube home page$/) do
  visit 'http://www.youtube.com'
end
When(/^I search for "(.*?)"$/) do
|search_term|
  fill_in 'search_query', :with => search_term
  click_on 'search-btn'
end
Then(/^videos of large rodents are returned$/) do
  expect(page).to have_content 'Largest rodents'
end

and youtube.feature:
Feature: Search for Videos on YouTube
  Scenario: Search for Videos of Large Rodents
    Given I am on the YouTube home page
    When I search for "capybara"
    Then videos of large rodents are returned
 of course gemfile and env.rb

after run i got:
RSpec::Expectations::ExpectationNotMetError: expected to find text "Largest rodents" in "Remind me later Review A privacy reminder from YouTube, a Google company PL (...)
./features/step_definitions/steps.rb:10:in `/^videos of large rodents are returned$/'
./features/youtube_search.feature:5:in `Then videos of large rodents are returned'

What can be wrong?

A: I would suggest adding a sleep in your code right before you do the expect. So that you can manually go through the page and confirm that the text is present.
If it's present, then it could be that the default wait time is too low and maybe the text takes some time to be visible in the page. If so, I would suggest doing:
expect(page).to have_content("Largest rodents", wait: 15)
In that case, the expect will allow a max wait time of 15 seconds before firing an expectation not met message.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WordPress Blog Not Displaying Posts I've created a custom template using the twentythirteen template. When I activate the template the blog posts disappear from the front page. I've used the same process to make the new template as I did for my own.
You can see my blog page here, http://www.gnarlydigital.com/blog/ and the new blog that I'm working on is here, http://www.flowdirectpumps.com/news/.
I've tripled checked all the code and both templates are identical. I've uploaded the Gnarly Digital template and it works.
Can anyone see anything obvious?
This is the index.php file
<?php get_header(); ?>

<?php if ( have_posts() ) : ?>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentythirteen_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>

<?php get_footer(); ?>


text:
Q: TensorFlow lite conversion: error: op operands must be tensor of 8-bit unsigned integer, but got tensor<1x?x?x3x!tf.quint8> I am trying to convert a model to TensorFlow Lite after adding a few layers to a model. I have successfully run them with test inputs in Python, and they're working fine. The goal is to allow the model to take in RGB images (uint8), resize and shuffle the channels so that preprocessing is entirely consistent between python and platforms using TensorFlow Lite (avoid using Android bitmap resizing libraries, or embedded system resizing methods). I've found preprocessing to be inconsistent between devices.
It also happens for any other op. This makes me think its the Input() layer causing the issue. I'm not sure how to create the layer properly for the conversion to work.
Model setup code

    input_shape = (None, None, 3) # Im using None here because I want the model to accept arbitrary image sizes.
    input = Input(shape=input_shape, batch_size=1, dtype="uint8")
    bn_axis = 3
    bn_eps = 0.0001

    x = ChannelReversal()(input) # A custom layer
    x = Resizing(224, 224, interpolation='bilinear', name="Resize")(x)
    x = DepthwiseNormalization([91.4953, 103.8827, 131.0912])(x) # Another custom layer

    x = Conv2D(
        64, (7, 7), use_bias=False, strides=(2, 2), padding='same',
        name='conv1/7x7_s2')(x)

Here's the error in its full glory
venv/lib/python3.8/site-packages/tensorflow/python/framework/op_def_library.py:742:0: note: see current operation: %1 = "tf.ReverseV2"(%arg0, %outputs_0) {device = ""} : (tensor<1x?x?x3x!tf.quint8>, tensor<1xi32>) -> tensor<1x?x?x3xui8>

error: 'tf.ReverseV2' op operand #0 must be tensor of bfloat16 type or 16-bit float or 32-bit float or 64-bit float or 1-bit signless integer or 16-bit signless integer or 32-bit signless integer or 64-bit signless integer or 8-bit signless integer or complex type with 64-bit float elements or complex type with 32-bit float elements or TensorFlow string type or 16-bit unsigned integer or 8-bit unsigned integer values, but got 'tensor<1x?x?x3x!tf.quint8>'

Here are my custom layers, although I don't think this is the problem
from tensorflow.python.keras.engine.base_layer import Layer
from tensorflow.python.keras import backend as K
from tensorflow.python.ops import math_ops
import tensorflow as tf

class ChannelReversal(Layer):
    """Image color channel reversal layer (e.g. RGB -> BGR)."""

    def __init__(self):
        super(ChannelReversal, self).__init__()

    def call(self, inputs):
        return tf.reverse(inputs, axis=tf.constant([3]), name="channel_reversal")
        # return inputs[..., ::-1]

class DepthwiseNormalization(Layer):
    """Channel specific normalisation"""

    def __init__(self, mean=[0,0,0], stddev=[1.,1.,1.]):
        super(DepthwiseNormalization, self).__init__()
        self.mean = tf.broadcast_to(mean, [224,224,3])
        self.stddev = tf.broadcast_to(stddev, [224,224,3])

    def call(self, inputs):
        if inputs.dtype != K.floatx():
            inputs = math_ops.cast(inputs, K.floatx())

        return (inputs - self.mean) / self.stddev

I was able to fix it by removing dtype argument in input = Input(shape=input_shape, batch_size=1, dtype="uint8"), but then the model expects Float32, which is brings an issue when using it in TensorFlow Lite.

A: My workaround is to just use float32 in the model. This does mean I cast the input before passing it into the model, but this can be done by the TensorFlow lite support library. It looks like this might be a bug in the conversion to TensorFlow Lite.
TensorBuffer imageBuffer = TensorBuffer.createFrom(image.getTensorBuffer(), DataType.FLOAT32); will automatically cast it if the data type of image doesn't match FLOAT32.


text:
Q: Slick-center not working when number of slides is a not a multiple of 3 or less than six with slidesToScroll = 3 I have given some margin top to my slick-center class.I want the slick slider to scroll 3 slides at once.These are my slider settings :
$(".center").slick({
    dots: true,
    infinite: true,
    centerMode: true,
    slidesToShow: 3,
    slidesToScroll: 3
  });

 $(".center").slick('slickSetOption', 'slidesToScroll', 3, true);
});

As slidesToScroll does not work with centerMode ,I'm using slickSetOption to force it to work with scrolling three slides at once.
The issue: This slick-center styling works perfectly fine when the number of slides in my slider are in multiples of 3.But whenever the number of slides are 4,5 .. or any non three multiple,the slick slider doesn't append the correct slide with the slick-center class.
This is my codepen :- https://codepen.io/shivanit2/pen/zLwzbR
Currently there are 8 slides in my codepen,and you can see how its not giving the correct styling .(if you scroll on the third slick-dot)
If you increase 1 slide,it will work perfectly.(multiple of 3's)
How can I resolve this issue?


text:
Q: Windows 2003 Standard IIS Remote Admin - Can't login I have just installed Windows Server 2003 Standard Edition and therefore IIS6 (comes as standard). I have also install the windows component that enable the administration of IIS from the browser (https://server:8098/). The problem I have is that I have to log-in to this tool but the Server Administrator u/name and p/word does not let me in.
The Windows documentation on this tool (http://support.microsoft.com/kb/324282) says "You are prompted for a user name and password that exist on the Web Server" but none of the standard user acounts on the server let me in.
Thanks,

A: Here are a couple ideas:

*

*Take a look at the security log on the server for clues.

*Look at the "Directory Security" tab on the properties of the admin site and ensure "Enable anonymous access" is unchecked.  You will need to use "Integrated Windows authentication" or "Basic authentication".  If you use Basic auth then the password is sent across then network base64 encoded - you will want to use SSL to encrypt it.

*Is there a specific requirement to use the web tools?  You can download Internet Information Services (IIS) 6.0 Manager for Windows XP from Microsoft and run it from a client.

A: I'm not so sure now, haven't set up a Win 2003 box in a while but as far as I remember you have to activate remote desktop first and then you can use a RDP client to access the server.  I recommend that over the ActiveX RDP client.

A: Is the server part of a domain?  It may be defaulting to a domain username/password combo rather than a local username/password.
Try "server.domain.local\administrator" or "administrator@server.domain.local".

A: I would check the permissions on that site in IIS - make sure you are using an account that is a member of a group specifically assigned permissions. I understand that the builtin admin account is not working but its possible the site permissions have changed removing that account or group. - hope that makes some sort of sense

A: This might be unlikely, but are you trying to use a username that has a blank password? Windows restricts remote access when using those accounts.
If that's the case, you can check the Group Policy (gpedit.msc for local computer, or the one for domains if it's in a domain.):
Computer Configuration
 Windows Settings
  Security Settings
   Local Policies
    Accounts: Limit local account use of blank passwords to console logon only


text:
Q: UITapGestureRecogniser not working after switching back to the viewcontroller I added Tap gesture on on containerview subview. Tapgesture action is not triggering when i switch back to the the view controller from menu. Intial root view is loading from storyboard. when coming from home its switching root view as following code.
 AppDelegate *appDelegate;
 appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
 UIViewController *vc ;
 vc = [mainStoryboard instantiateViewControllerWithIdentifier: @"HomeView"];
[[SlideNavigationController sharedInstance]popAllAndSwitchToViewController:vc withCompletion:nil];

I tried printing by the all gesture recognisers to confirm gesture is added or not.
NSArray *gestureRecognizers = self.view.gestureRecognizers;

O/P
<__NSSingleObjectArrayI 0x282dcab80>(
<UITapGestureRecognizer: 0x2813eba00; state = Possible; view = <UIView 0x10d21c1c0>; target= <(action=didTapGesture:, target=<TV2ZPlayerOverlayVC 0x106016600>)>>
)

TapGesture
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapGesture:)];
tap.delegate = self;
[self.view addGestureRecognizer:tap];


text:
Q: "UnsupportedOperation: fileno" in Spacy Jupyter Notebook Anyone might know what this error is about and what to do about it?
Spacy works in python command line interface though.
I have tried to google various parts of the error, but found nothing specific.
This has been on Conda, on Windows 11, with Python 3.9.
Error message below for reference.
UnsupportedOperation                      Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4264/572880994.py in <module>
----> 1 import spacy

C:\ProgramData\Anaconda3\lib\site-packages\spacy\__init__.py in <module>
      4
      5 # set library-specific custom warning handling before doing anything else
----> 6 from .errors import setup_default_warnings
      7
      8 setup_default_warnings()  # noqa: E402

C:\ProgramData\Anaconda3\lib\site-packages\spacy\errors.py in <module>
      1 import warnings
----> 2 from .compat import Literal
      3
      4
      5 class ErrorsWithCodes(type):

C:\ProgramData\Anaconda3\lib\site-packages\spacy\compat.py in <module>
      1 """Helpers for Python and platform compatibility."""
      2 import sys
----> 3 from thinc.util import copy_array
      4
      5 try:

C:\ProgramData\Anaconda3\lib\site-packages\thinc\__init__.py in <module>
      3
      4 from .about import __version__
----> 5 from .config import registry

C:\ProgramData\Anaconda3\lib\site-packages\thinc\config.py in <module>
     11 from pydantic.main import ModelMetaclass
     12 from pydantic.fields import ModelField
---> 13 from wasabi import table
     14 import srsly
     15 import catalogue

C:\ProgramData\Anaconda3\lib\site-packages\wasabi\__init__.py in <module>
     10 from .about import __version__  # noqa
     11
---> 12 msg = Printer()

C:\ProgramData\Anaconda3\lib\site-packages\wasabi\printer.py in __init__(self, pretty, no_print, colors, icons, line_max, animation, animation_ascii, hide_animation, ignore_warnings, env_prefix, timestamp)
     54         self.pretty = pretty and not env_no_pretty
     55         self.no_print = no_print
---> 56         self.show_color = supports_ansi() and not env_log_friendly
     57         self.hide_animation = hide_animation or env_log_friendly
     58         self.ignore_warnings = ignore_warnings

C:\ProgramData\Anaconda3\lib\site-packages\wasabi\util.py in supports_ansi()
    262         if "ANSICON" in os.environ:
    263             return True
--> 264         return _windows_console_supports_ansi()
    265
    266     return True

C:\ProgramData\Anaconda3\lib\site-packages\wasabi\util.py in _windows_console_supports_ansi()
    234             raise ctypes.WinError()
    235
--> 236     console = msvcrt.get_osfhandle(sys.stdout.fileno())
    237     try:
    238         # Try to enable ANSI output support

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\iostream.py in fileno(self)
    306             return self._original_stdstream_copy
    307         else:
--> 308             raise io.UnsupportedOperation("fileno")
    309
    310     def _watch_pipe_fd(self):

UnsupportedOperation: fileno

A: I have the same issue. Maybe you can try that.
conda update spacy

It solved my problem.

A: The issue was temporarily addressed by uninstall the current version of Wasabi with an older one.
pip uninstall wasabi -y

pip install wasabi==0.9.1

The folks from Github mentioned that a newer version of Wasabi should avoid this problem.

A: This issue has been fixed with spaCy 3.4.3 and wasabi 0.10.1, at least using Python 3.9.


text:
Q: Changing process priority in linux for jvm process Is it fine if I change the JVM process priority through nice at server machine [linux]. I wanted my JVM process to use maximum resources from OS.
What is the standard practice? Do people tune the linux OS specifically for a process to get  maximum performance?

A: The normal fair share approach work well for most work loads, and it is not common to tune priorities for performance.  Tuning process priorities can have undesirable side-effects.  There are cases, such as batch processes, where applications are specifically niced.
You will need root privileges to give the JVM higher than normal priority.  This might be acceptable if the process is I/O bound.  If the process is CPU bound, you may find it kills performance on ALL other processes.  This will include the process you used to up the priority.
It is common to nice batch processes, so they don't use resources which might be used by interactive processes.  The CPU speed monitors can be be set to ignore such processes when determining if CPU speed should be increased.  If batch processes are niced, this is typically done in the script running the process.
Modern kernels also allow you to set IO priorities for processes.  Check man ionice.  If your JVM is IO bound this might be appropriate.
I do run my boinc processs extremely niced.  This is because I only want to use CPU cycles which would otherwise be unused for these processes.  They typically uses over 90% of the available cycles.

A: Setting a favourable 'nice' level will give that process priority CPU time over other processes. You will only be able to burst out to a certain "performance" based on how powerful your CPU is.


text:
Q: Combining plots created by R base, lattice, and ggplot2 I know how to combine plots created by R graphics. Just do something like
attach(mtcars)
par(mfrow = c(3,1))
hist(wt)
hist(mpg)
hist(disp)

However, now I have plots by three different graphic systems
# 1
attach(mtcars)
boxplot(mpg~cyl,
        xlab = "Number of Cylinders",
        ylab = "Miles per Gallon")
detach(mtcars)

# 2
library(lattice)
attach(mtcars)
bwplot(~mpg | cyl,
       xlab = "Number of Cylinders",
       ylab = "Miles per Gallon")
detach(mtcars)

# 3
library(ggplot2)
mtcars$cyl <- as.factor(mtcars$cyl)
qplot(cyl, mpg, data = mtcars, geom = ("boxplot"),
      xlab = "Number of Cylinders",
      ylab = "Miles per Gallon")

The par method doesn't work anymore. How can I combine them?

A: I have been adding support for these kinds of problems to the cowplot package. (Disclaimer: I'm the maintainer.) The examples below require R 3.5.0 and the latest development version of cowplot. Note that I rewrote your plot codes so the data frame is always handed to the plot function. This is needed if we want to create self-contained plot objects that we can then format or arrange in a grid. I also replaced qplot() by ggplot() since use of qplot() is now discouraged.
library(ggplot2)
library(cowplot) # devtools::install_github("wilkelab/cowplot/")
library(lattice)

#1 base R (note formula format for base graphics)
p1 <- ~boxplot(mpg~cyl,
               xlab = "Number of Cylinders",
               ylab = "Miles per Gallon",
               data = mtcars)

#2 lattice
p2 <- bwplot(~mpg | cyl,
             xlab = "Number of Cylinders",
             ylab = "Miles per Gallon",
             data = mtcars)

#3 ggplot2
p3 <- ggplot(data = mtcars, aes(factor(cyl), mpg)) +
        geom_boxplot() +
        xlab("Number of Cylinders") +
        ylab("Miles per Gallon")

# cowplot plot_grid function takes all of these
# might require some fiddling with margins to get things look right
plot_grid(p1, p2, p3, rel_heights = c(1, .6), labels = c("a", "b", "c"))

The cowplot functions also integrate with the patchwork library for more sophisticated plot arrangements (or you can nest plot_grid() calls):
library(patchwork) # devtools::install_github("thomasp85/patchwork")
plot_grid(p1, p3) / ggdraw(p2)

A: See the approach using gridBase described in the answer to this question: R: How should I create Grid-graphics?
library(grid)
library(gridBase)
library(lattice)
library(ggplot2)

grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 3)))

# base graphics
vp <- pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 1))
par(omi = gridOMI())
boxplot(mpg ~ cyl,
        xlab = "Number of Cylinders",
        ylab = "Miles per Gallon", data = mtcars)
popViewport()

# lattice plot
vp <- pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2))
par(fig = c(0.9, 1, 0.6, 0.9))
p <- bwplot(~ mpg | cyl,
            xlab = "Number of Cylinders",
            ylab = "Miles per Gallon",
            data = mtcars)
print(p, vp = vp, newpage = FALSE)
popViewport()

# ggplot
vp <- pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 3))
mtcars$cyl <- as.factor(mtcars$cyl)
p <- qplot(cyl,
           mpg,
           data = mtcars,
           geom = ("boxplot"),
           fill = cyl,
           xlab = "Number of Cylinders",
           ylab = "Miles per Gallon")
print(p, vp = vp, newpage = FALSE)
popViewport()


text:
Q: my `couchdb External Processes` return error i'm using couchdb 1.0.2 and i'v following this tutorial to make an External Process...
nothing different with the tutorial... (even for the code and folder structure)...
the error message is
{"error":"{bad_return_value,{os_process_error,{exit_status,2}}}","reason":"{gen_server,call,\n            [<0.1116.0>,\n             {execute,{[{<<\"info\">>,\n

while googling, i got this, but the error is different, and the answer not fix my problem...
i'm using ubuntu 10.10, and couchdb 1.0.2.. is this that caused the error??

A: I know the problem..... in the tutorial, it says to run an external process I must configure my local.ini like this:
[external]

There are two ways you can fix it:
1) add python at the config local.ini
[external]
test = python /usr/local/src/couchdb/test.py

2) add #!/usr/bin/python2.6 (I use Python 2.6) at the top of test.py


text:
Q: Where can I get a SQL Server Trace Dataset? I need a huge SQL Server query trace file (like the profiler trace) with the SQL query text and the time-stamp. I need a trace of SQL traffic produced by a real application because I want to do some pattern analysis. I check many online dataset sites, but I couldn't find one. I don't think anyone will set a profiler trace in production environment since it reduces the performance. But I need a huge trace file (or just SQL Text and Time-stamp will be enough) with the database (with schema and data). Is it possible to get such a data-set ?
At least is it possible to find a data-set with 24 hours of trace?
Does Microsoft has trace files for it's sample databases such as AdventureWorks?

A: Pattern analysis would be entirely dependent on workload.
Every workload is different. Not just differences between transactional (OLTP) and analytics (OLAP), but even a dozen OLTP applications will produce entirely different patterns.
If you want to build a synthetic one, capture a trace while benchmark tests run. You can start with Benchmark Factory or HammerDB as mentioned in this Stack answer.


text:
Q: The meaning of "for the first time" Why does "for the first time" only mean in a certain way?
For example, he drove the car for the first time.
Can it mean he drove the car for the first time of times people drove the car? I mean, he's the first person who drove the car.
Why do people only use "for the first time" to mean that he drove the car for the first time of times he drove the car?

A: I'm making up a sentence from your words because context is always important to get a better understanding.

He drove our new car for the first time when we went to visit our parents.

Time here is a countable noun (countable means you can have it in the plural). The sentence means that at some point we acquired a new car and "he" drove it for the first time (for the first instance/occasion) in his life on the day we went to visit our parents.
After that there were several other times/occasions/instances on which he drove the car. And we could talk of a second time, a third time, etc. It's the meaning you mention in your comment:  One of several instances.
In your original question you referred to the Big Bang and "the beginning of the time" (no "the" here). Time in that case refers to  "a nonspatial continuum" from past through present to future" (1.a). The beginning of time" is a phrase we might find in a religious books, but not only. It means the moment when our World was created. This is not referred to as "the first time, or "a first time", there is just one, it's unique.


text:
Q: connection Pooling in Apache Tomcat 6 causes website to hang until tomcat is restarted again After configuring connection pooling the website seems to hang up after a period of time but it executes faster otherwise.. Is connection pooling the cause for the same? When the website stops responding then a tomcat restart reverts back the problem? What to do?

A: Probably your code is not releasing connections back to the pool.


text:
Q: When I change specific cell value to specific value then write I have make an attempt to create this code and it is working fine but it writes the timestamp whenever Col"B" any values changes to specific value.
I just want that when cell value changes from Approved to Reject then write timestamp.
It should not work when other values changed to Reject.
Any help will be appreciated.
function onEdit(e){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = e.source.getActiveSheet().getName();
  var editedColumn = e.range.getSheet().getActiveCell().getColumn();

  if(sheet=="Sheet1"){
  if(e.value=="Approved" && editedColumn==2 ){

    e.range.offset(0,12).setValue(new Date ()).setNumberFormat("MM/dd/yyyy hh:mm:ss");

  }}}

A: Instead of
e.value=="Approved" && editedColumn==2

use
e.oldValue=="Approved" && e.value=="Reject" && editedColumn==2

Resources

*

*https://developers.google.com/apps-script/guides/triggers/events


text:
Q: Can't connect remotely to my Neo4j database I have a Neo4j database on my desktop computer that I would like to access remotely. I'm not very knowledgeable about servers/networking, but here's a list of things I've done to try to get it working:

*

*Uncommented the dbms.connectors.default_listen_address=0.0.0.0 line in the settings, as well as dbms.connector.http.listen_address=:7474 and dbms.connector.https.listen_address=:7473

*Set up a TCP/UDP port forward on my router mapping 30408 to 7473.

*Reserved a static IP for my desktop (the same one that appears in the port forward).

*Defined incoming firewall exceptions on my desktop for ports 7474, 7473, and 30408 for both TCP and UDP (I'm guessing the 30408 one doesn't matter, but I've been trying everything).

When I try to connect through Chrome with {public_ip}:30408, it gives ERR_EMPTY_RESPONSE (Firefox just says "The connection was reset").
I am able to successfully connect to the neo4j browser on my local network with {local_ip}:7474.
Edit: Should I look into trying to do this with SSH? I still don't know what is going wrong in the first place.


text:
Q: React Native Packager without watchman I just started looking into react-native for android development and setup the environment in windows. Then it turns out there's no watchman release for windows.
The react native packager runs without watchman but the app reloads or live reloads doesn't work and I needed to restart react native packager every time I make changes to the code. This takes at least 1 minute for some reason.
Is there anyway to make this more bearable? For e.g. trigger file changes to packager manually or alternative to watchman that works with react native packager.
Thanks in advance

A: hot/manual reloads should work on windows, you should not have to restart the packager too often


text:
Q: Calculating Compound Interest using Python functions Write a function that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
I am having the error "   ValueError: unsupported format character 'I' (0x49) at index 28"
Here is my code so far.
def BankBalance():
    InputB = 1000
    return InputB
    print("Your initial balance is $1000")

def Interest():
    InputI = 0.05
    return InputI
    print("The rate of interest is 5%")

def CountNumber():
    InputN = float(input("Please enter the number of times per year you would like your interest to be compounded: "))
    return InputN

def Time():
    InputT = float(input("Please enter the number of years you need to compund interest for:"))
    return InputT

def Compount_Interest(InputB, InputI, InputT, InputN):
    Cinterest = (InputB*(1+(InputI % InputN))**(InputN * InputT))
    print("The compound interest for %.InputT years is %.Cinterest" %Cinterest)

B = BankBalance()
I = Interest()
N = CountNumber()
T = Time()
Compount_Interest(B, I, N, T)

A: Here is how you would do it.
def main():
# Getting input for Balance
    balance = float(input("Balance: $ "))
# Getting input for Interest Rate
    intRate = float(input("Interest Rate (%) : "))
# Getting input for Number of Years
    years = int(input("Years: "))
    newBalance = calcBalance(balance, intRate, years)

    print ("New baance:  $%.2f"  %(newBalance))
def calcBalance(bal, int, yrs):
    newBal = bal
    for i in range(yrs):
        newBal = newBal + newBal * int/100
    return newBal

# Program run
main()

A: You are trying to use your variable as a function.
Try this instead :
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))

A: Python, and most other programming languages, don't assume that two adjacent mathematical expressions with no operator between them means multiplication. You are missing a multiplication operator (*) between InputB and the rest of the expression:
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
# Here -------------^


text:
Q: Circular Image View in Android without using any external library Is there any way to make a circular image view in Android without using any external libraries? Something in android design libraries? And I should be able to set the image at run time using code.

A: To have a circular ImageView with new Material components of Android use ShapeableImageView of package com.google.android.material.imageview.ShapeableImageView.
Property to apply is shapeAppearanceOverlay
Example:
<com.google.android.material.imageview.ShapeableImageView
            android:id="@+id/ivUserPic"
            android:layout_width="@dimen/_75sdp"
            android:layout_height="@dimen/_75sdp"
            android:adjustViewBounds="true"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/labelTitle"
            app:shapeAppearanceOverlay="@style/ShapeAppearance.Image.PILL" />

style:
  <style name="ShapeAppearance.Image.PILL" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
</style>

<style name="ShapeAppearance.Image.Top.PILL" parent="">
    <item name="cornerSizeTopLeft">6dp</item>
    <item name="cornerFamilyTopLeft">rounded</item>
    <item name="cornerSizeTopRight">6dp</item>
    <item name="cornerFamilyTopRight">rounded</item>
</style>

A: The best way to do it if you use Material Design in your app
<com.google.android.material.card.MaterialCardView
            android:layout_width="75dp"
            android:layout_height="75dp"
            app:cardCornerRadius="50dp"
            app:strokeWidth="1dp"
            app:strokeColor="@color/black">
            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:id="@+id/paymentlogo"
                android:scaleType="fitCenter"
                android:src="@drawable/your_img" />
        </com.google.android.material.card.MaterialCardView>

A: You can put your ImageView inside CardView and set its corner radius.
Simple example
<android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="25dp"
        card_view:cardPreventCornerOverlap="false">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"/>
    </android.support.v7.widget.CardView>

Note that the corner radius should be twice shorter than image size.

A: UPDATE
Now we can create circular imageView for Android without using any third-party library or custom ImageView
Use ShapeableImageView
Check out this to know how to use ShapeableImageView

OLD ANSWER

you can try this it is working fine in my device
create one RoundedImageView class like this
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView
{

    public RoundedImageView(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {

        Drawable drawable = getDrawable();

        if (drawable == null)
        {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0)
        {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();

        Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius)
    {
        Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
            finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                    false);
        else
            finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                finalBitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,
                finalBitmap.getHeight() / 2 + 0.7f,
                finalBitmap.getWidth() / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, paint);

        return output;
    }

}

now in your layout.xml  use below code
<com.example.RoundedImageView
    android:layout_width="150dp"
    android:layout_height="150dp"
    app:srcCompat="@drawable/disha" />

A:     <androidx.cardview.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:cardCornerRadius="50dp"
        android:id="@+id/icon">

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@drawable/sign_up_1"
            android:id="@+id/icon_val"
            />
    </androidx.cardview.widget.CardView>

if you use androidx then
look at my code,it works fine

A: Jetpack Compose is Android's modern toolkit for building native UI. It simplifies and accelerates UI development on Android.
To have a circular ImageView with Jetpack Compose in Android:-
    Image(
            painter = rememberImagePainter("https://...."),  //image URL
            contentDescription = "avatar",
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(64.dp)
                .clip(CircleShape)
        )

For more Jetpack Compose sample codes,refer this

A: public class CircularImageView extends android.support.v7.widget.AppCompatImageView {

    public CircularImageView(Context context) {
        super(context);
    }

    public CircularImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Try it..

A: public class RoundedImageView extends ImageView {

       public RoundedImageView(Context ctx, AttributeSet attrs) {
              super(ctx, attrs);
       }

       @Override
       protected void onDraw(Canvas canvas) {

              Drawable drawable = getDrawable();

              if (drawable == null) {
                     return;
              }

              if (getWidth() == 0 || getHeight() == 0) {
                     return;
              }
              Bitmap b = ((BitmapDrawable) drawable).getBitmap();
              Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

              int w = getWidth(), h = getHeight();

              Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
              canvas.drawBitmap(roundBitmap, 0, 0, null);

       }

       public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
              Bitmap finalBitmap;
              if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
                     finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                                  false);
              else
                     finalBitmap = bitmap;
              Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                           finalBitmap.getHeight(), Config.ARGB_8888);
              Canvas canvas = new Canvas(output);

              final Paint paint = new Paint();
              final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                           finalBitmap.getHeight());

              paint.setAntiAlias(true);
              paint.setFilterBitmap(true);
              paint.setDither(true);
              canvas.drawARGB(0, 0, 0, 0);
              paint.setColor(Color.parseColor("#BAB399"));
              canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,
                           finalBitmap.getHeight() / 2 + 0.7f,
                           finalBitmap.getWidth() / 2 + 0.1f, paint);
              paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
              canvas.drawBitmap(finalBitmap, rect, rect, paint);

              return output;
       }

}

You can make class of RoundImageView like this


text:
Q: Change Qt Creator Interface Scaling / Font Size Can I change Qt Creator's (latest version: 4.14.0, Windows 10) general GUI font size (or scaling)?
The problem is, my system display scaling is set to 250% and I have two options for high DPI compatibility in Qt Creator, but both have issues:
I can disable Creator's built-in High DPI Scaling and force System (Enhanced) in the Windows compatibility settings:

Or I can enable Creator's built-in scaling and leave the Windows compatibility scaling override turned off (Application scaling):

In the former case, it's actually a size I find very comfortable except the cursors are all too small and Designer gets wonky (plus it's tricky to layout GUI's because apps all run in System (Enhanced) mode from Creator).
In the latter case, the cursors and Designer work, and it's nice to not have heavy anti-aliasing everywhere, except the GUI font is too large for me, and everything feels cramped (especially the top bar, and the left bar reminds me of one of those old school children's telephones with the huge buttons). Plus the general GUI font is different enough in size from my editor font that the whole thing just feels jarring and kind of stresses me out.
So what I think I'd like to do, ideally, is use application scaling like in the latter example, but just shrink the GUI font size to match the former.
I think I ran through all the options thoroughly, and all I can find is settings for the editor window and the console, but not the rest of the GUI.
To be honest, I'm actually not entirely sure why they don't look the same; my expectation was that Qt's built-in High DPI support would take the scale factor into account in the same way that Windows' System (Enhanced) mode does, but I'm sure it's more complicated than that.

A: The problem is Qt automatically round up your 250% scaling to 300%. For Qt Creator application, you can create a "QT_SCALE_FACTOR_ROUNDING_POLICY" environment variable, and set it to "PassThrough". You can find details in this question: Qt Creator "too big" on 3840x2160 and 150% scaling on Windows 10.
It's also worth noting that Qt also behaves like this coding a GUI program. This can be fixed with:
QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);


text:
Q: How can I get properties of a WPF element I have created I am currently making a tool that allows the user to make multiple types of searches quickly by checking what sites they want to search in a listbox.
I am running into an issue related to adding custom to sites to search -- I would like to have a button that allows the user to add another checkbox website to the ListBox that contains them all. That part is not so difficult, but once I have created the checkbox I need to get the URL of the site the user entered, and I cannot figure out how to reference any aspect of the newly created checkbox.
Currently whenever the user clicks the search button, the programs checks what sites are enabled
and then runs whatever code is relevant to the searches that are selected. For the default custom search, it gets the content of the textbox and uses site:textbox.text (in google) to find results from that website
I need to be able to reference the text of a new custom site checkbox and then create a URL out of it. You can see here that I have created a string array which contains the links for other website selections. I attempted to fix this problem by adding  sites.Append(newcustomsitetext.text) in the function that creates the new button (button_click_1), but the user has not actually entered a custom website at that point and that string would be more useful outside of the array because I already have the part of the link I need in the array (google.com/searchq=etc).
I also tried to create a method that would append the selection (updateSitesArray) but again I cannot refence the properties of the Textbox outside of the function that created it.
I am very inexperienced with C# and WPF so I'm sure I am doing something (probably many things) wrong here, so I apologize if this is a silly question.
Here is a screenshot of the application
C# script (browserDiplay.DetermineURL converts string to URI for webbrowser)
namespace HomeWork_Helper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    ///

    public partial class MainWindow : Window
    {
        public int selection = 0;
        public ListBox list;
        string[] sites = { "https://www.google.com/search?q=","https://api.wolframalpha.com/v1/simple?i=","http://www.google.com/search?q=site:wikipedia.org","http://www.google.com/search?q=site:"};
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e) //main search button click
        {
            for (int i = 0; i < SitesList.Items.Count; i++)
            {
                string text = SitesList.Items[i].ToString();
                if (text.Contains("IsChecked:True"))
                {
                    if (SitesList.Items[i].Equals(WolframCheck))
                    {
                        BrowserDisplay browserDisplay = new BrowserDisplay(); //create a new browser
                        browserDisplay.Show(); //Show it
                        browserDisplay.determineURL(sites[i] + searchBox.Text + "&appid=2GA4A5-YL7HY9KR42");
                        Console.WriteLine(text);
                        Console.WriteLine((sites[i] + searchBox.Text + "&appid=2GA4A5-YL7HY9KR42"));
                    }
                    else if (SitesList.Items[i].Equals(CustomSiteCheck))
                    {
                        BrowserDisplay browserDisplay = new BrowserDisplay(); //create a new browser
                        browserDisplay.Show(); //Show it
                        browserDisplay.determineURL(sites[i] + CustomSiteEntry.Text + " " + searchBox.Text);
                        Console.WriteLine(text);
                    }
                    else if (i > 4)    //if i > 4 listbox item is new
                    {
                        BrowserDisplay browserDisplay = new BrowserDisplay(); //create a new browser
                        browserDisplay.Show(); //Show it
                        browserDisplay.determineURL(sites[i] + ***How can I reference a new element here?*** + " " + searchBox.Text);
                        Console.WriteLine(text);
                    }
                    else
                    {
                        BrowserDisplay browserDisplay = new BrowserDisplay(); //create a new browser
                        browserDisplay.Show(); //Show it
                        browserDisplay.determineURL(sites[i] + " " + searchBox.Text);
                        Console.WriteLine(text);
                    }
                }
            }

        }

        public void Button_Click_1(object sender, RoutedEventArgs e) //creates a new buton
        {

            CheckBox newcustomcheck = new CheckBox();
            TextBox customsitetext = new TextBox();
            customsitetext.Width = 215;
            customsitetext.Text = "Enter a custom site here";
            newcustomcheck.Content = customsitetext;
            //newcustomcheck.Checked += updateSitesArray;
            SitesList.Items.Add(newcustomcheck);
            sites.Append(customsitetext.Text);

        }
        private void updateSitesArray(TextBox sender, EventArgs e)
        {

        }
    }
}

XAML code :
<Window x:Class="HomeWork_Helper.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:HomeWork_Helper"
        mc:Ignorable="d"
        Title="MainWindow" Background="DarkGray" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="20"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="20"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20" />
            <RowDefinition Height="Auto" MinHeight="60"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="20" />
        </Grid.RowDefinitions>

        <TextBox Name="searchBox" HorizontalAlignment="Left" Height="60" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="501" Grid.Column="2" Grid.ColumnSpan="2" Grid.Row="1"/>
        <Button Name ="searchButton" Content="Search" HorizontalAlignment="Left" Height="60" VerticalAlignment="Top" Width="251" Grid.Column="1" Grid.Row="1" Click="Button_Click"/>

        <ListBox Name="SitesList" Grid.Column="1" HorizontalAlignment="Left" Height="160" Grid.Row="2" VerticalAlignment="Top" Width="251">
            <CheckBox Name="GoogleCheck" Content="Google Search" IsChecked="false"/>
            <CheckBox Name="WolframCheck" Content="Wolfram Search (slow)" IsChecked="false"/>
            <CheckBox Name="WikipediaCheck" Content="Wikipedia Search" IsChecked="false"/>
            <CheckBox Name="CustomSiteCheck" >
                <TextBox Name="CustomSiteEntry" Text="Enter a cutstom site here." Width="215"/>
            </CheckBox>
        </ListBox>
        <Button Content="Add another custom site" Grid.Column="1" HorizontalAlignment="Left" Height="40" Grid.Row="3" VerticalAlignment="Top" Width="250" Click="Button_Click_1"/>

    </Grid>
</Window>

A: Never create the items directly. Always use a data model and let the framework create the items automatically/dynamically by defining a DataTemplate. This will make data handling much easier, reduce related code and improves readability significantly.
Always operate on the data model. Do not operate on the view.
Another important design principle is to avoid type switches or chained if-statements that check for a data type to execute related action. Such code can't scale: adding new data types would break your code. You would also require to add new if-statements. Code will become ugly and hard to maintain.
In your case simply encapsulate the individual information (or logic) and move it into a dedicated class e.g. Site. Each Site knows the correct URL or how to assemble it. The caller does not have have to care about this details. Simply get the assembled URL and launch the browser to execute the search. This also enables clean polymorphism and removes duplicate code: simply iterate over the Site items and start a search based on each Site data using a single generic search implementation.
The following example is a raw template how get started. Since you are developing using WPF, I recommend to learn and use MVVM as soon as possible. It will make developing much easier.
Please read:
INotifyPropertyChanged (to allow data binding), Data binding overview, Data templating overview (and Dependency properties overview) to fully understand the example.
Site.cs
public class Site : INotifyPropertyChanged
{
  private string title;
  public string Title
  {
    get => this.title;
    set
    {
      this.title = value;
      OnPropertyChanged();
    }
  }

  private string url;
  public string Url
  {
    get => this.url;
    set
    {
      this.url = value;
      OnPropertyChanged();
    }
  }

  private bool isEnabled;
  public bool IsEnabled
  {
    get => this.isEnabled;
    set
    {
      this.isEnabled = value;
      OnPropertyChanged();
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    => this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

MainWindow.xaml.cs
public partial class MainWindow : Window
{
  // This property should really be a DependencyProperty
  public ObservableCollection<Site> SearchSites { get; }

  public MainWindow()
  {
    InitializeComponent();
    this.DataContext = this;

    this.SearchSites = new ObservableCollection<Site>
    {
      new Site() { Title = "DuckDuckGo", Url = "https://duckduckgo.com/?q=" }
    };
  }

  private void StartSearch_OnClick(object sender, RoutedEventArgs e)
  {
    IEnumerable<Site> enabledSearchSites = this.SearchSites.Where(site => site.IsEnabled);
    foreach (Site searchSite in enabledSearchSites)
    {
      var browserDisplay = new BrowserDisplay(); //create a new browser
      browserDisplay.Show(); //Show it
      browserDisplay.determineURL(searchSite.Url + this.SearchBox.Text);
    }
  }

  public void AddNewSearchSite_OnClick(object sender, RoutedEventArgs e)
  {
    var newSearchSite = new Site
    {
      Title = "Enter a custom site name here",
      Url = "Enter a custom site URL here"
    };

    // Since SearchSites is an ObservableCollection, adding/removing an item
    // will instantly update the view (binding target)
    this.SearchSites.Add(newSearchSite);
  }
}

MainWindow.xaml
<ListBox ItemsSource="{Binding SearchSites}">
  <ListBox.ItemTemplate>

    <!-- Describe how each item should look like
         and wire it to the data model using data binding -->
    <DataTemplate DataType="{x:Type local:Site}">
      <CheckBox IsChecked="{Binding IsEnabled}">
        <CheckBox.Content>
          <StackPanel Orientation="Horizontal">
            <TextBox Text="{Binding Title}" />
            <TextBox Text="{Binding Url}" />
          </StackPanel>
        </CheckBox.Content>
      </CheckBox>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>


text:
Q: CityEngine: Displaying points I'm new with CityEngine and I'm currently trying to alter the display of a point dataset which are representing a number of sensors.
I am unsure of how to alter their height (obviously I don't want to extrude them) and also how to change the size! They are tiny! I've attached a screen shot as an example. I can't find much information on the internet for this...

As you can see, they aren't very well displayed! I have had to highlight one to make it obvious where they are, the rest look like specs.
I have also attached a screengrab of the attributes.

A: Even though this question was asked quite some time ago the answers might still be of value to someone.
There are actually two questions asked here I think.
How to alter the elevation of the objects?
You can use the "move tool" (click the button on the top or use the 'w' key). Then pull on the vertical arrow to shift all the selected objects vertically.
There is a text field on the top that you can type the exact offset if you want to be that exact.
How to display the points
As you imported points into CityEngine it does only show you points. If you apply a rule to the point you can change the size of the visualization either using the scope operation s(x,y,z) and add any geometry you want to it so it is visualized - e.g. a cube using the primitive cube operation (or i("builtin:cube") if you're not on CityEngine 2016.0 yet).
You stated that you don't want to extrude them. But there is no other way to give points a proper visualization than to create larger geometry.


text:
Q: Which one is recommended: store css file as binary data or content of css file as text format? I am trying to store custom CSS for each user in the database so inside  tag, based on the user I will import particular styling. There are 2 options:

*

*store the content of CSS as text format and add it into  tag

*store CSS as a binary file then decode and use it (haven't figured it out how yet).

The size of CSS is not more than a couple of kilobytes.
I am not sure which option is optimal and recommended in terms of scalability. If it is the second one, how can I import the decoded CSS file inside  tag?

A: bytea and text are identical in the way they are stored and the limits. The difference is that text is checked for encoding, while bytea isn't.
Since CSS are strings, I would use text as the more natural data type.


text:
Q: XMLGregorianCalendar to java.sql.Timestamp I'm working with webservices, inserting records, that return a timestamp value in XMLGregorianCalendar type. I need to transform it in a java.sql.Timestamp value, so I use a function like this.
public static java.sql.Timestamp getSqlTimeStamp(XMLGregorianCalendar xgc) {
    if (xgc == null) {
        return null;
    } else {
        return new Timestamp(xgc.toGregorianCalendar().getTime().getTime());
    }
}
Timestamp timestamp=getSqlTimeStamp(ExitInXMLGregor.getTimestamp());

My problem is that in the server, the timestamp value when I insert a record, looks like this: 2012-10-03T19:23:22.342+02:00
But when I make my type conversion, I obtain the timestamp value like this: 2012-10-03T17:23:22.342
The time in the server (where the webservice is located) is 2h more than my locale, and for some reason, I obtain my insert locale time, after transform it.
The problem is that I really need to obtain the server time, cause in the DB, the timestamp value matches with the server one, and I'm having problems in the update operation, due to the different values of timestamp.
Please, I would appreciate any kind of help. thanks!
Edit:
I kind of find a solution, but is not exactly what I need. When I convert my timestamp in java.sql.Timestamp format into XMLGregorian I setting the timeZone of the server (setTimeZone(TimeZone.getTimeZone("GMT+02:00"))). This actually works, but is far away from the ideal solution (It could happen that the timezone or even the server change) It would be great to know in this point the timeZone of the server dinamically, but I don't know how...
public static XMLGregorianCalendar getXMLGregorianCalendar(Timestamp timestamp)
        throws BaseException {
    try {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeZone(TimeZone.getTimeZone("GMT+02:00"));
        gc.setTimeInMillis(timestamp.getTime());
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
    } catch (DatatypeConfigurationException ex) {
        throw new BaseException(ex);
    }
}

A: I suspect the timestamp does specify the correct time, just doesn't display with the right time zone.
2012-10-03T17:23:22.342 is the same as 2012-10-03T19:23:22.342+02:00, assuming the (hidden) time zone of the former is +00:00.

A: tl;dr

*

*Both strings represent the same moment, simply adjusted to a time zone while failing to note the offset-from-UTC.

*Avoid such confusion by always including the offset and zone info in such strings.

*Use modern java.time classes that supplant the troublesome legacy classes. (Instant, not Timestamp)

Example code.
myPreparedStatement.setObject(
    … ,
    myXMLGregorianCalendar  // If forced to work with a `javax.xml.datatype.XMLGregorianCalendar` object rather than a modern java.time class…
    .toGregorianCalendar()  // …convert to a `java.util.GregorianCalendar`, and then…
    .toZonedDateTime()      // …convert to modern `java.time.ZonedDateTime` class.
    .toInstant()            // Adjust to UTC by extracting an `Instant` object.
)

Retrieving from a database, as of JDBC 4.2 and later.
Instant instant = myResultSet.getObject( … , Instant.class ) ;

java.time
As the correct accepted Answer by Robert Tupelo-Schneck says, it seems all is well in that both strings represent the same moment but adjusted into a different time zone with a different offset-from-UTC. The problem is that one of those two strings lacks an indicator of its offset-from-UTC.
Such an omission is a bad practice as it creates this confusion. Always include the offset-from-UTC unless absolutely certain the context makes the offset/zone clear.
Work in UTC
Working in UTC avoids this kind of confusion. Generally best to work, store, and exchange date-time values in UTC. Adjust from UTC to a time zone only for presentation to the user or where required by business logic.
Also, you are using terribly troublesome old classes that are now supplanted by the java.time classes. Convert your XMLGregorianCalendar to java.time.ZonedDateTime.
ZonedDateTime zdt = myXMLGregorianCalendar.toGregorianCalendar().toZonedDateTime() ;

Adjust to UTC by extracting an Instant object.
Instant instant = zdt.toInstant() ;

As of JDBC 4.2 and later, you can directly exchange java.time objects with the database. No need to ever use the legacy java.sql.Timestamp class again.
myPreparedStatement.setObject( … , instant ) ;

Retrieval:
Instant instant = myResultSet.getObject( … , Instant.class ) ;

Adjust from UTC to some particular time zone if you want to view the same moment using the wall-clock time used by the people of a particular region.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Convert
If you must interface with some old code requiring a java.sql.Timestamp, you can convert back-and-forth with java.time.Instant. Call new conversion methods added to the old classes.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;

Going the other direction.
Instant instant = ts.toInstant() ;

See also my Answer to a similar Question.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: Enable Postgres PDO module for PHP 5 on Ubuntu to work with Laravel I've spent some hours trying to change the connection driver of my Laravel app from MySQL to Postgres. I'm working with Laravel 5.2 on a Ubuntu 14 (and PHP 5.5.9).
I had Postgres installed in this computer before starting it all. The version I got is 9.3.12.
The problem I'm having is that when my App uses the database it throws an error:

PDOException in Connector.php line 55:
could not find driver

In PHPInfo it says

PDO Drivers:     mysql

And running php -m I don't see anything related to Postgres.
So it seems it's not installed in my computer, but everytime I try to install these modules I get errors, usually related to dependencies.
What is the proper way to get Postgres installed for PHP5?
@edit
With the suggested command sudo apt-get install php5-pgsql I get a message (in my language) that is similar to the following:

The following packages have not found dependencies
php5-pgsql : Depends: php5-common (= 5.5.9+dfsg-1ubuntu4) but
  5.5.9+dfsg-1ubuntu4.14 is installed
E: Impossible to fix problems, you kept (hold) broken packages.


text:
Q: Aligning elements within a list element I have a list of n items.
I'm trying to align the a element having child img, next to  sibling p element.
I've tried setting both to display:inline-block, but I don't see any change. My code looks like this:

Header 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate interdum lacus in hendrerit. Donec libero metus, maximus sit amet.

My goal is to create a sort of panel where the a element is to the left with the text next to it, and the h3 centered in that same panel.

Header 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate interdum lacus in hendrerit. Donec libero metus, maximus sit amet.

A: I didn't understand what your question goal. But, tell me if my answer was wrong :)

li{
  list-style: none;
}
h3{
  text-align: center;
}
img{
  float: left;
}
p{
  text-align: right;
}

Header 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate interdum lacus in hendrerit. Donec libero metus, maximus sit amet.

A: use display:inline-block in a and p and set some width, use text-align:center in h3

body,
h3,
p {
  margin: 0;
  font-size:16px /* restore font-size inline-block fix*/
}
h3 {text-align: center}
ul {
  margin: 0;
  padding: 0;
  font-size: 0
  /*inline-block fix gap*/
}
li {
  background: red;
}
a,
li,
p {
  display: inline-block;
  vertical-align: top;
  width: 50%
}
img {
  width: 100%;
  display: block
}

Header 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate interdum lacus in hendrerit. Donec libero metus, maximus sit amet.

Header 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vulputate interdum lacus in hendrerit. Donec libero metus, maximus sit amet.


text:
Q: Atombios stuck in loop - after 18.04 upgrade After upgrading from 16.04.5 to 18.04.01
HP Tower - 550-276na (N9C09EA#ABU)
Was working fine on 16.04.5

*

*Had issues with ppa - uninstalled with ppa-purge (was just php)

*Also had to disable secure boot - then re-install
sudo apt-get install  linux-signed-generic shim-signed grub-efi-amd64-signed fwupdate-signed
BUT now get error
*ERROR Atombios stuck in loop for more than 5 secs aborting
And machine monitor gets stuck in boot - i.e. cannot login.
How can I get the Radeon card working on 18.04?
Many thanks
Mark

*

*Radeon error atombios stuck in loop
-- This seems to mention removing tlp ??? - which makes no sense

*https://help.ubuntu.com/community/HybridGraphics - tried vgaswitcheroo, which I can start, but doesn't seem to work.

lspci -k shows
bamboo@ubuntu ~ $ lspci -k
00:00.0 Host bridge: Intel Corporation Skylake Host Bridge/DRAM Registers (rev 07)
    Subsystem: Hewlett-Packard Company Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor Host Bridge/DRAM Registers
    Kernel driver in use: skl_uncore
00:01.0 PCI bridge: Intel Corporation Skylake PCIe Controller (x16) (rev 07)
    Kernel driver in use: pcieport
    Kernel modules: shpchp
00:02.0 VGA compatible controller: Intel Corporation HD Graphics 530 (rev 06)
    Subsystem: Hewlett-Packard Company HD Graphics 530
    Kernel driver in use: i915
    Kernel modules: i915
00:14.0 USB controller: Intel Corporation Sunrise Point-H USB 3.0 xHCI Controller (rev 31)
    Subsystem: Hewlett-Packard Company Sunrise Point-H USB 3.0 xHCI Controller
    Kernel driver in use: xhci_hcd
00:16.0 Communication controller: Intel Corporation Sunrise Point-H CSME HECI #1 (rev 31)
    Subsystem: Hewlett-Packard Company Sunrise Point-H CSME HECI
    Kernel driver in use: mei_me
    Kernel modules: mei_me
00:17.0 SATA controller: Intel Corporation Sunrise Point-H SATA controller [AHCI mode] (rev 31)
    Subsystem: Hewlett-Packard Company Sunrise Point-H SATA controller [AHCI mode]
    Kernel driver in use: ahci
    Kernel modules: ahci
00:1c.0 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #5 (rev f1)
    Kernel driver in use: pcieport
    Kernel modules: shpchp
00:1c.6 PCI bridge: Intel Corporation Sunrise Point-H PCI Express Root Port #7 (rev f1)
    Kernel driver in use: pcieport
    Kernel modules: shpchp
00:1f.0 ISA bridge: Intel Corporation Sunrise Point-H LPC Controller (rev 31)
    Subsystem: Hewlett-Packard Company Sunrise Point-H LPC Controller
00:1f.2 Memory controller: Intel Corporation Sunrise Point-H PMC (rev 31)
    Subsystem: Hewlett-Packard Company Sunrise Point-H PMC
00:1f.3 Audio device: Intel Corporation Sunrise Point-H HD Audio (rev 31)
    Subsystem: Hewlett-Packard Company Sunrise Point-H HD Audio
    Kernel driver in use: snd_hda_intel
    Kernel modules: snd_hda_intel
00:1f.4 SMBus: Intel Corporation Sunrise Point-H SMBus (rev 31)
    Subsystem: Hewlett-Packard Company Sunrise Point-H SMBus
    Kernel modules: i2c_i801
01:00.0 Display controller: Advanced Micro Devices, Inc. [AMD/ATI] Jet PRO [Radeon R5 M230] (rev 83)
    Subsystem: Pegatron Jet PRO [Radeon R5 M230]
    Kernel driver in use: radeon
    Kernel modules: radeon, amdgpu
02:00.0 Network controller: Intel Corporation Wireless 3165 (rev 81)
    Subsystem: Intel Corporation Dual Band Wireless AC 3165
    Kernel driver in use: iwlwifi
    Kernel modules: iwlwifi
03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 10)
    Subsystem: Hewlett-Packard Company RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
    Kernel driver in use: r8169
    Kernel modules: r8169

Kern.log shows
Oct  8 20:40:39 ubuntu kernel: [ 1801.169328] [drm:atom_op_jump [radeon]] *ERROR* atombios stuck in loop for more than 5secs aborting
Oct  8 20:40:39 ubuntu kernel: [ 1801.170020] [drm:atom_execute_table_locked [radeon]] *ERROR* atombios stuck executing 69A0 (len 254, WS 0, PS 4) @ 0x69AE
Oct  8 20:40:39 ubuntu kernel: [ 1801.170705] [drm:atom_execute_table_locked [radeon]] *ERROR* atombios stuck executing 630C (len 78, WS 12, PS 8) @ 0x6345
Oct  8 20:40:39 ubuntu kernel: [ 1801.176742] [drm] probing gen 2 caps for device 8086:1901 = 261ad03/e
Oct  8 20:40:39 ubuntu kernel: [ 1801.176744] [drm] PCIE gen 3 link speeds already enabled
Oct  8 20:40:39 ubuntu kernel: [ 1801.454620] radeon 0000:01:00.0: Wait for MC idle timedout !
Oct  8 20:40:40 ubuntu kernel: [ 1801.593576] radeon 0000:01:00.0: Wait for MC idle timedout !
Oct  8 20:40:40 ubuntu kernel: [ 1801.601065] [drm] PCIE GART of 2048M enabled (table at 0x0000000000040000).
Oct  8 20:40:40 ubuntu kernel: [ 1801.601152] radeon 0000:01:00.0: WB enabled
Oct  8 20:40:40 ubuntu kernel: [ 1801.601154] radeon 0000:01:00.0: fence driver on ring 0 use gpu addr 0x0000000080000c00 and cpu addr 0x00000000130f71f9
Oct  8 20:40:40 ubuntu kernel: [ 1801.601155] radeon 0000:01:00.0: fence driver on ring 1 use gpu addr 0x0000000080000c04 and cpu addr 0x00000000679535f7
Oct  8 20:40:40 ubuntu kernel: [ 1801.601156] radeon 0000:01:00.0: fence driver on ring 2 use gpu addr 0x0000000080000c08 and cpu addr 0x00000000343676ec
Oct  8 20:40:40 ubuntu kernel: [ 1801.601156] radeon 0000:01:00.0: fence driver on ring 3 use gpu addr 0x0000000080000c0c and cpu addr 0x000000003fe861e0
Oct  8 20:40:40 ubuntu kernel: [ 1801.601157] radeon 0000:01:00.0: fence driver on ring 4 use gpu addr 0x0000000080000c10 and cpu addr 0x000000001a688652
Oct  8 20:40:40 ubuntu kernel: [ 1802.029891] [drm:r600_ring_test [radeon]] *ERROR* radeon: ring 0 test failed (scratch(0x850C)=0xCAFEDEAD)
Oct  8 20:40:40 ubuntu kernel: [ 1802.030738] [drm:si_resume [radeon]] *ERROR* si startup failed on resume

dmesg shows
[  153.936921] [drm:atom_op_jump [radeon]] *ERROR* atombios stuck in loop for more than 5secs aborting
[  153.936983] [drm:atom_execute_table_locked [radeon]] *ERROR* atombios stuck executing 69A0 (len 254, WS 0, PS 4) @ 0x69AE
[  153.937010] [drm:atom_execute_table_locked [radeon]] *ERROR* atombios stuck executing 630C (len 78, WS 12, PS 8) @ 0x6345
[  153.942315] [drm] probing gen 2 caps for device 8086:1901 = 261ad03/e
[  153.942317] [drm] PCIE gen 3 link speeds already enabled
[  154.222946] radeon 0000:01:00.0: Wait for MC idle timedout !
[  154.363113] radeon 0000:01:00.0: Wait for MC idle timedout !
[  154.370596] [drm] PCIE GART of 2048M enabled (table at 0x0000000000040000).
[  154.370687] radeon 0000:01:00.0: WB enabled
[  154.370689] radeon 0000:01:00.0: fence driver on ring 0 use gpu addr 0x0000000080000c00 and cpu addr 0x00000000ae84d697
[  154.370690] radeon 0000:01:00.0: fence driver on ring 1 use gpu addr 0x0000000080000c04 and cpu addr 0x00000000c86ba01c
[  154.370690] radeon 0000:01:00.0: fence driver on ring 2 use gpu addr 0x0000000080000c08 and cpu addr 0x000000003d0a11af
[  154.370691] radeon 0000:01:00.0: fence driver on ring 3 use gpu addr 0x0000000080000c0c and cpu addr 0x0000000055de998a
[  154.370692] radeon 0000:01:00.0: fence driver on ring 4 use gpu addr 0x0000000080000c10 and cpu addr 0x000000002f6275c7
[  154.804875] [drm:r600_ring_test [radeon]] *ERROR* radeon: ring 0 test failed (scratch(0x850C)=0xCAFEDEAD)
[  154.804908] [drm:si_resume [radeon]] *ERROR* si startup failed on resume

sudo lshw -c video Shows
  *-display
       description: Display controller
       product: Jet PRO [Radeon R5 M230]
       vendor: Advanced Micro Devices, Inc. [AMD/ATI]
       physical id: 0
       bus info: pci@0000:01:00.0
       version: 83
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi bus_master cap_list rom
       configuration: driver=radeon latency=0
       resources: irq:129 memory:c0000000-cfffffff memory:df200000-df23ffff ioport:e000(size=256) memory:df240000-df25ffff
  *-display
       description: VGA compatible controller
       product: HD Graphics 530
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 06
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
       configuration: driver=i915 latency=0
       resources: irq:128 memory:de000000-deffffff memory:b0000000-bfffffff ioport:f000(size=64) memory:c0000-dffff

vgaswitcheroo not working
root@ubuntu:~# sudo cat /sys/kernel/debug/vgaswitcheroo/switch
0:DIS: :DynPwr:0000:01:00.0
1:IGD:+:Pwr:0000:00:02.0
root@ubuntu:~# sudo echo ON > /sys/kernel/debug/vgaswitcheroo/switch
root@ubuntu:~# sudo cat /sys/kernel/debug/vgaswitcheroo/switch
0:DIS: :DynPwr:0000:01:00.0
1:IGD:+:Pwr:0000:00:02.0
root@ubuntu:~# sudo echo DIS > /sys/kernel/debug/vgaswitcheroo/switch
root@ubuntu:~# sudo cat /sys/kernel/debug/vgaswitcheroo/switch
0:DIS: :DynPwr:0000:01:00.0
1:IGD:+:Pwr:0000:00:02.0
root@ubuntu:~# sudo echo OFF > /sys/kernel/debug/vgaswitcheroo/switch
root@ubuntu:~# sudo cat /sys/kernel/debug/vgaswitcheroo/switch
0:DIS: :DynPwr:0000:01:00.0
1:IGD:+:Pwr:0000:00:02.0
root@ubuntu:~# sudo echo ON > /sys/kernel/debug/vgaswitcheroo/switch
root@ubuntu:~# sudo cat /sys/kernel/debug/vgaswitcheroo/switch
0:DIS: :DynPwr:0000:01:00.0
1:IGD:+:Pwr:0000:00:02.0

A: Possibly relates to this issue fixed in this patch.
Upgrading to a newer kernel version that includes the DPM_FLAG_NEVER_SKIP flag set (or perhaps some other related kernel fixes included) might help.


text:
Q: Buzzer is not working with my MicroPython code I'm working on a buzzer that has to make a simple sound. But I can't figure out about how to make this buzzer work in MicroPython. I've already tried the following code but it is not doing much. I'm a little bit stuck at this.
import pycom
import machine
import time
from machine import Pin
import board
import pulseio

buzzer = pulseio.PWMOut(board.D16, variable_frequency=True)

def main():
   buzzer.duty_cycle = ON
   buzzer.frequency = 440
   buzzer.duty_cycle = OFF

if __name__ == "__main__":
   main()

For more information about what I use as materials:
Buzzer:https://datasheet4u.com/datasheet-pdf/Ningbo/KPT-1410/pdf.php?id=868269
The materials for my project is this:

*

*https://pycom.io/product/lopy4/

*https://pycom.io/product/expansion-board-3-0/
I think i'm getting close to it, but can't figure it out.

A: here is similar function to map function that you have used in arduino
def remap(value, leftMin, leftMax, rightMin, rightMax):
    # Figure out how 'wide' each range is
    leftSpan = leftMax - leftMin
    rightSpan = rightMax - rightMin
    # Convert the left range into a 0-1 range (float)
    valueScaled = float(value - leftMin) / float(leftSpan)
    # Convert the 0-1 range into a value in the right range.
    return rightMin + (valueScaled * rightSpan)

for example, if your ADC values are between 2000 and 1000 (on purpose i show that higher ADC value mean lower actual value) you can use function above with following call to get percentage value:
percent_value = remap(
    adc_pin.read(),
    1000, 2200,     # these values comes from experiment above when wet and dry
    100, 1
)

and look at the samples in documentation how to make buzz
import array
import pulseio
import pwmio
import board

# 50% duty cycle at 38kHz.
pwm = pwmio.PWMOut(board.D13, frequency=38000, duty_cycle=32768)
pulse = pulseio.PulseOut(pwm)
#                             on   off     on    off    on
pulses = array.array('H', [65000, 1000, 65000, 65000, 1000])
pulse.send(pulses)

# Modify the array of pulses.
pulses[0] = 200
pulse.send(pulses)


text:
Q: NavigationView click listener not working
I am trying to handle NavigationView click listener for back button but it is not working.

navigationView.setOnClickListener may be enough but may be it's due to some other reason that's why added full class
MainActivity.class
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private ActionBarDrawerToggle toggle;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        resetActionBar();

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        navigationView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                    onBackPressed();
            }
        });
        getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, new CameraFragment()).commit();

    }

    @Override
    public void onBackPressed() {

        //super.onBackPressed();
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if(id == android.R.id.home)
        {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                onBackPressed();
            else
                drawerLayout.openDrawer(navigationView);
            return  true;
        }else if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Fragment fragment = null;

        if (id == R.id.nav_camera) {
            // Handle the camera action
            fragment = new CameraFragment();
        } else if (id == R.id.nav_gallery) {
            fragment = new GalleryFragment();
        } else if (id == R.id.nav_slideshow) {
            fragment = new SlideShowFragment();
        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if(fragment!=null){

            if(item.isChecked())
            {
                if(getSupportFragmentManager().getBackStackEntryCount()==0){
                    drawer.closeDrawers();
                }else{
                    removeAllFragments();
                    getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
                    drawer.closeDrawer(GravityCompat.START);
                }

            }else{
                removeAllFragments();
                getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
                drawer.closeDrawer(GravityCompat.START);
            }
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void removeAllFragments(){
        getSupportFragmentManager().popBackStackImmediate(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    public void replaceFragment(final Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .replace(R.id.content_fragment, fragment).addToBackStack("")
                .commit();
    }

    public void updateDrawerIcon() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
                    if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                        toggle.setDrawerIndicatorEnabled(false);
                    else
                        toggle.setDrawerIndicatorEnabled(true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }, 50);
    }

    public void resetActionBar()
    {
        //display home
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    public void setActionBarTitle(String title) {
        getSupportActionBar().setTitle(title);
    }
}

Answer found by Mike M Comment:
remove navigation.setOnClickListener and replace it to
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                        onBackPressed();
            }
        });


text:
Q: How to use boolean conditions So I'm obviously confused with boolean flow because I run into a problem each time. NOTE: I am teaching myself to program, you are all my only hope in learning! I am trying to define a method that checks if a user is an admin, so that I can display certain objects in views to ONLY admins simple enough...or not, for some reason it's not recognizing that I'm an admin (when I truly am, I've checked!). With this all being said, I am a newb so go easy on me!
helpers/sessions_helper is used by both my User and Blogpost models:
def current_user #determines if user is logged out or is the current user of the session/cookie of profile
  if (user_id = session[:user_id])
    @current_user ||= User.find_by(id: user_id)
  elsif (user_id = cookies.signed[:user_id])
    user = User.find_by(id: user_id)
    if user && user.authenticated?(cookies[:remember_token])
      log_in user
      @current_user = user
    end
  end
end

def current_user?(user)
  user == current_user
end

def is_an_admin
  if current_user && current_user.admin?
  end
end

<%= @blogpost.title %>

<%= @blogpost.content %>

  <% if is_an_admin %>
    <%= link_to "Return to blog", blogposts_path %>
    <%= link_to "Edit Post", edit_blogpost_path, class: 'btn btn-primary' %> |
    <%= link_to "Delete Post", blogpost_path(@blogpost),
                method: :delete, data: {confirm: "Are you sure?"}, class: 'btn btn-danger' %>
  <% else %>
    <%= link_to "Return to blog", blogposts_path %>
  <% end %>

I'm unsure if maybe I have the method in the wrong place? I have tried placing it inside my applications controller and my user controller to no avail. I must be missing something.

A: Your sintax got messed up, but I think you're always returning nil on the is_an_admin method:
def is_an_admin
  if current_user && current_user.admin?
  end
end

It does nothing if the condition is true so it's always returning nil
Change it to something like:
def is_an_admin?
  current_user and current_user.admin? # or shorter: current_user.try('admin?')
end


text:
Q: Why a Vector3 has to be public or serialized to set it's value from another script Anyone care to explain why the direction = bulletDirection; only works when direction is public or [SerializeField] private?
I have Shot() on another script and i use it to set the direction.
private void Shot(){

    GameObject bullet = bulletPrefab;

    // Set Facing Side and Instantiate the Bullet
    if (activePlayerController.facingSide == PlayerController.FacingSide.Right) {
        bullet.GetComponent<BulletController> ().SetDirection (Vector3.right);
    } else if (activePlayerController.facingSide == PlayerController.FacingSide.Left) {
        bullet.GetComponent<BulletController> ().SetDirection (Vector3.left);
    }
    Instantiate (bullet, activePlayer.transform.position, Quaternion.identity, bulletsParent.transform);
}

But the directionis only set to bulletDirection when it is public or [SerializeField] private. When private it is always Vector3.zero.
[SerializeField] private Vector3 direction;

void FixedUpdate () {
    transform.Translate (direction * speed * Time.deltaTime);
}

public void SetDirection(Vector3 bulletDirection) {
    direction = bulletDirection;
}

A: I'd ask in the comments, but I haven't got the rep yet. So, what I'd suggest is to take a look at all the times "direction" is updated.
First though, when you instantiate a new item, the Awake() method is invoked, although Start() isn't until just before the next frame update. So, in between these times, any code that runs in Awake() and Start() could potentially have an effect on your initialisation process.
One way to determine the exact values and points in your code that update the "direction" value is to modify the direction to a property instead, and check the stack trace at each modification. You'd do this with the following code:
#if UNITY_EDITOR
using System.Diagnostics;
using System.Text;
#endif

public class BulletController : MonoBehaviour
{
    private Vector3 _direction = Vector3.None;
    public Vector3 direction
    {
        get
        {
            return _direction;
        }
        set
        {
            _direction = value;
#if UNITY_EDITOR
            StringBuilder sb = new StringBuilder ( "direction updated.\n" );
            StackTrace trace = new StackTrace ( true );
            for ( int i = 0; i < trace.FrameCount; i++ ) // You could use "for ( int i = 1; ... ", after you get the hang of it.
            {
                StackFrame sf = trace.GetFrame ( i );
                sb.AppendLine ( $"[{value}] {sf.GetMethod ( )} : {sf.GetFileName ( )} ({sf.GetFileLineNumber ( )})" );
            }
            UnityEngine.Debug.Log ( sb.ToString ( ) );
#endif
        }
    }
}


text:
Q: Deleted Ubuntu partition, stuck at GRUB command line I am having one big problem. I had dual-boot on my PC: I had Windows 7 and Ubuntu. Yesterday I upgraded to Windows 10 and I deleted the partition where Ubuntu was installed.
When I restarted my laptop it says grub rescue. I tried with these commands: ls, set, root but when I type insmod nomral it says unknown file system. Also when I try ls (hd0,msdos1,3,4 or 5).
I don't have any OS CD or USB and I only have this laptop. I need it so much today.

A: Type the following:
insmod ntfs
insmod part_msdos
set root=(hd0,msdos1)
chainloader +1
boot

If you succeed to get to Windows, you must rewrite the bootloader using something like EasyBCD if you don't have a Windows installation media (DVD or USB).


text:
Q: Powershell Set-Content corrupts file formatting after -Replace is used Bond.out file example (looking to replace what is highlighted):

Out.csv file (data to be used):

Code:
#set paths up
$filepath= 'C:\folder\path\bond.out'
$filepath2= 'C:\folder\path\temp.txt'
$Ticklist='C:\folder\path\tick.txt'
$ratelist='C:\folder\path\rate.txt'

#Import needed data from an excel file which creates and array
$csv = Import-CSV C:\folder\path\RateIDTable.csv | Where { $_.'Rate' -ne "" } | Export-Csv C:\folder\path\out.csv -NoTypeInformation
$bond = Import-CSV C:\folder\path\out.csv | select -Property TickerID, Rate

#Put array from Excel file into two text files
$Tick = $bond | foreach-object {$_.TickerID} | set-content $Ticklist
$replace = $bond | foreach-object {$_.rate} | set-content $Ratelist

#Create two separate arrays from the new text files
$Tickdata = (Get-content $Ticklist ) -join ','
 foreach ($t in $Tickdata)
  {
  $t = $t -split(",")
  $First = $t[0]}

$Ratedata = (Get-content $Ratelist ) -join ','
 foreach ($r in $Ratedata)
  {
  $r = $r -split(",")
  $First = $r[0]}

#Get main file to search (bond.out) and search for the word that is in the first line from "t" array file
$data = Select-String $filepath -pattern $t[0] | Select-Object -ExpandProperty Line
$data

#Once found, split the line, replace the rate on the 3rd line with the rate in the first line from the "r" array file, the put the line back to together
$split=$data.split("{|}")
$split[3]=$r[0]
$join = $split -join "|"
$join

#Put the updated line back into the "bond.out" file from whence it came
(get-content $filepath) -replace($data,$join) | set-content $filepath

#computer says no :(

Output:

As you can see, it actually replaces the rate and puts it all back like I need it to. But that last line doesn't seem to work. Instead I get the file back like so:

It appears as though it is repeating the same line from the $join parameter and adding letters to the beginning of each iteration.
I believe it has something to do with the '|' at the end of the line, and remember reading something about marking the beginning and end of lines some time ago, but can't find it anywhere.

A: Here's an idea. Instead of using regular expressions ...
The Import-Csv command has a -Delimiter parameter. Can you just import bond.out as a "CSV" (but with a pipe delimiter), and update it just like you would a CSV file?
Pseudo-code
### Convert bond.out to objects
$BondOut = Import-Csv -Delimiter '|' -Path $FilePath

### Get the line you want to update
$LineToUpdate = $BondOut.Where({ $PSItem.TickerID -eq 'BBG0019K2QZ5' })

### Update the Rate property from your source (out.csv)
$LineToUpdate.Rate = $SomeSource.Rate

### Export the modified objects to a new bond.out.modified file
$BondOut | Export-Csv -Delimiter '|' -Path 'bond.out.modified' -NoTypeInformation

A: As per PetSerAI's clue:
#set paths up
$filepath= 'C:\folder\path\bond.out'
$filepath2= 'C:\folder\path\temp.txt'
$Ticklist='C:\folder\path\tick.txt'
$ratelist='C:\folder\path\rate.txt'

#Import needed data from an excel file which creates and array
$csv = Import-CSV C:\folder\path\RateIDTable.csv | Where { $_.'Rate' -ne "" } | Export-Csv C:\folder\path\out.csv -NoTypeInformation
$bond = Import-CSV C:\folder\path\out.csv | select -Property TickerID, Rate

#Put array from Excel file into two text files
$Tick = $bond | foreach-object {$_.TickerID} | set-content $Ticklist
$replace = $bond | foreach-object {$_.rate} | set-content $Ratelist

#Create two separate arrays from the new text files
$Tickdata = (Get-content $Ticklist ) -join ','
 foreach ($t in $Tickdata)
  {
  $t = $t -split(",")
}

$Ratedata = (Get-content $Ratelist ) -join ','
 foreach ($r in $Ratedata)
  {
  $r = $r -split(",")
}

#Get main file to search (bond.out) and search for the word that is in the first line from "t" array file

###Replace all pipes with a comma

(get-content $filepath) -replace('\|', ',') | set-content $filepath
$data = Select-String $filepath -pattern $t[0] | Select-Object -ExpandProperty Line
$data

#Once found, split the line, replace the rate on the 3rd line with the rate in the first line from the "r" array file, the put the line back to together
$split=$data.split("{,}")
$split[3]=$r[0]
$join = $split -join ","

#Put the updated line back into the "bond.out" file from whence it came

###change all commas back to pipes

(get-content $filepath) -replace($data,$j) | set-content $filepath
(get-content $filepath) -replace(',', '|') | set-content $filepath
#computer says yay :D