text:
Q: Trouble with brackets yet again I have been working on loops and conditionals lately. I have been pretty successful in understanding the concepts, but the brackets continue to confuse me. Without the bracket at the end of line three, and the very last bracket at the bottom, the call log will not read "Generator #1 is off." like it should. Why do those brackets make such a big difference?
var totalGen = 19;
var totalMW = 0;
for (var genNumber = 1; genNumber <= totalGen; genNumber++){
  if (genNumber <= 4 && genNumber % 2 == 0) {
    totalMW += 62;
   console.log("Generator #" + genNumber + " is on, adding 62 MW, for a total                 of " + totalMW + " MW!");
  }
  else if (genNumber >= 5 && genNumber % 2 == 0) {
    totalMW += 124;
    console.log("Generator #" + genNumber + " is on, adding 124 MW, for a     total of " + totalMW + " MW!");
  }
    else {
      console.log("Generator #" + genNumber + " is off.");
    }
}

A: You need to look at it as statements or groups of statements. If you only have a single statement then there is no need for the curly brackets.
For example:
for(...) statement;
if (cond1) statement;
else if (cond2) statement;

A statement can be a single line. If you however need multiple statements, you need to use curly brackets to group them:
for(...) {
    statement 1;
    statement 2;
    etc..
}

if (cond1) statement;  // single line
else if (cond2) {      // group, only executed if cond2 is true
    statement 1;
    statement 2;
}
else                  // single line
    statement;

This way the browser will know that all these statements belong to a single step.
If you however did this:
if (cond)
    statement 1;
    statement 2;

only statement 1 will be executed if cond is true. statement 2 will be executed regardless, in other words, it will be the same as:
if (cond) statement 1;

statement 2;

Using brackets in all cases can be a good habit as it prevents accidents where several statements are added to a condition etc.

A: In this case, those brackets doesn't make any difference at all.
When there is only one statement in the loop (as it is here), the brackets are not needed.
for (a, b, c) d;

does exactly the same as:
for (a, b, c) { d; }

Personally I always use brackets, even if there is only one statement in the block. I think that it makes the code easier to read and maintain.

A: For loops and if statements are contained within curly braces - that's the syntax.
So if you embed an if inside a for, each block must be inside its respective block.
if(something){
    return;
 }

for(i=0; i<10; i++){// open curly for the for
      if(i == 4){//curly for the if
          console.log('i is 4!');
      }//end curly for the if
 }//end curly for the for

A: The for loop in javascript works with or without curly-braces.
for (...) {
    //statement
}

is the same as
for (...)
    //statement

However, this is only true for single statements...
for (...) {
    if (...) {
        //A
    }

    if (....) {
        //B
    }
}

is not the same as
for (...)
    if (...) {
        //A
    }

    if (....) {
        //B
    }

as only the first if will be caught by the for loop, the other if will be ignored until the loop has finished.
In your code you have a singular if-then-else-if-then-else statement and so it is caught by the for loop.


text:
Q: Get "average" of several randomly broken copies of a same file Due to a broken controller, files get randomly corrupted while being downloaded from a USB flash drive.
I have downloaded several copies of the same file and the errors seem to be generally unique and random for each copy.
Thus, I need a script to compare several (3 to 5) broken copies of a same file (~100 Mb in size each) and 'vote' for correct value for each byte, appending it afterwards to an output file.
Is there a quick and easy way to implement this in Python 3?

A: Zip the byte streams together, and use a Counter to get the consensus byte at each position.
from functools import partial
from collections import Counter
from contextlib import ExitStack
from mmap import mmap, PROT_READ

fnames = ["t1.txt", "t2.txt"]

with ExitStack() as stack:
    fhs = [stack.enter_context(open(f, 'rb')) for f in fnames]
    out = stack.enter_context(open("fixed", 'wb'))
    streams = [mmap(f.fileno(), 0, prot=PROT_READ) for f in fhs]
    for bs in zip(*streams):
        c = Counter(bs)
        out.write(c.most_common(1)[0][0])

redpajama_set_name: RedPajamaStackExchange


text:
Q: \n vs /m in javascript regex I understand that:

\n stands for new line.
/m stands for multiline matching.

I've written a small example about it:

$('button').click(function () {
  var reg = /()(\n?)([\[\w\s\.\]]+)(\2)/g;
  var div = $('body > div');
  div.html(div.html().replace(reg, '$1$2[edited...]$4'));
  $('body').append($('
').text(div.html()))
})

  [div text...]

    [child div text...]

    [child span text 1...]

    [child span text 2...]

<button>click me</button>

It would make some changes:
1/. Find all  tags.
2/. Replace the text of each tag with [edited...].
3/. Show parent html to check again.
It works fine.
Here is my questions:
var reg = /()(\n?)([\[\w\s\.\]]+)(\2)/g;

(): Starting span tag.
(\n?): New line (if need).
([\[\w\s\.\]]+): Standing for [child span text 1/2...].
(\2): New line (if need).
1/. Why does it work without ending span tag (<\/span>)? I mean: it includes the ending tag although I don't require.
2/. In the replacing: .replace(reg, '$1$2[edited...]$4'). I just needn't add  tag, it's automatically. It may be a problem if I have a case:
Hey regex, I don't require it. But why are you done it?
Something may be: All modern browser is smart enough to undertand that I need an end tag (). But, I'm working with regex and string, not with HTML.
So, should it be edited in the furture?
3/. If I remove (\n?) and (\2) from the regex. It still works:

$('button').click(function () {
  var reg = /()([\[\w\s\.\]]+)/g;
  var div = $('body > div');
  div.html(div.html().replace(reg, '$1[edited...]'));
  $('body').append($('
').text(div.html()))
})

  [div text...]

    [child div text...]

    [child span text 1...]

    [child span text 2...]

<button>click me</button>

Same result for this case:
var reg = /()([\[\w\s\.\]]+)/gm;

Clearly, \n and /m don't be required. It's working if I add to or not.
So, are \n and /m similar to?

A: *

*It's not affecting the  tag, but since it's there in the source it'll be there in the output, unchanged.

*It should be edited, but only because you shouldn't be parsing HTML with regex.

*Your list of things to match is [\[\w\s\.\]]+, and \s includes \n so it doesn't change anything if you have (\n?) before it.
Don't use regex.
$('button').click(function () {
  var div = $('body > div');
  div.find("span").text("[edited...]");
  $('body').append($('
').text(div.html()));
})

Done...


text:
Q: ASP MVC 4, pass data from javascript (View) to a C# static method I'm working on a video application and I want to trace the users' actions using the video player API (Flowplayer).
I'm doing it by setting an event listener on each event to handle the "play, pause, resume, etc." events using javascript. After catching the event,I'm calling a static method placed in the server side in order to write the action to the database (and hide the tracing info from the user).
This is what I got for now:
JS Code:
<script type="text/javascript">
// bind listeners to all players on the page
flowplayer(function (api, root) {
    api.bind("pause", function () {
        console.info("pause", api.paused);

        var timePassed = api.video.time;
        @{
            Reporter.ReportPause(timePassed);
        }
        //... more code  ...

</script>

C# Code:
public static void ReportPause ( string timePassed)
{
    // do something with timePassed
}

I got an exception: "Cannot resolve symbol 'timePassed'".
How can I do it the right/elegant way (with minimal overhead).
Thank you all,
YNWA

A: <script type="text/javascript">
        // bind listeners to all players on the page
        flowplayer(function (api, root) {
            api.bind("pause", function () {
                console.info("pause", api.paused);

                var timePassed = $.flowplayer().getTime();
                    $.ajax({
        url: '/Home/ReportPause',
        type: 'POST',
        dataType: "json",
        data: { timePassed: timePassed },
        error: function (a, b, c) { onError(a, b, c, parameters); },
        success: function (data) { onSuccess(data, parameters); }
    });
                });
            }
    </script>

// Controller
public class HomeController{
    public JsonResult ReportPause(string timePassed)
    {
         TimePassedClass.ReportPause(timePassed);
         // more code
    }
}
public static class TimePassedClass
{
      public static void ReportPause(string timePassed)
       {
          // your logic
       }
}


text:
Q: "It's better not" vs. "It'd be better not" Which of these are correct? If both, which sounds more normal?
1) If it's not to give my all, it's better not to have started.
2) If it's not to give my all, it'd be better not to have started.
Any help is appreciated.


text:
Q: Spring Cloud Data Flow - Partition Batch Job using Spring Cloud Kubernetes Deployer : Environment properties not getting passed to worker pods I modified the dataflow sample app partitioned-batch-job to deploy it in a kubernetes cluster via the SCDF server that is running in the cluster. I used the dashboard UI to launch this app as a task. Modified the code for the partitionHandler() (DeployerPartitionHandler bean) as shown below. I am facing an issue with the worker pods being launched without the spring datasource properties from the master pod environment. I confirmed the master step environment has the right values for these properties and it is being set in the DeployerPartitionHandler bean as below:
        partitionHandler
        .setEnvironmentVariablesProvider(new SimpleEnvironmentVariablesProvider(this.environment));

I worked around it for now by passing these as command line arguments as indicated in the code below. Appreciate any inputs on why the environment properties are not available in the worker pods.
Also confirmed that the "spring cloud deployer local" flavor of this app runs on my local machine without this problem via "java -jar target/<app.jar>" .
@Bean
public PartitionHandler partitionHandler(TaskLauncher taskLauncher, JobExplorer jobExplorer,
                                         TaskRepository taskRepository) throws Exception {

    DockerResourceLoader dockerResourceLoader = new DockerResourceLoader();
    Resource resource = dockerResourceLoader.getResource(config.getDockerResourceLocation());
    logger.info("Docker Resource URI: " + config.getDockerResourceLocation());

    DeployerPartitionHandler partitionHandler =
        new DeployerPartitionHandler(taskLauncher, jobExplorer, resource, "workerStep", taskRepository);

    List<String> commandLineArgs = new ArrayList<>(8);
    commandLineArgs.add("--spring.profiles.active=worker");
    commandLineArgs.add("--spring.cloud.task.initialize-enabled=false");
    commandLineArgs.add("--spring.batch.initializer.enabled=false");

    // Passing these properties in command line as worker tasks are not getting them from the environment
    commandLineArgs.add("--spring.datasource.url=jdbc:mysql://10.141.22.143:3306/scdf?useSSL=false");
    commandLineArgs.add("--spring.datasource.username=dbuser");
    commandLineArgs.add("--spring.datasource.password=dbpassword");
    commandLineArgs.add("--spring.datasource.driverClassName=org.mariadb.jdbc.Driver");

    partitionHandler
        .setCommandLineArgsProvider(new PassThroughCommandLineArgsProvider(commandLineArgs));
    partitionHandler
        .setEnvironmentVariablesProvider(new SimpleEnvironmentVariablesProvider(this.environment));
    partitionHandler.setMaxWorkers(2);
    partitionHandler.setApplicationName("PartitionedBatchJobTask");

    return partitionHandler;
}

Included below is the worker pod configuration YAML that shows SCDF is already passing the datasource properties as command line, but it is still not being used (the datasource defaults to H2 embedded and not MYSQL as the URL property indicates). The properties are bunched up together (as part of the sun.java.command property) if that matters.
- --sun.boot.library.path=/opt/openjdk/lib/amd64
- --KUBERNETES_PORT_443_TCP=tcp://10.233.0.1:443
- --sun.java.command=io.spring.PartitionedBatchJobApplication --management.metrics.tags.service=task-application
  --spring.datasource.username=dbuser --spring.datasource.url=jdbc:mysql://10.141.22.143:3306/scdf?useSSL=false
  --spring.datasource.driverClassName=org.mariadb.jdbc.Driver --management.metrics.tags.application=partitioned-batch-job-89
  --docker-resource-location=docker:vrajkuma/partitioned-batch-job:2.3.1-SNAPSHOT
  --spring.cloud.task.name=partitioned-batch-job --spring.datasource.password=dbpassword
  --spring.cloud.task.executionid=89
- --sun.cpu.endian=little
- --MY_SCDF_SPRING_CLOUD_DATAFLOW_SKIPPER_SERVICE_PORT_HTTP=80


text:
Q: Get the value from objects in JavaScript I was inspecting some code through Firebug's debugger. The value I found is wrapped in this.executions. So when I print the value of temp
var temp = this.executions;
console.log(temp);

I am getting output as
[Object { context="1461223497558",  value1="TEST1",  value2="TEST2"}]

I tried using a for...in loop
for(var key in temp) {
  var value = temp[key];
}

Though then I am still getting output like
Object { context="1461223497558",  value1="TEST1",  value2="TEST2"}

I want to extract the values TEST1 and TEST2 of the variables value1 and value2 key. Any idea how to get them?

A: Iterate over keys :
var keys  = Object.keys(temp[0]); // As your first temp var is an array
keys.forEach(function(key){
 console.log(key +" : " +temp[key]);
});

Or first iterate on executions :
this.executions.forEach(function(temp){ // loop over executions
    var keys  = Object.keys(temp);
    keys.forEach(function(key){ // loop over keys
     console.log(key +" : " +temp[key]);
    });
});

this will outpout
context : 1461223497558
value1 : TEST1
...

So now you can do what you want with your data

A: filter the object values that start with 'TEST' (ES6):
var obj = arr[0];
var out = Object.keys(obj).filter(el => obj[el].substring(0, 4) === 'TEST');

DEMO
Or perhaps a more general function (this time ES5):
function extractValues(obj, str) {
  return Object.keys(obj).filter(function(el) {
    return obj[el].substring(0, str.length) === str;
  });
}

extractValues(obj, 'TEST'); // ['TEST1', 'TEST2']

DEMO

A: Note that your first output
[Object { context="1461223497558",  value1="TEST1",  value2="TEST2"}]

is an array of objects indicated by the square brackets around the object.
Therefore you first need to loop over that array (e.g. by using your for...in loop) and then access the properties of the current object:
for(var key in temp) {
  var object = temp[key];
  console.log(object.value1, object.value2);
}


text:
Q: Vaadin 14 fails to load lumo-color and lumo-typography on Windows 10 machine We made a simple UI with Vaadin 14 and Spring Boot. The UI runs flawlessly on OSX as well as in a Docker container based on a Linux image.

However, we don't get it to run on a Windows 10 machine. The app starts and we can access the UI. But all styles are missing. The UI looks totally broken, even though the buttons are working.

There are no errors in the Java log, but the browser console shows the following:
style-gather.js?ee41:216 Could not find style data in module named lumo-color
style-gather.js?ee41:216 Could not find style data in module named lumo-typography

What are we missing?
Edit:
I pushed the project to https://github.com/tuhrig/vaadin-win-issue


text:
Q: I get a ConcurrentModificationException when attempting to launch Minecraft with Forge I have tried to reinstall Minecraft with Forge multiple times, but Minecraft still won't launch.
When I check "Launcher Visibility" and change it to "Hide Launcher" and re-open, I get this error log in the console:
[13:20:11] [main/INFO] [LaunchWrapper]: Loading tweak class name cpw.mods.fml.common.launcher.FMLTweaker
[13:20:11] [main/INFO] [LaunchWrapper]: Using primary tweak class name cpw.mods.fml.common.launcher.FMLTweaker
[13:20:11] [main/INFO] [LaunchWrapper]: Calling tweak class cpw.mods.fml.common.launcher.FMLTweaker
[13:20:11] [main/INFO] [FML]: Forge Mod Loader version 7.10.18.1180 for Minecraft 1.7.10 loading
[13:20:11] [main/INFO] [FML]: Java is Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_20, running on Windows 7:amd64:6.1, installed at C:\Program Files\Java\jre1.8.0_20
[13:20:11] [main/INFO] [LaunchWrapper]: Loading tweak class name cpw.mods.fml.common.launcher.FMLInjectionAndSortingTweaker
[13:20:11] [main/INFO] [LaunchWrapper]: Loading tweak class name cpw.mods.fml.common.launcher.FMLDeobfTweaker
[13:20:11] [main/INFO] [LaunchWrapper]: Calling tweak class cpw.mods.fml.common.launcher.FMLInjectionAndSortingTweaker
[13:20:11] [main/ERROR] [LaunchWrapper]: Unable to launch
java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source) ~[?:1.8.0_20]
    at java.util.ArrayList$Itr.remove(Unknown Source) ~[?:1.8.0_20]
    at net.minecraft.launchwrapper.Launch.launch(Launch.java:117) [launchwrapper-1.9.jar:?]
    at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.9.jar:?]

How can I resolve this?

A: You are not using Forge 10.13.0.1180 as shown on this line
[13:20:11] [main/INFO] [FML]: Forge Mod Loader version 7.10.18.1180 for Minecraft 1.7.10 loading

What i would do is make a copy of your saves and then completely delete the .minecraft folder from appdata.
Reinstall minecraft completely from scratch and then
Use this link to install the correct version of Forge.
It should work fine if you do this

A: You don't need to "downgrade" or "uninstall" Java 8 but you do need to have Java 7 on you machine - and you can run it side-by-side with 8.
The steps I took were:

*

*Install Java 7u76 - I went for the x64 .exe - by default it will install to c:\Program Files\java\jre7\ which should be fine, and won't upset Java 8 - but make a note of this location for step 3.

*Ensure forge is up to date - at the time of writing I went for 1.7.10-Recommended 10.13.2.1230 - run the updater, choosing "Forge Client" and pointing it at your Minecraft install.

*Run the Minecraft Launcher, select the "Forge" profile, and select "Edit Profile", then in the "Java Settings (Advanced)" section, check the box for the executable and change the path to c:\Program Files\java\jre7\javaw.exe and then save the profile:

*Play!

Remember though that you'll probably have to change this setting next time you update Forge as I think it seems to revert the settings back to their defaults when you run the updater.

A: Tip 1: Try down grading Java to Java 7. This is just a fail safe. Forge definitely works with Java 7
Tip 2: Make sure you have launched Minecraft without Forge before trying with Forge. Sometimes this can fix issues with Forge and Minecraft compatibility.
Tip 3: Make sure you are running the correct version of Forge.
There is no need to uninstall Minecraft and re-install.
How To Install Forge for Minecraft 1.7.10
Here is a quick tutorial video I made on installing Forge for Minecraft 1.7.10

*

*Download Forge for 1.7.10 from here

*Activate the installer and select "client"

*Open Minecraft launcher and select "New Profile" (bottom left)

*Name the profile something like "Forge 1.7.10" and select Forge 1.7.10 from the drop down a little further done the profile making page. Save the profile.

*Select your new profile and hit "Play"

*Enjoy playing modded Minecraft.

A: You need to get Java 7 because Java 8 is not compatible with Forge, so here's the download page.
Also, configure Java's security to medium.


text:
Q: Namespace for redis-queue queue in django app I have a django app that uses redis-queue for managing long running tasks in the background. I have it set up and running (if in a stupid configuration), but I'm unclear what the appropriate namespace to store my queue is.
I set up the rq worker as recommended in the docs:
#rqsetup.py
import os
import redis
from rq import Worker, Queue, Connection

listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)

if __name__ == '__main__':
    with Connection(conn):
        worker = Worker(map(Queue, listen))
        worker.work()

I can add the queue to my view:
# views.py
from rqsetup import conn
from rq import Queue
from somewhere import bgtask

def myview(request):
    q = Queue(connection=conn)
    job = q.enqueue(bgtask)
    return render(request, 'somepage.html')

This is obviously dumb, because then the queue and the job are lost after the view is returned. The whole point is to have the queue in some namespace where I can access it again later.
However, I can't figure anywhere else to put it. If I try to in rqsetup, I just get import errors, or it imports out of order before its set up properly. I don't really have a good guess of where else it should go.
I otherwise have a normally structured app:
myproject
 -myproject
  -__init__.py
  -settings.py
  -urls.py
  -wsgi.py
 -myapp
  -apps.py
  -somewhere.py
  -views.py
 -manage.py
 -Procfile
 -requirements.txt
 -rqsetup.py

Where should a redis-queue queue be stored in a django project?

A: Turns out django_rq provides the queue namespace for you! settings.py should have something like this:
RQ_QUEUES = {
    'default': {
        'HOST': 'localhost',
        'PORT': 6379,
        'DB': 0,
        'PASSWORD': 'some-password',
        'DEFAULT_TIMEOUT': 360,
    },
    'high': {
        'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku
        'DEFAULT_TIMEOUT': 500,
    },
    'low': {
        'HOST': 'localhost',
        'PORT': 6379,
        'DB': 0,
    }
}

Then you just just get the queue from the django_rq namespace: queue = django_rq.get_queue('high').


text:
Q: In Google Apps Script, is there a way to define two versions of the logoUrl, one for dark mode and one for light? I'm using Apps Script to create an add-on for extending Gmail. I'm using a black & white icon and it looks great when the user's Gmail UI is in light mode, but becomes invisible in dark mode. Is there a way to use two different logoUrl's, one for each UI mode? I haven't found any documentation or example that points to a solution. The Gmail section of my manifest appsscript.json is:
  "gmail": {
    "name": "MailReceipts",
    "logoUrl": "https://www.gstatic.com/images/icons/material/system/1x/receipt_long_black_24dp.png",
    "contextualTriggers": [
      {
        "unconditional": {},
        "onTriggerFunction": "getContextualAddOn"
      }
    ],
    "primaryColor": "#3d8c5b",
    "secondaryColor": "#54bf7d"
  }

A: Unfortunately there is no parameter that lets you define two versions of the logoUrl in Google Workspace Add-Ons manifest JSON. The only available JSON field under the common parameter is as follows:
{
  "homepageTrigger": {
    object (HomepageTrigger)
  },
  "layoutProperties": {
    object (LayoutProperties)
  },
  "logoUrl": string,
  "name": string,
  "openLinkUrlPrefixes": [
    string
  ],
  "universalActions": [
    {
      object (UniversalAction)
    }
  ],
  "useLocaleFromApp": boolean
}

layoutProperties field only controls the Google Workspace add-on toolbar and button colors and appearance not the logo color itself
Suggestion:
A workaround would be to choose an image or logo that is visible for both light and dark mode. You can easily change the logo by replacing the image url in logoUrl field.
References:
https://developers.google.com/apps-script/manifest/addons#addons
https://developers.google.com/apps-script/manifest/gmail-addons
https://developers.google.com/apps-script/manifest/addons#common
https://developers.google.com/apps-script/manifest/addons#layoutproperties


text:
Q: How to use API response messages in Angular 8 i18n? I am in need to use translations for API responses (especially error messages)
Ex:
1) User name invalid for test@test.com
2) Password is incorrect for test@test.com
3) Login Success for test@test.com

I used i18n select for this purpose. My sample code is below:
{respError, select, User name invalid for {User name invalid for} Password is incorrect for { Password is incorrect for}}

respError - is a variable which holds backend response
Here I am parsing the string and then comparing using i18n select which is working fine. But I am in need to add the dynamic email in the message. I tried to add like this
{User name invalid for {Email}}, but no luck.
Is there any other way to use variables inside {} - braces.

A: There is one example from the documatation that might help:
Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}

From the above example, it looks like you can try to use double curly brackets instead of single:
{User name invalid for {{Email}}}


text:
Q: Updating two tables we getting duplicates I have two tables like
emp:
id  name sal deptno
-------------------
1    a    x   10
2    b    x   20
3    c    x   20

dept:
id sal deptno
-------------
1  100 10
2  200 20
3  300 20

Here I want to update sal column in emp table
update emp
set sal = d.sal
from emp as e
left join dept as d on e.deptno = d.deptno

After executing that query I am getting
id name sal deptno
------------------
1  a    100 10
2  b    200 20
3  c    200 20

but I want
id name sal deptno
------------------
1   a   100 10
2   b   200 20
3   c   300 20

A: try this one :
 update emp
 set sal = d.sal
 from emp as e
 left join dept as d on e.id = d.id


text:
Q: DEADLINE_EXCEEDED when publishing to a Cloud Pub/Sub topic from Compute Engine I have a Java application running in a Google Compute Engine instance. I am attempting to publish a message to a Cloud Pub/Sub topic using the google-cloud library, and I am getting DEADLINE_EXCEEDED exceptions. The code looks like this:
PubSub pubSub = PubSubOptions.getDefaultInstance().toBuilder()
            .build().getService();

String messageId = pubSub.publish(topic, message);

The result is:

com.google.cloud.pubsub.PubSubException: io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED

The documentation suggests that this response is typically caused by networking issues. Is there something I need to configure in my Networking section to allow Compute Engine to reach Pub/Sub? The default-allow-internal firewall rule is present.
I have already made my Compute Engine service account an editor and publisher in the Pub/Sub topic's permissions.
The application resides in a Docker container within a Container Engine-managed Compute Engine instance. The Pub/Sub topic and the Compute Engine instance are in the same project. I am able to use the google-cloud library to connect to other Cloud Platform services, such as Datastore. I am also able to publish to the same Pub/Sub topic without fail from App Engine instances in the same project.
Would I have more luck using the google-api-services-pubsub API library instead of google-cloud?

A: I have the same problem at the moment and created an issue at the google-cloud-java issue tracker on GitHub since I couldn't find it there.
We switched from the old google-api-services-pubsub libraries (which worked) to the new ones and got the exception. Our Java application is also running on a Compute Engine instance.

A: While this can be caused by networking issues (the client cannot connect to the service), the more typical cause is publishing too fast. It is common to call the publish method in a tight loop which can create of thousands to hundreds of thousands within the time it takes a typical request to return.  The network stack on a machine will only send so many requests at a time, while the others sit waiting for execution.  If your machine is able to send N parallel requests and each request takes 0.1s, in a minute you can send 600N requests.  If you publish at a faster rate than that, all additional requests will time out on the client with DEADLINE_EXCEEDED.
You can confirm this by looking at server side metrics in Cloud Monitoring: you will not see these requests and you will only see successful requests. The rate of those requests will tell you the throughput capacity of your machines.
The solution to this is Publisher flow control: limit how fast you are calling the publish method, effectively. You can do this in most client libraries through simple configuration. Please refer to the documentation for the client library publisher API for you client library for details. E.g. in Java, this is a property called FlowControlSettings of the Publisher BatchingSettings.  In Python, this is set directly in the PublisherOptions.


text:
Q: Lemmainser using NLTK I currently have a sentence like this:
text = "This is a car."

I then use a tokeniser and then stem it like so:
ps = PorterStemmer()
text = word_tokenize(text)
stemmed_words = []
for w in words:
    stemmed_words.append(ps.stem(w))

However, I now wish to use NLTK's lemmainser to do this instead. To use it, I need to give it the parts-of-speach of the word like so (inside the loop):
lemmatizer = WordNetLemmatizer()
word = lemmatizer.lemmatize(w, pos=pos)

However, I am unsure how to get the pos argument. I understand I can use this to get the part of speach but that is not accepted as an argument:
pos = nltk.pos_tag(text)

A: You need a dictionary to to translate NLTK POS tags into WordNet tags:
pos_translate = {'J':'a', 'V':'v', 'N':'n', 'R':'r'}

Now, extract POS tags, translate each tag, if possible (if not, choose a default tag, say, "n", and lemmatize:
text = ['This', 'is', 'a', 'car', '.']
[lemmatizer.lemmatize(w,\
       pos=pos_translate[pos[0]] if pos[0] in pos_translate else 'n')\
       for w,pos in nltk.pos_tag(text)]
# ['This', 'be', 'a', 'car', '.']


text:
Q: Integrating Jest with JSPM based app So I wanted to use Jest with my jspm project to write some unit tests, but it turned out it's not so easy... Well, it even turned out it's not so easy with any other testing framework.
How do I write tests for my jspm app? Which framework should I choose? Everything that I look up is quite complicated. I haven't found an easy solution. Every framework seems to require a bunch of workarounds to get things working in jspm setup. I feel kind of lost at the moment
If not Jest, then what would be the least painful way of testing an app in jspm setup?

A: its true that without a 3rd party utility its not really possible to test a jspm based app with Jest.
luckily, there's such a tool to help you do that: https://www.npmjs.com/package/gulp-jest-jspm (mine coincidentally)
You will need to install and use Gulp in order to run your tests
Ive been testing my own React app (built with JSPM) with Jest and its very straightforward.
I've found Jest to be very easy to learn and use. Let me know if you need more info
Yoav


text:
Q: Yocto build succeeds, but warning about missing RDEPENDS I'm using Yocto to compile my application for my target hardware. The build succeeds, but I get a warning:

WARNING: myApplication-0.0.1-r0 do_package_qa: QA Issue: /usr/local/bin/myApplication contained in package myApplication requires libstdc++.so.6(CXXABI_1.3.3), but no providers found in RDEPENDS_myApplication? [file-rdeps]

I've added everything I can find to both the DEPENDS and RDEPENDS of my application's recipe, but I'm still getting that error.
DEPENDS += "gcc-runtime"
RDEPENDS_${PN} += "libstdc++ libstdc++-dev gcc-runtime"

Is there something I can add to my RDEPENDS to eliminate this warning?
I have also tried these other combinations, all of which resulted in a successful build, and of which give the same warning.

*

*Both DEPENDS and RDEPENDS empty.

*RDEPENDS_${PN} += "libstdc++"

*RDEPENDS_${PN} += "libstdc++ libstdc++-dev

*RDEPENDS_${PN} += "libstdc++ gcc-runtime DEPENDS += "gcc-runtime"

A: Please try to add
RDEPENDS_${PN} += "libstdc++6"

RDEPENDS needs the output package name which usually is the name of ipk or rpm and
not the recipe name which generated the given output package. Secondly packages containing only libraries also use debian library naming conventions so they get renamed like above.


text:
Q: Application of Brouwer's theorem in Conceptual Mathematics: A first introduction to categories For the 2nd ed. of Lawvere and Schanuel's Conceptual Mathematics: A first introduction to categories, on p. 132 we are given the following scenario (reproduced for those who don't have the book):
Consider 2 cars traveling on a highway from Buffalo to Rochester:
---------*--------------------*----------
       Buffalo             Rochester

Person A drives starting from Buffalo and ending in Rochester. Person B starts and finishes at the same time, starting and finishing anywhere between Buffalo and Rochester. During the drive both are allowed to go anywhere along the highway they want, even west of Buffalo or east of Rochester. Will Person A and Person B meet at some point?
There are 3 objects involved: I, an interval, E, its endpoints, and R, the long road. This gives two inclusion maps i and j:
        *                   *        E
        |                   |
        |                   | j
        V                   V
        *-------------------*        I
        |   |   |   |   |   |
        |   |   |   |   |   | i
        V   V   V   V   V   V
------------------------------------ R

Person A's travel gives an additional map $m: I \rightarrow R$ and person B's gives another $y: I \rightarrow R$.
Express the restrictions given above on Person A and B's travels by equations involving composition of maps, introducing other objects and maps as needed. Then formulate the conclusion that at some time Person A and B meet in terms of composition of maps (You will need to introduce the object $1$).
This exercise is in the section describing Brouwer's retraction and fixed point theorems. My initial thoughts are:

*

*Some restriction involving $m = i \circ j$ to indicate $m$ must start at Buffalo and end at Rochester.

*Some map $f: 1 \rightarrow I$ where $m \circ f = y \circ f$, where $f$ indicates the point at which they meet ?

I am not too sure how to put this in more formal terms, any help would be appreciated.

A: Consider objects End points $(E)$ of Interval $(I)$, $I$ and $R$ in some category $\mathscr C$, where every map is a continuous map. Following is one way, in which you can describe the situation.

*

*Inclusion map $j:E\rightarrow I$. Which basically are the ends of road $BR$ (Road from Buffalo to Rochester).

*Inclusion map $i:I\rightarrow R$. Which says that object $I$ is also contained in object $R$.

Suppose maps $y, m:I\rightarrow R$ describe two travels. Then following are the restrictions on the travel:

*

*$y\circ j = i\circ j$. This restriction means that, $y$ travel has end points same as end points of road $BR$.

*$\exists o:E\rightarrow I \ such \ that \ i\circ o = m\circ j$. We know that $m\circ j$ describe the end points of travel $m$, and these points lie on the road $BR$. Also, $BR$ road is described by map $i$. Therefore, there exists some family of points $o:E\rightarrow I$ which are mapped to family of points $m\circ j$ by $i$.


text:
Q: I'm using Sanity for managing the database but I'm having a problem with displaying items on my website... here is the code Why items are not displayed on my website? what did I do wrong guys?
Can anyone help me or show me how to solve the issue in this block of code(index.js)
import { client } from '../lib/client';
import {HeroBanner,FooterBanner, Product} from '../components';
const Home = ({ products, bannerData}) => (

    <HeroBanner heroBanner ={bannerData.length && bannerData[0]} />

Best Selling Product

Speakers of many variations

    {products?.map((product) =><Product key={product.id} product={product.name}/>)}

    <FooterBanner footerBanner={bannerData && bannerData[0]}/>

);

export const getServerSideProps = async () =>{
  const query = '*[_type == "product"]';
  const product = await client.fetch(query);

  const bannerQuery = '*[_type == "banner"]';
  const bannerData = await client.fetch(bannerQuery);

  return{
    props: {product, bannerData }
  }
}

export default Home;```

A: The error is that you are passing the prop product through your getServerSideProps function. You need to retrieve it correctly.
const Home = ({
  products, // <---- Here you are trying to get 'products' instead of 'product'
  bannerData
}) => {
  return (
     {/* ... */}
  );
};

export async function getServerSideProps() {

  //...

  return {
    props: { product, bannerData } // <----- Here you are passing 'product'
  }
}


text:
Q: Can't change textview (broadcastreceiver) I'm trying to change my textview, but it doesn't work.
MainActivity:
public void changeTxt(String txt){
    TextView t = (TextView) findViewById(R.id.wifiName);
    t.setText(txt);
}

BroadcastReceiver:
MainActivity ma;
@Override
public void onReceive(Context context, Intent intent) {
    ma= new MainActivity();
    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                        status == BatteryManager.BATTERY_STATUS_FULL;

    int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    String txt = acCharge+"";
    ma.changeTxt(txt);
}

A: Call registerBroadCastReciever like this :
//BroadCastReciever variable in base activity or activity
        private BroadcastReceiver serviceBroadcastReceiver;
//Register reciever method
        void registerBroadcastReceiver(){
        if (serviceBroadcastReceiver != null)
        {
         LocalBroadcastManager.getInstance(this.getActivity()).unregisterReceiver(this.serviceBroadcastReceiver);
            LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(this.serviceBroadcastReceiver, new IntentFilter("...BROADCAST_STR"));
            return;
        }
        this.serviceBroadcastReceiver = new BroadcastReceiver()
        {
            public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent)
            {
                //Recieve STH and call method like SetText() that initialize your textView text
            }
        };
        LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(this.serviceBroadcastReceiver, new IntentFilter("...BROADCAST_STR"));
    }       //Then onResume & onPause methods in activity
    @Override
    public void onResume() {
        super.onResume();
        registerBroadcastReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(this.serviceBroadcastReceiver);
    }

A: Try this:
MyActivity:
public class MyActivity extends Activity {

    private TextView wifi;
    private BateryReceiver bateryReceiver;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        wifi = (TextView) findViewById(R.id.wifiName);
        wifi.setText("nothing");

        bateryReceiver = new BateryReceiver(wifi);

    }

    @Override
    protected void onResume() {
        super.onResume();

        registerReceiver(bateryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(bateryReceiver);
    }
}

BateryReceiver: (create new class if you don't have)
public class BateryReceiver extends BroadcastReceiver {

    private final TextView textView;

    public BateryReceiver(TextView textView)
    {
        this.textView = textView;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean ac = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);
        boolean usb = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);

        String plugSource = (ac == true)? "AC" : "USB";

        if(isCharging)
            textView.setText("charging: " + isCharging + " by " + plugSource);
        else
            textView.setText("not charging");
    }
}

It should be working.


text:
Q: showing continents programmatically in MKMapView I have a view with 3 buttons (Europe, Asia, America) and a MKMapView.
If one of these buttons was clicked, i need to show the specific continent.
In
    MKGeometry.h (Mapkit Framework)
there is a constant
MKMapRectWorld
which i can use to show the whole world.
Is there something similar for continents?
If not, what is the best way to determine all informations i need for creating a MKCoordinateRegion?

A: Use Google Earth or Goole Maps to work out the lat/long boundaries and then call setRegion on your map view.


text:
Q: Batch copy only modified files I have two folders (say Source and Working). Now within these, there are 100s of other files/folders.
Now, the folder Source gets updated periodically (i.e. some files/folders may change or get added). I am trying to keep both the folders in sync.
So I need a batch command such that only the files/folders which are new/modified in "Source" get updated into the  "Working" folder.

A: You do not need a bat file. Just use the xcopy with some parameters. Try:
xcopy <path to source> <path to destination> /D /E /C /Q /H /R /Y /K

source  Specifies the file(s) to copy.
destination Specifies the location or name of new files.
/A  Copies only files with the archive attribute set, doesn't change the attribute.
/M  Copies only files with the archive attribute set, turns off the archive attribute.
/D:m-d-y    Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.
/EXCLUDE:file1 [+file2][+file3]...  Specifies a list of files containing strings. When any of the strings match any part of the absolute path of the file to be copied, that file will be excluded from being copied. For example, specifying a string like \obj\ or .obj will exclude all files underneath the directory obj or all files with the .obj extension respectively.
/P  Prompts you before creating each destination file.
/S  Copies directories and subdirectories except empty ones.
/E  Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.
/V  Verifies each new file.
/W  Prompts you to press a key before copying.
/C  Continues copying even if errors occur.
/I  If destination does not exist and copying more than one file, assumes that destination must be a directory.
/Q  Does not display file names while copying.
/F  Displays full source and destination file names while copying.
/L  Displays files that would be copied.
/H  Copies hidden and system files also.
/R  Overwrites read-only files.
/T  Creates directory structure, but does not copy files. Does not include empty directories or subdirectories. /T /E includes empty directories and subdirectories.
/U  Copies only files that already exist in destination.
/K  Copies attributes. Normal Xcopy will reset read-only attributes.
/N  Copies using the generated short names.
/O  Copies file ownership and ACL information.
/X  Copies file audit settings (implies /O).
/Y  Suppresses prompting to confirm you want to overwrite an existing destination file.
/-Y Causes prompting to confirm you want to overwrite an existing destination file.
/Z  Copies networked files in restartable mode.
/B  Copies the Symbolic Link itself versus the target of the link.
/J  Copies using unbuffered I/O. Recommended for very large files.

A: /D:m-d-y    Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.
So only the /D and /Y parameter are needed to answer the original question:
xcopy <source> <destination> /D /Y


text:
Q: Bigquery + Firebase analytics: select table of yesterday I'm querying bigQuery like this:
SELECT
  param1.value.string_value AS id,
  count(1) AS views,
FROM `projectname.analytics_id.events_20200808`,
  UNNEST(event_params) as param1
WHERE
  event_name = 'myEvent'
  AND param1.key='id'
GROUP BY 1

I would like to make this a scheduled query. Is there a possibility to make my table a variable (so I can query the table of yesterday automatically)?
projectname.analytics_id.events_20200808 -> projectname.analytics_id.events_VARIABLE

Thanks!

A: You can use dynamic SQL option by using EXECUTE IMMEDIATE. Here is the example:
DECLARE TABLE_NAME STRING;
SET TABLE_NAME=CONCAT("projectname.analytics_id.events_",FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)));
EXECUTE IMMEDIATE FORMAT("""SELECT * FROM %s""",TABLE_NAME);


text:
Q: ANTLR: field access and evaluation I'm trying to write a piece of grammar to express field access for a hierarchical structure, something like a.b.c where c is a field of a.b and b is a field of a.
To evaluate the value of a.b.c.d.e we need to evaluate the value of a.b.c.d and then get the value of e.
To evalutate the value of a.b.c.d we need to evalute the value of a.b.c and then get the value of d and so on...
If you have a tree like this (the arrow means "lhs is parent of rhs"):
Node(e) -> Node(d) -> Node(c) -> Node(b) -> Node(a)

the evaluation is quite simple. Using recursion, we just need to resolve the value of the child and then access to the correct field.
The problem is: I have this 3 rules in my ANTLR grammar file:
tokens {
    LBRACE  = '{' ;
    RBRACE  = '}' ;
    LBRACK  = '[' ;
    RBRACK  = ']' ;
    DOT     = '.' ;
    ....
}

reference
    : DOLLAR LBRACE selector RBRACE -> ^(NODE_VAR_REFERENCE selector)
;

selector
    : IDENT access -> ^(IDENT access)
;

access
    : DOT IDENT access? -> ^(IDENT<node=com.at.cson.ast.FieldAccessTree> access?)
    | LBRACK IDENT RBRACK access? -> ^(IDENT<node=com.at.cson.ast.FieldAccessTree> access?)
    | LBRACK INTEGER RBRACK access? -> ^(INTEGER<node=com.at.cson.ast.ArrayAccessTree> access?)
;

As expected, my tree has this form:
ReferenceTree
  IdentTree[a]
    FieldAccessTree[b]
      FieldAccessTree[c]
        FieldAccessTree[d]
          FieldAccessTree[e]

The evaluation is not that easy as in the other case because I need to get the value of the current node and then give it to the child and so on...
Is there any way to reverse the order of the tree using ANTLR or I need to do it manually?

A: You can only do this by using the inline tree operator1, ^, instead of a rewrite rule.
A demo:
grammar T;

options {
  output=AST;
}

tokens {
  ROOT;
  LBRACK = '[' ;
  RBRACK = ']' ;
  DOT    = '.' ;
}

parse
 : selector+ EOF -> ^(ROOT selector+)
 ;

selector
 : IDENT (access^)*
 ;

access
 : DOT IDENT             -> IDENT
 | LBRACK IDENT RBRACK   -> IDENT
 | LBRACK INTEGER RBRACK -> INTEGER
 ;

IDENT   : 'a'..'z'+;
INTEGER : '0'..'9'+;
SPACE   : ' ' {skip();};

Parsing the input:
a.b.c    a[1][2][3]

will produce the following AST:

1 for more info about inline tree operators and rewrite rules, see: How to output the AST built using ANTLR?


text:
Q: reduced size image not shown while big image works I really have no idea why it won't work, I did exactly same as other tutorials. Maybe the way I'm extracting image is the problem. I'm using imagekit and goose. Any help would be appreciated.
Here is my Full Code for this problem .
class PostCreateView(CreateView):
     model = Post
     form_class = PostForm
     template_name = 'main/add_post.html'

     def form_valid(self, form):
            self.object = form.save(commit=False)
            # any manual settings go here
            self.object.moderator = self.request.user
            self.object.image = extract(self.object.url)

            self.object.save()
            return HttpResponseRedirect(reverse('post', args=[self.object.slug]))

For extract method
def extract(url):
    g = Goose()
    article = g.extract(url=url)
    resposne = {'image':article.top_image.src}
    return article.top_image.src

my models, where image is saved(has been extracted)
class Post(models.Model):
    image = models.ImageField(upload_to="images",blank=True, null=True)
    image_thumbnail = ImageSpecField(source='image',
        processors=[ResizeToFill(70,70)],
        format='PNG',
        options={'quality':60}
    )

For post.html

second img is working, while the first one shows small box showing broken image
I have installed pillow correctly, and

A: according to discussion I had with you in discussion chat, the image url of thumbnail is:

which is wrong.
you need to fix the url and possibly also hand image file over to ImageSpecField so it can thumbnail correctly..


text:
Q: Bootstrap Typeahead Bloodhound tokenizer doesn't work with mulitple values Here's my javascript:
<script type="text/javascript">
    $(document).ready(function () {

        var people = new Bloodhound({
              datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.tokens); },
              queryTokenizer: Bloodhound.tokenizers.whitespace,
              local: [
                {
                    fullName: '',
                    "],
                },
                {
                    fullName: 'Marijus Merkevicius',
                    tokens: ["Marijus Merkevicius", "marijusm"],
                },
              ]
            });

        // initialize the bloodhound suggestion engine
        people.initialize();

        // instantiate the typeahead UI
        $('#${id }').typeahead(null, {
          displayKey: 'fullName',
          source: people.ttAdapter(),
        });

    });
</script>

When I use return Bloodhound.tokenizers.whitespace(d.fullName); autocomplete works perfectly however when I return d.tokens it doesn't at all. What am I doing wrong here ?

A: Tokens is an array and it is expecting a string. You could try d.tokens.join(' '), though not sure if you need a jQuery selector ($) around d.


text:
Q: How to add bitmapfield at runtime? Hi developers I am new to Blackberry. The screen contain some buttons.When I click on a button it should add a bitmapfield in specified position in current manager, and it should removed when I click on other button on the screen.How can I implement it?

A: Useful info:
How to create a BitmapField tutorial.
ButtonField API (includes sample code).

When I click on a button it should add
  a bitmapfield in specified position in
  current manager, and it should removed
  when I click on other button on the
  screen.

Well, your screen is a Manager. So you can just use its add(Field field), insert(Field field, int index) or delete(Field field) methods (bearing in mind that your BitmapField is a Field).


text:
Q: FreeBSD + Audio from Realtec ALC883 integrated in motherboard I have one integrated soundcard in motherboard with Realtec ALC883 chip(?) and one PCI sound card ESS Solo-1E. FreeBSD 10.3-RELEASE
I need play differend mp3 on each of output. I have no problem with sound on PCI card, but can't understand, how to send sound form mpg123 to integrated soundcard (as I understand, there are no such device in /dev/).
ls /dev/:
acpi            atkbd0          devctl2         kbd1            mixer1          reroot          ttyv2           ttyvd           usbctl
ad0             audit           devstat         kbdmux0         mixer2          sndstat         ttyv3           ttyve           xpt0
ad0p1           bpf             dsp0.0          klog            mixer3          stderr          ttyv4           ttyvf           zero
ad0p2           bpf0            dumpdev         kmem            mixer4          stdin           ttyv5           ufssuspend
ad0p3           console         fd              log             nfslock         stdout          ttyv6           ugen0.1
ada0            consolectl      fido            lpt0            null            sysmouse        ttyv7           ugen1.1
ada0p1          ctty            geom.ctl        lpt0.ctl        pass0           ttyu0           ttyv8           ugen2.1
ada0p2          cuau0           gptid           mdctl           pci             ttyu0.init      ttyv9           ugen3.1
ada0p3          cuau0.init      hpet0           mem             ppi0            ttyu0.lock      ttyva           ugen4.1
apm             cuau0.lock      io              midistat        pts             ttyv0           ttyvb           urandom
apmctl          devctl          kbd0            mixer0          random          ttyv1           ttyvc           usb

dsp0.0 is for PCI card
cat /dev/sndstat:
Installed devices:
pcm0: <ESS Solo-1E> (play/rec) default
pcm1: <ATI R6xx (HDMI)> (play)
pcm2: <Realtek ALC883 (Rear Analog)> (play/rec)
pcm3: <Realtek ALC883 (Front Analog)> (play/rec)
pcm4: <Realtek ALC883 (Onboard Digital)> (play)

cat /boot/loader.conf:
snd_solo_load="YES"
snd_hda_load="YES"

A: to list all avaliable sound devices (in my example 0 - PCI card, 2 - internal rear output)
root@012-music:/home/ishayahu # sysctl dev.pcm
....
dev.pcm.2.bitperfect: 0
dev.pcm.2.buffersize: 65536
dev.pcm.2.rec.autosrc: 2
dev.pcm.2.rec.32bit: 20
dev.pcm.2.rec.vchanformat: s16le:2.0
dev.pcm.2.rec.vchanrate: 48000
dev.pcm.2.rec.vchanmode: fixed
dev.pcm.2.rec.vchans: 1
dev.pcm.2.play.32bit: 24
dev.pcm.2.play.vchanformat: s16le:2.0
dev.pcm.2.play.vchanrate: 48000
dev.pcm.2.play.vchanmode: fixed
dev.pcm.2.play.vchans: 1
dev.pcm.2.%parent: hdaa1
dev.pcm.2.%pnpinfo:
dev.pcm.2.%location: nid=20,24,26
dev.pcm.2.%driver: pcm
dev.pcm.2.%desc: Realtek ALC883 (Rear Analog)dev.pcm.0.bitperfect: 0
...
dev.pcm.0.buffersize: 16384
dev.pcm.0.rec.vchanformat: s16le:2.0
dev.pcm.0.rec.vchanrate: 48000
dev.pcm.0.rec.vchanmode: fixed
dev.pcm.0.rec.vchans: 1
dev.pcm.0.play.vchanformat: s16le:2.0
dev.pcm.0.play.vchanrate: 48000
dev.pcm.0.play.vchanmode: fixed
dev.pcm.0.play.vchans: 1
dev.pcm.0.%parent: pci4
dev.pcm.0.%pnpinfo: vendor=0x125d device=0x1969 subvendor=0x125d subdevice=0x8888 class=0x040100
dev.pcm.0.%location: pci0:4:1:0
dev.pcm.0.%driver: pcm
dev.pcm.0.%desc: ESS Solo-1E

to play different files on differents outputs:
mpg123 -a /dev/dsp0.0 dir/file.mp3
mpg123 -a /dev/dsp2.0 dir2/file.mp3


text:
Q: PhpMyAdmin SQL code not showing up when creating new database and table I'm  using WampServer with phpmyadmin, but have also tried Xamp and same results.
I have 6 entries in the table called employees:
I have a table called employee with entries:

empId, lastName, firstName, department, position, and salary.

empId is primary key w/ auto increment. I'm following a tutorial online where they are using a mac computer, I'm on windows, in case that has something to do with the issue.

When I look at the SQL this produces it shows this:
SELECT * FROM `employee` WHERE 1

I don't see any CreateTable or other SQL.

Can anyone shed some light as to what is going on here?
Thank you.

UPDATE:
So if I go to > Export to SQL:
And this is what I get:
CREATE TABLE IF NOT EXISTS employee (
empId int(11) NOT NULL,
  lastName varchar(40) NOT NULL,
  firstName varchar(20) NOT NULL,
  department int(2) NOT NULL,
  position varchar(20) NOT NULL,
  salary int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE employee
 ADD PRIMARY KEY (empI);

Which looks like the correct SQL.

So at least I know it is creating the correct SQL even though its not showing on the phpmyadmin web gui page.

A: A CREATE TABLE statement is just a command to create a table. You can also create a table using the GUI of PHPMyAdmin, in which case it performs the necessary actions for you.
But those are just commands, blue-prints if you like. In the database itself the 'Create table' statement doesn't exist. The database contains an actual table which was created using such a statement. When you export the database (like you did) or ask for the create table statement, it just reverse-engineers the actual table structure into a statement, like drawing a blue-print based on an actual object you have.
PHPMyAdmin will often show the statement that it generated to build -for instance- a table, but in some cases you may not see it. It might be that the guy of the tutorial has a slightly different version of PHPMyAdmin, or he activated a feature that shows the statement.


text:
Q: Plugin method not found This is my plugin:
<?php
namespace Vendor\Module\Plugin;

use Magento\Email\Controller\Adminhtml\Email\Template\DefaultTemplate;

class MyPlugin
{
    public function afterExecute(DefaultTemplate $template, $result)
    {
        $text = $template->getData('template_text');
        $text .= '
Custom Text
';
        $template->setData('template_text', $text);
    }
}

Var dump works. Plugin executes, but I can't get why getData method is not found. Any suggestions?

A: You have done wrong.The original function execute() does have return @return **void** .So, for you $result is void type variable and also how you can $template variable as your return does not give any parameters like that?. and $template give Magento\Email\Controller\Adminhtml\Email\Template\DefaultTemplate class object.
If you want $template variable data then you have to use
$template = $template->getRequest()->getParam('code');

Actually, You have to explain what you to achieve?


text:
Q: REGEXP_LIKE - Find pattern containing special character I need to find if a column value contains the following pattern:
513-2400-23 - Valid
513-PBS-231 - Valid
521-PB-21 - Valid
52-12-21 - Valid
513-2321 - Not Valid

I have tried the following version and many other but they are working for one case but not for other.
SELECT CASE
    WHEN REGEXP_LIKE('B12-23-43', '.-.-.') THEN 'Y'
    ELSE 'N' END FROM DUAL;

A: Assuming that valid pattern requires exactly two dashes, this should work:
SELECT CASE
    WHEN REGEXP_LIKE('B12-23-43', '^[^-]+-[^-]+-[^-]+$') THEN 'Y'
    ELSE 'N' END FROM DUAL;

The pattern requires the string to start in one or more non-dashes, then to have a dash, then some more non-dash characters, and finally some more non-dash characters.
Demo on sqlfiddle.

A: Select Case WHEN REGEXP_LIKE('B12-23-43',
              '^[[:alnum:]]{1,}-[[:alnum:]]{1,}-[[:alnum:]]{1,}$') THEN 'Y'
       ELSE 'N' END
FROM DUAL;

UPDATE
To also cover cases such as this one: 544-445-PBBTS-24.3, it could be extended as shown below:
Select Case When
   Regexp_Like('B12-23-43',
   '^([[:alnum:]]{1,}-){2}[[:alnum:]]{1,}(-[[:alnum:]]{1,}\.[[:alnum:]]{1,})?$')
   THEN 'Y'
   ELSE 'N' END
FROM DUAL;

A: SELECT CASE
    WHEN (LEN('B12-23-43') - LEN(REPLACE('B12-23-43', '-', '')) = 2) THEN 'Y'
    ELSE 'N' END FROM DUAL;


text:
Q: Google Line Charts hAxis sections offset & overlapping Java Dates Current & Previous Week Google Line Charts to show issue
Background: This chart is updated programmatically each week and has worked fine for several months. The line chart tracks a percentage of systems in a given state, with the count of systems called out, along with a trend-line over a rolling year.
Issue: This week as shown on the top of linked image (with no changes to the code generating the data or chart), seemingly random sections of of the hAxis date range have moved to the right, overlapping other dates. The trend and annotations on the line itself appear correct.
Any insight or guidance would be very much appreciated!
Code:
  <script type="text/javascript"
      src="https://www.google.com/jsapi?autoload={
        'modules':[{
          'name':'visualization',
          'version':'1',
          'packages':['corechart']
        }]
      }"></script>

    <script type="text/javascript">
    google.setOnLoadCallback(drawChart);
    function drawChart() {

        // Create the data table.
        var data = google.visualization.arrayToDataTable([
        ['Date', 'Percent ', {type: 'number', role: 'annotation'}],[new Date(2015, 4, 30), 0.016119402985075, 81],[new Date(2015, 5, 06), 0.018779342723005, 96],[new Date(2015, 5, 13), 0.025033960799534, 129],[new Date(2015, 5, 20), 0.018069973087274, 94],[new Date(2015, 5, 27), 0.017182130584192, 90],[new Date(2015, 6, 04), 0.023132347364429, 122],[new Date(2015, 6, 11), 0.019939804364184, 106],[new Date(2015, 6, 18), 0.017420311341735, 94],[new Date(2015, 6, 25), 0.017922457937089, 98],[new Date(2015, 7, 01), 0.017391304347826, 96],[new Date(2015, 7, 08), 0.020658949243099, 116],[new Date(2015, 7, 15), 0.022210563133963, 127],[new Date(2015, 7, 22), 0.018635664216105, 109],[new Date(2015, 7, 29), 0.017215189873418, 102],[new Date(2015, 8, 05), 0.018827057647451, 113],[new Date(2015, 8, 12), 0.015666226912929, 95],[new Date(2015, 8, 19), 0.013627514600909, 84],[new Date(2015, 8, 26), 0.016435295994894, 103],[new Date(2015, 9, 03), 0.014991320814265, 95],[new Date(2015, 9, 10), 0.013443801782085, 86],[new Date(2015, 9, 17), 0.014195340225274, 92],[new Date(2015, 9, 24), 0.015899709524538, 104],[new Date(2015, 9, 31), 0.01468824940048, 98],[new Date(2015, 10, 07), 0.016303542315103, 110],[new Date(2015, 10, 14), 0.015366603248939, 105],[new Date(2015, 10, 21), 0.017199017199017, 119],[new Date(2015, 10, 28), 0.016353464352317, 114],[new Date(2015, 11, 05), 0.015175152460644, 107],[new Date(2015, 11, 12), 0.017195582273172, 123],[new Date(2015, 11, 19), 0.015932391244112, 115],[new Date(2015, 11, 26), 0.017364939360529, 126],[new Date(2016, 0, 02), 0.012350761630301, 90],[new Date(2016, 0, 09), 0.017178412011362, 127],[new Date(2016, 0, 16), 0.02000266702227, 150],[new Date(2016, 0, 23), 0.017802980350785, 135],[new Date(2016, 0, 30), 0.017995857068876, 139],[new Date(2016, 1, 06), 0.015858805473846, 124],[new Date(2016, 1, 13), 0.018248637688506, 144],[new Date(2016, 1, 20), 0.018827930174564, 151],[new Date(2016, 1, 27), 0.018682276746793, 150],[new Date(2016, 2, 05), 0.01676321952422, 136],[new Date(2016, 2, 12), 0.022989903904634, 189],[new Date(2016, 2, 19), 0.018874729502284, 157],[new Date(2016, 2, 26), 0.018192698982645, 152],[new Date(2016, 3, 02), 0.017251565638662, 146],[new Date(2016, 3, 09), 0.014193548387097, 121],[new Date(2016, 3, 16), 0.012823475046211, 111],[new Date(2016, 3, 23), 0.015923931721847, 139],[new Date(2016, 3, 30), 0.015510019246009, 137],[new Date(2016, 4, 07), 0.014972067039106, 134],[new Date(2016, 4, 14), 0.019345567101481, 175],[new Date(2016, 4, 21), 0.01909150757077, 174],[new Date(2016, 4, 28), 0.018032786885246, 165]        ]);
        // Set chart options
        var options = {
            animation: {startup: 'true', duration: '500'},
            annotations: {'textStyle': {'color': 'black'}, 'style': 'point'},
            chartArea: {right: '20', bottom: '70', left: '70', top: 50, height: '60%', width: '90%'},
            'title':'Rolling Year:  Trend by Week',
            'width':1500,
            'height':400,
            hAxis: {textPosition: 'out', gridlines: {color: 'transparent'}, textStyle: {fontSize: '10'}, slantedText: 'true', ticks: [new Date(2015, 4, 30), new Date(2015, 5, 06), new Date(2015, 5, 13), new Date(2015, 5, 20), new Date(2015, 5, 27), new Date(2015, 6, 04), new Date(2015, 6, 11), new Date(2015, 6, 18), new Date(2015, 6, 25), new Date(2015, 7, 01), new Date(2015, 7, 08), new Date(2015, 7, 15), new Date(2015, 7, 22), new Date(2015, 7, 29), new Date(2015, 8, 05), new Date(2015, 8, 12), new Date(2015, 8, 19), new Date(2015, 8, 26), new Date(2015, 9, 03), new Date(2015, 9, 10), new Date(2015, 9, 17), new Date(2015, 9, 24), new Date(2015, 9, 31), new Date(2015, 10, 07), new Date(2015, 10, 14), new Date(2015, 10, 21), new Date(2015, 10, 28), new Date(2015, 11, 05), new Date(2015, 11, 12), new Date(2015, 11, 19), new Date(2015, 11, 26), new Date(2016, 0, 02), new Date(2016, 0, 09), new Date(2016, 0, 16), new Date(2016, 0, 23), new Date(2016, 0, 30), new Date(2016, 1, 06), new Date(2016, 1, 13), new Date(2016, 1, 20), new Date(2016, 1, 27), new Date(2016, 2, 05), new Date(2016, 2, 12), new Date(2016, 2, 19), new Date(2016, 2, 26), new Date(2016, 3, 02), new Date(2016, 3, 09), new Date(2016, 3, 16), new Date(2016, 3, 23), new Date(2016, 3, 30), new Date(2016, 4, 07), new Date(2016, 4, 14), new Date(2016, 4, 21), new Date(2016, 4, 28)], title: 'Reporting Week', format: 'yyyy-MM-dd'},
            vAxis: {showTextEvery: '1', title: 'Percent & Count ', format: '#,###.#%'},
            legend: {position: 'top'},
            trendlines: { 0: {visibleInLegend: true, pointsVisible: false, title: 'Trend', color: 'red'} }
            };
        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.LineChart(document.getElementById('DS_Trend'));
        google.visualization.events.addListener(chart, 'ready', function () {

        console.log(DS_Trend.innerHTML);
        });
        chart.draw(data, options);
    }
    </script>


text:
Q: Picking two different random numbers fast Sometimes one requires random numbers with the condition that they are unique.
The classic algorithm is to keep looping until you hit the different numbers by chance, some pseudo code:
 minval = 0 ;
 maxval = 4 ; // random max will be one less than maxval

 val1 = random( minval , maxval ) ;
 val2 = random( minval , maxval ) ;

 while( val1 == val2 ) {

  val2 = random( minval , maxval ) ;

 }

I have a time critical and memory limited program and was wondering if there are any algorithms that avoid the continuous loop brute force method without using extra memory like a look up table.
Probably a simple solution but it's a late and tired evening here.
Any tips?

A: Yes, you can exclude the already found number like this:
 minval = 0 ;
 maxval = 4 ; // random max will be one less than maxval

 val1 = random( minval , maxval ) ;
 val2 = random( minval , maxval - 1 ) ;

 if(val2 >= val1) val2++;

The second time, specify an interval of one less than the first one, and shift the part above the already found number up by one.


text:
Q: Android: Stopping method to be called twice if already running I am trying to prevent my application calling the same method twice in the event of a double-click, or if the user presses different buttons quickly, almost at the same time.
I have clickable Views, acting as buttons, that call the same method but passing different parameters. This is the call:
startTheSearch(context, getState(), what, where);

Inside this method I'm creating a new Thread, because it queries a web server for the result:
new Thread(new Runnable() {

 public void run() {

    progDiag = ProgressDialog.show(ctx, null, "Searching", true);
    getServerXML(context, what, where, searchIsCustom, mOffset);
       handler.sendEmptyMessage(0);
 }
 }).start();

The problem is that upon two quick clicks, the method is fired twice, two threads are created, and consequently two new activities are created. That makes my app crash.
When the methods are done, and we have the result from the server, we call the handler:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
Intent i = new Intent(Golf.this, Result.class);

Bundle b = new Bundle();
b.putString("what", mWhat);
b.putString("where", mWhere);
b.putInt("offset", mOffset);
b.putBoolean("searchIsCustom", searchIsCustom);
i.putExtras(b);

startActivityForResult(i, Activity.RESULT_OK);
progDiag.dismiss();

} catch (Exception e) {
 Alerts.generalDialogAlert("Error", "settings", ctx);
}

}
};

I tried to have a global boolean variable called "blocked" initially set to false, creating a condition like:
if(!blocked){
 blocked = true;

 new Thread(new Runnable() {
  public void run() {

But this only seems to work on slower phones like the G1, I tried on Nexus and before it set blocked = true, the second request has was granted. So is there any way I can block the method being called if it's already running, or if the thread has started so it wont create a new one?

A: In the book Hello Android the author Ed Burnette gives a very nice solution for this problem.
To leave your app snappy and responsive you should create a second thread to do the web request.
Instead of creating a new thread for every request you can use a SingleThreadExecutor. If you start a second thread you can check if you are waiting for the result of another thread and block until this thread is ready, or cancel the old thread and start a new one if you think that the user now wants to do some other thing.
You can find the source code from the book on this page. Look for the Translate folder inside the source. It is a nice example on how to react to user commands and how to prevent too many web requests because of a user touching a lot on the gui.

A:
I tried on Nexus and before it set
  blocked = true, the second request has
  was granted

That is impossible. Android UIs are single-threaded. There is no way that two onClick() methods of OnClickListeners will be called at the same time.

A: Instead of using the "blocked" Boolean, you might investigate using a mutex.  They're designed for this kind of problem.


text:
Q: How to remove elements from array of dates between hours ranges Rails? My array is generated by the
   start_date = (Date.today + 10.hours + 30.minutes).to_datetime
   end_date = (Date.today + 1.day + 18.hours).to_datetime
   period = 0.5/24
   array = start_date.step(end_date, period).to_a

this is the result (but this result is going to cover max 62 days)
array =
  [Sat, 25 Feb 2023 10:30:00 +0000, Sat, 25 Feb 2023 11:00:00 +0000, Sat, 25 Feb 2023 11:30:00 +0000,
  Sat, 25 Feb 2023 12:00:00 +0000, Sat, 25 Feb 2023 12:30:00 +0000, Sat, 25 Feb 2023 13:00:00 +0000,
  Sat, 25 Feb 2023 13:30:00 +0000, Sat, 25 Feb 2023 14:00:00 +0000, Sat, 25 Feb 2023 14:30:00 +0000,
  Sat, 25 Feb 2023 15:00:00 +0000, Sat, 25 Feb 2023 15:30:00 +0000, Sat, 25 Feb 2023 16:00:00 +0000,
  Sat, 25 Feb 2023 16:30:00 +0000, Sat, 25 Feb 2023 17:00:00 +0000, Sat, 25 Feb 2023 17:30:00 +0000,
  Sat, 25 Feb 2023 18:00:00 +0000, Sat, 25 Feb 2023 18:30:00 +0000, Sat, 25 Feb 2023 19:00:00 +0000,
  Sat, 25 Feb 2023 19:30:00 +0000, Sat, 25 Feb 2023 20:00:00 +0000, Sat, 25 Feb 2023 20:30:00 +0000,
  Sat, 25 Feb 2023 21:00:00 +0000, Sat, 25 Feb 2023 21:30:00 +0000, Sat, 25 Feb 2023 22:00:00 +0000,
  Sat, 25 Feb 2023 22:30:00 +0000, Sat, 25 Feb 2023 23:00:00 +0000, Sat, 25 Feb 2023 23:30:00 +0000,
  Sun, 26 Feb 2023 00:00:00 +0000, Sun, 26 Feb 2023 00:30:00 +0000, Sun, 26 Feb 2023 01:00:00 +0000,
  Sun, 26 Feb 2023 01:30:00 +0000, Sun, 26 Feb 2023 02:00:00 +0000, Sun, 26 Feb 2023 02:30:00 +0000,
  Sun, 26 Feb 2023 03:00:00 +0000, Sun, 26 Feb 2023 03:30:00 +0000, Sun, 26 Feb 2023 04:00:00 +0000,
  Sun, 26 Feb 2023 04:30:00 +0000, Sun, 26 Feb 2023 05:00:00 +0000, Sun, 26 Feb 2023 05:30:00 +0000,
  Sun, 26 Feb 2023 06:00:00 +0000, Sun, 26 Feb 2023 06:30:00 +0000, Sun, 26 Feb 2023 07:00:00 +0000,
  Sun, 26 Feb 2023 07:30:00 +0000, Sun, 26 Feb 2023 08:00:00 +0000, Sun, 26 Feb 2023 08:30:00 +0000,
  Sun, 26 Feb 2023 09:00:00 +0000, Sun, 26 Feb 2023 09:30:00 +0000, Sun, 26 Feb 2023 10:00:00 +0000,
  Sun, 26 Feb 2023 10:30:00 +0000, Sun, 26 Feb 2023 11:00:00 +0000, Sun, 26 Feb 2023 11:30:00 +0000,
  Sun, 26 Feb 2023 12:00:00 +0000, Sun, 26 Feb 2023 12:30:00 +0000, Sun, 26 Feb 2023 13:00:00 +0000,
  Sun, 26 Feb 2023 13:30:00 +0000, Sun, 26 Feb 2023 14:00:00 +0000, Sun, 26 Feb 2023 14:30:00 +0000,
  Sun, 26 Feb 2023 15:00:00 +0000, Sun, 26 Feb 2023 15:30:00 +0000, Sun, 26 Feb 2023 16:00:00 +0000,
  Sun, 26 Feb 2023 16:30:00 +0000, Sun, 26 Feb 2023 17:00:00 +0000, Sun, 26 Feb 2023 17:30:00 +0000,
  Sun, 26 Feb 2023 18:00:00 +0000]

From this array I want to remove all the datetimes that are between beginning of each day till 10:29 o'clock and after 18:00 o'clock till the end of each the day.
Desired result:
array =
  [Sat, 25 Feb 2023 10:30:00 +0000, Sat, 25 Feb 2023 11:00:00 +0000, ....... Sat, 25 Feb 2023 18:00:00 +0000,
  Sun, 26 Feb 2023 10:30:00 +0000, Sun, 26 Feb 2023 11:00:00 +0000, ....... Sun, 26 Feb 2023 18:00:00 +0000]

I'ved tried
 w_start_time = (start_date + 8.hours + 1.minute).strftime('%k:%M:%S')
 w_end_time = (start_date - 1.minute).strftime('%k:%M:%S')

 hours = array_of_datestimes.reject! { |n| n.strftime('%k:%M:%S').between?(w_start_time, w_end_time) }

this returns  nil
Can someone help me?
Thank you

A: Here are two ways.
Convert to minutes.
array.accept! { |date| (630..1080).cover?(60*date.hour + date.min) }

where 630 = 60*10+30 and 1080 = 60*18. See Range#cover?, which only uses range end points, making it very efficient.
Count to determine which elements to keep
We see that on the first day we wish to keep the first
(18.0 - 10.5)/0.5 + 1 = 16

elements. As there are 48 30-minute intervals per day, we wish to remove the next
48 - 16 = 32

elements. We therefore may create an enumerator that generates false 16 times, then true 32 times, then repeats, where an element of array is to be removed if the corresponding value of the enumerator equals true. We can use Array#cycle to create this enumerator.
reject = ([false]*16 + [true]*32).cycle
  #=> #<Enumerator: [false, false, false, false, false, false, false,
  #     false, false, false, false, false, false, false, false, false,
  #     true, true, true, true, true, true, true, true, true, true,
  #     true, true, true, true, true, true, true, true, true, true,
  #     true, true, true, true, true, true, true, true, true, true,
  #     true, true]:cycle>

We then simply write
array.reject! { reject.next }

To illustrate this calculation suppose array held an array of strings corresponding to the DateTime elements of the given array.
array = [
  "Sat, 25 Feb 2023 10:30:00 +0000", "Sat, 25 Feb 2023 11:00:00 +0000",
  "Sat, 25 Feb 2023 11:30:00 +0000", "Sat, 25 Feb 2023 12:00:00 +0000",
  "Sat, 25 Feb 2023 12:30:00 +0000", "Sat, 25 Feb 2023 13:00:00 +0000",
  "Sat, 25 Feb 2023 13:30:00 +0000", "Sat, 25 Feb 2023 14:00:00 +0000",
  "Sat, 25 Feb 2023 14:30:00 +0000", "Sat, 25 Feb 2023 15:00:00 +0000",
  "Sat, 25 Feb 2023 15:30:00 +0000", "Sat, 25 Feb 2023 16:00:00 +0000",
  "Sat, 25 Feb 2023 16:30:00 +0000", "Sat, 25 Feb 2023 17:00:00 +0000",
  "Sat, 25 Feb 2023 17:30:00 +0000", "Sat, 25 Feb 2023 18:00:00 +0000",
  "Sat, 25 Feb 2023 18:30:00 +0000", "Sat, 25 Feb 2023 19:00:00 +0000",
  "Sat, 25 Feb 2023 19:30:00 +0000", "Sat, 25 Feb 2023 20:00:00 +0000",
  "Sat, 25 Feb 2023 20:30:00 +0000", "Sat, 25 Feb 2023 21:00:00 +0000",
  "Sat, 25 Feb 2023 21:30:00 +0000", "Sat, 25 Feb 2023 22:00:00 +0000",
  "Sat, 25 Feb 2023 22:30:00 +0000", "Sat, 25 Feb 2023 23:00:00 +0000",
  "Sat, 25 Feb 2023 23:30:00 +0000", "Sun, 26 Feb 2023 00:00:00 +0000",
  "Sun, 26 Feb 2023 00:30:00 +0000", "Sun, 26 Feb 2023 01:00:00 +0000",
  "Sun, 26 Feb 2023 01:30:00 +0000", "Sun, 26 Feb 2023 02:00:00 +0000",
  "Sun, 26 Feb 2023 02:30:00 +0000", "Sun, 26 Feb 2023 03:00:00 +0000",
  "Sun, 26 Feb 2023 03:30:00 +0000", "Sun, 26 Feb 2023 04:00:00 +0000",
  "Sun, 26 Feb 2023 04:30:00 +0000", "Sun, 26 Feb 2023 05:00:00 +0000",
  "Sun, 26 Feb 2023 05:30:00 +0000", "Sun, 26 Feb 2023 06:00:00 +0000",
  "Sun, 26 Feb 2023 06:30:00 +0000", "Sun, 26 Feb 2023 07:00:00 +0000",
  "Sun, 26 Feb 2023 07:30:00 +0000", "Sun, 26 Feb 2023 08:00:00 +0000",
  "Sun, 26 Feb 2023 08:30:00 +0000", "Sun, 26 Feb 2023 09:00:00 +0000",
  "Sun, 26 Feb 2023 09:30:00 +0000", "Sun, 26 Feb 2023 10:00:00 +0000",
  "Sun, 26 Feb 2023 10:30:00 +0000", "Sun, 26 Feb 2023 11:00:00 +0000",
  "Sun, 26 Feb 2023 11:30:00 +0000", "Sun, 26 Feb 2023 12:00:00 +0000",
  "Sun, 26 Feb 2023 12:30:00 +0000", "Sun, 26 Feb 2023 13:00:00 +0000",
  "Sun, 26 Feb 2023 13:30:00 +0000", "Sun, 26 Feb 2023 14:00:00 +0000",
  "Sun, 26 Feb 2023 14:30:00 +0000", "Sun, 26 Feb 2023 15:00:00 +0000",
  "Sun, 26 Feb 2023 15:30:00 +0000", "Sun, 26 Feb 2023 16:00:00 +0000",
  "Sun, 26 Feb 2023 16:30:00 +0000", "Sun, 26 Feb 2023 17:00:00 +0000",
  "Sun, 26 Feb 2023 17:30:00 +0000", "Sun, 26 Feb 2023 18:00:00 +0000"
]

Then
array.reject! { reject.next }
  #=> ["Sat, 25 Feb 2023 10:30:00 +0000", "Sat, 25 Feb 2023 11:00:00 +0000",
  #    "Sat, 25 Feb 2023 11:30:00 +0000", "Sat, 25 Feb 2023 12:00:00 +0000",
  #    "Sat, 25 Feb 2023 12:30:00 +0000", "Sat, 25 Feb 2023 13:00:00 +0000",
  #    "Sat, 25 Feb 2023 13:30:00 +0000", "Sat, 25 Feb 2023 14:00:00 +0000",
  #    "Sat, 25 Feb 2023 14:30:00 +0000", "Sat, 25 Feb 2023 15:00:00 +0000",
  #    "Sat, 25 Feb 2023 15:30:00 +0000", "Sat, 25 Feb 2023 16:00:00 +0000",
  #    "Sat, 25 Feb 2023 16:30:00 +0000", "Sat, 25 Feb 2023 17:00:00 +0000",
  #    "Sat, 25 Feb 2023 17:30:00 +0000", "Sat, 25 Feb 2023 18:00:00 +0000",
  #    "Sun, 26 Feb 2023 10:30:00 +0000", "Sun, 26 Feb 2023 11:00:00 +0000",
  #    "Sun, 26 Feb 2023 11:30:00 +0000", "Sun, 26 Feb 2023 12:00:00 +0000",
  #    "Sun, 26 Feb 2023 12:30:00 +0000", "Sun, 26 Feb 2023 13:00:00 +0000",
  #    "Sun, 26 Feb 2023 13:30:00 +0000", "Sun, 26 Feb 2023 14:00:00 +0000",
  #    "Sun, 26 Feb 2023 14:30:00 +0000", "Sun, 26 Feb 2023 15:00:00 +0000",
  #    "Sun, 26 Feb 2023 15:30:00 +0000", "Sun, 26 Feb 2023 16:00:00 +0000",
  #    "Sun, 26 Feb 2023 16:30:00 +0000", "Sun, 26 Feb 2023 17:00:00 +0000",
  #    "Sun, 26 Feb 2023 17:30:00 +0000", "Sun, 26 Feb 2023 18:00:00 +0000"]

This clearly works for any number of days provided the first element of the array corresponds to 10:30 on the first day. The time associated with the last element of the array is not required to be 18:00.
This calculation will be relatively fast as it does require that each DateTime element be broken down into hours and minutes.

A: Maybe you should try this :
array = array.reject { |date|
  (date.hour < 10 || (date.hour == 10 && date.min < 30)) ||
  (date.hour >= 18)
}

A: This worked for me
 w_start_time = (start_date - 1.minute).strftime('%k:%M:%S')
 w_end_time = (start_date + 8.hours - 1.minute).strftime('%k:%M:%S')

 hours = array.filter { |n| n.strftime('%k:%M:%S').between?(w_start_time, w_end_time) }


text:
Q: Define relationships for hierarchical data in Entity Framework Code First I have a hierarchical relationship defined for one of my tables where the relationship is stored in a separate join table.  The join table also contains information about the type of relationship.  The (simplified) schema looks like:
Bills
   ID int IDENTITY(1,1) NOT NULL (PK)
   Code varchar(5) NOT NULL
   Number varchar(5) NOT NULL
   ...

BillRelations
   ID int IDENTITY(1,1) NOT NULL (PK)
   BillID int NOT NULL
   RelatedBillID int NOT NULL
   Relationship int NOT NULL
   ...

I have FK relationships defined on BillID and RelatedBillID to ID in the Bills table.
I'm trying to map this in Entity Framework Code First with little success.  My classes look like the following.   Ignore the RelationshipWrapper stuff, it's a wrapper class around an enum named Relationship that corresponds to the value in the Relationship column.
public class Bill
{
     [Key]
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public int ID { get; set; }

     [Required]
     [StringLength(5)]
     public string Code { get; set; }

     [Required]
     [StringLength(5)]
     public string Number { get; set; }

     public virtual ICollection<BillRelation> RelatedBills { get; set; }

     ...
}

public class BillRelation
{
     [Key]
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public int ID { get; set; }

     public long BillID { get; set; }

     [ForeignKey("BillID")]
     public virtual Bill Bill { get; set; }

     public long RelatedBillID { get; set; }

     [ForeignKey("RelatedBillID")]
     public virtual Bill RelatedBill { get; set; }

     public RelationshipWrapper Relationship { get; set; }

     ...
 }

I've tried this in various incarnations, both using explicitly defined relationships via the ModelBuilder on the DbContext and data annotations only, but the above defines what I'm looking for.  I'm using collections because the the foreign key properties aren't primary keys.
Using this set up I get an error: Bill_ID column is not defined (or something similar).
If I got the ModelBuilder route using the following, I get an error that "The table BillRelations does not exist in the database."
modelBuilder.Entity<Bill>().HasMany( b => b.RelatedBills )
                           .WithRequired( r => r.Bill )
                           .Map( m => m.MapKey( "BillID" ).ToTable( "BillRelations" ) );
modelBuilder.Entity<BillRelation>().HasRequired( r => r.RelatedBill )
                                   .WithRequiredDependent()
                                   .Map( m => m.MapKey( "RemoteBillID" ).ToTable( "BillRelations" ) );

I have been able to make it work by defining only one half of the relationship, Bills -> BillRelations, then using a Join in my repository to fill in an [NotMapped] RelatedBill property on the BillRelations class for each of the related bills in the Bill's RelatedBills collection.  I'd rather not do this if I can help it.
The only other solution I've thought of is to model each relationship in a separate table (there are 4 types) and use a standard Bill<->Bill mapping through the join table for each of the 4 relationship types -- again I'd rather not do this if I can avoid it.
Can anyone see what I'm doing wrong or tell me if what I want to do is even possible in EF Code First 4.1?

A: Just a few ideas:

*

*Your mapping with data annotations doesn't work because EF Code First conventions don't recognize which navigation properties belong together. Obviously you want to associate Bill.RelatedBills with BillRelation.Bill. But because there is a second navigation property BillRelation.RelatedBill refering to the Bill entity as well the AssociationInverseDiscoveryConvention can't be applied to recognize the correct relation. This convention only works if you have exactly one pair of navigation properties on the entities. As a consequence, EF assumes actually three relationships, each with only one exposed end in the model. The relationship where Bill.RelatedBills belongs to assumes a not exposed foreign key on the other side according to EF default naming conventions - which is Bill_ID with underscore. It doesn't exist in the database, hence the exception.

*In your Fluent API mapping I would just try to remove ...ToTable(...) altogether. I believe that it is not necessary as the mapping knows anyway which table the foreign key belongs to. This will possibly fix the second error ("Table ... does not exist....")

*Your second mapping - the one-to-one relationship - does possibly not work as expected because one-to-one relationships are "usually" mapped with a shared primary key association between the tables in the database. (I am not sure though if shared primary keys are really required by EF.) Because your BillId column seems to be a foreign key which is not a primary key at the same time I would try to map the relationship as one-to-many. Moreover because your foreign key columns are exposed as properties in the model you should use HasForeignKey instead of MapKey:
modelBuilder.Entity<Bill>()
    .HasMany( b => b.RelatedBills )
    .WithRequired( r => r.Bill )
    .HasForeignKey ( r => r.BillID );
// turn off/on cascade delete by chaining
//  .WillCascadeOnDelete(true/false)
// here at the end

modelBuilder.Entity<BillRelation>()
    .HasRequired( r => r.RelatedBill )
    .WithMany()
    .HasForeignKey ( r => r.RelatedBillID );
// turn off/on cascade delete by chaining
//  .WillCascadeOnDelete(true/false)
// here at the end

Edit
It is possible that the whole Fluent mapping is not necessary if you put the [InverseProperty] attribute on one of the navigation properties - for example in your Bill class:
[InverseProperty("Bill")]
public virtual ICollection<BillRelation> RelatedBills { get; set; }

In this attribute you specify the name of the associated navigation property on the related entity. This binds Bill.RelatedBills and BillRelation.Bill together to a pair of navigation properties being the ends of the same association. I hope that EF will do the correct thing with the remaining navigation property BillRelation.RelatedBill, i.e. create a one-to-many relationship - I hope... If the default cascading delete won't work for you, you are forced to use Fluent API though since there is no data annotation attribute to configure cascading delete.


text:
Q: How do I update the Lotus Notes Document?
*

*For some enhancing reason, I have added some new fields in my form. It is having default value.

*But the existing document is not getting updated with the new fields.

*I am having a thousands of documents. I can not open, Edit and save. I tried to save the document from backend. I can not believe, that was also not working.

*Is their anyway for updating documents?

A: Create a view action button that executes this command:
@Command[ToolsRefreshAllDocs])

A: If you prefer using backend classes, you need call notesDocument.ComputeWithForm( False, False ) before saving document.


text:
Q: Google Fit API for Android Google Fit and Flutter
I am following this documentation from Google:
Google Fit
I don't understand step 5. I am not an Android developer and I have no idea where to locate the code. Step 5
For example, it says: Before you can invoke methods from the Google Fit APIs, you must connect to one or more of the following API clients, which are part of Google Play services:

*

*Sensors Client

*Recording Client

*History Client

*Sessions Client

*Goals Client

*BLE Client

*Config Client

Now, I try to connect the first one SensorsClient
But I don't know where to locate the code, which file? I am a flutter developer and I need help in step 5.
build.grandle
dependencies {
    implementation 'com.google.android.gms:play-services-fitness:18.0.0'
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

A: Use Google Fit Rest Api in Flutter.
Google manages the data through data sources. To see all the data sources:
https://www.googleapis.com/fitness/v1/users/me/dataSources
To get Number of Steps:
https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate
Request body:
{
    "aggregateBy" : [{
        "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
    }],
    "bucketByTime": { "durationMillis": 86400000 }, // This is 24 hours
    "startTimeMillis": 1546210381932,   // Start time
    "endTimeMillis": 1547210381932  // End Time
}

You can use fitKit which is Flutter plugin for reading health and fitness data. Wraps HealthKit on iOS and GoogleFit on Android.
    import 'package:fit_kit/fit_kit.dart';

void read() async {
  final results = await FitKit.read(
    DataType.HEART_RATE,
    dateFrom: DateTime.now().subtract(Duration(days: 5)),
    dateTo: DateTime.now(),
  );
}

void readLast() async {
  final result = await FitKit.readLast(DataType.HEIGHT);
}

void readAll() async {
  if (await FitKit.requestPermissions(DataType.values)) {
    for (DataType type in DataType.values) {
      final results = await FitKit.read(
        type,
        dateFrom: DateTime.now().subtract(Duration(days: 5)),
        dateTo: DateTime.now(),
      );
    }
  }
}

If you are writing custom platform-specific code
Before you can invoke methods from the Google Fit APIs, you must connect to one or more of the following API clients, which are part of Google Play services:

*

*Sensors Client : Client which exposes different sources of fitness data in local and connected devices, and delivers live events to
listeners.

*Recording Client : Client which enables low-power, always-on background collection of sensor data into the Google Fit store.

*History Client : Client for inserting, deleting, and reading data in Google Fit.

*Sessions Client : Client for creating and managing sessions of user activity in Google Fit.

*Goals Client : Client for reading fitness Goals created by users in Google Fit. BLE Client

*Config Client : Client for accessing custom data types and settings in Google Fit.

You must connect one of above.
    DataReadRequest readRequest = new DataReadRequest.Builder()
                .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                .bucketByTime(1, TimeUnit.DAYS)
                .enableServerQueries()
                .build();
// History Client
        Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
                .readData(readRequest)
                .addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
                    @Override
                    public void onSuccess(DataReadResponse dataReadResponse) {
                        Log.d(TAG, "onSuccess()");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "onFailure()", e);
                    }
                })
                .addOnCompleteListener(new OnCompleteListener<DataReadResponse>() {
                    @Override
                    public void onComplete(@NonNull Task<DataReadResponse> task) {
                        Log.d(TAG, "onComplete()");
                    }
                });

Example for getting Heart Rate from History Client:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessOptions;
import com.google.android.gms.fitness.data.Bucket;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataReadRequest;
import com.google.android.gms.fitness.result.DataReadResponse;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class googleFitData extends AppCompatActivity {

    private static final String TAG = "googleFitData";
    private static final int GOOGLE_FIT_PERMISSIONS_REQUEST_CODE = 2;
    private static final int PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION = 3;

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

        String[] PERMISSIONS = {
                Manifest.permission.ACTIVITY_RECOGNITION
        };

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION)
                    != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this,
                        PERMISSIONS,
                        PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION);
            }
        } else {
            googleSignin();

        }

    }

    public void googleSignin() {
        FitnessOptions fitnessOptions = FitnessOptions.builder()
                .addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ)
                .build();
        if (!GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this), fitnessOptions)) {
            GoogleSignIn.requestPermissions(
                    this, // your activity
                    GOOGLE_FIT_PERMISSIONS_REQUEST_CODE,
                    GoogleSignIn.getLastSignedInAccount(this),
                    fitnessOptions);
        } else {
            accessGoogleFit();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (GOOGLE_FIT_PERMISSIONS_REQUEST_CODE == requestCode) {

                accessGoogleFit();
            }
            if (PERMISSIONS_REQUEST_ACTIVITY_RECOGNITION == requestCode) {

                accessGoogleFit();
            }
        } else {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

        }

    }

    private void accessGoogleFit() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        long endTime = cal.getTimeInMillis();
        cal.add(Calendar.YEAR, -1);
        long startTime = cal.getTimeInMillis();

        DataReadRequest readRequest = new DataReadRequest.Builder()
                .read(DataType.TYPE_HEART_RATE_BPM)
                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                .bucketByTime(365, TimeUnit.DAYS)
                .build();

        Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
                .readData(readRequest)
                .addOnSuccessListener(new OnSuccessListener<DataReadResponse>() {
                    @Override
                    public void onSuccess(DataReadResponse dataReadResponse) {
                        Log.d(TAG, "onSuccess()");

                        for (Bucket bucket : dataReadResponse.getBuckets()) {
                            Log.e("History", "Data returned for Data type: " + bucket.getDataSets());

                            List<DataSet> dataSets = bucket.getDataSets();
                            for (DataSet dataSet : dataSets) {
                                showDataSet(dataSet);
                            }
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "onFailure()", e);
                    }
                })
                .addOnCompleteListener(new OnCompleteListener<DataReadResponse>() {
                    @Override
                    public void onComplete(@NonNull Task<DataReadResponse> task) {
                        Log.d(TAG, "onComplete()");
                    }
                });
    }

    private void showDataSet(DataSet dataSet) {
        DateFormat dateFormat = DateFormat.getDateInstance();
        DateFormat timeFormat = DateFormat.getTimeInstance();

        for (DataPoint dp : dataSet.getDataPoints()) {
            Log.e("History", "Data point:");
            Log.e("History", "\tType: " + dp.getDataType().getName());
            Log.e("History", "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
            Log.e("History", "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());

                for (Field field : dp.getDataType().getFields()) {

                    Log.e("History", "\tField: " + field.getName() +
                            " Value: " + dp.getValue(field));

                }

        }
    }

}


text:
Q: Generic array contains in C I have a small function to find if a number is in an array:
bool val_in_array(int val, int array[], size_t size)
{
    for (int i=0; i<size; i++)
        if (val == array[i])
            return true;
    return false;
}

How could I turn this into a "generic" function -- for example, one that can work on an int or float, or another type?

A: Hey that's quite the question. Let's take an example from the standard library:
void *bsearch(const void *needle, const void *array,
                     size_t nmemb, size_t size,
                     int (*compar)(const void *, const void *));

So that's an impressive header. But we can declare val_in_array as follows:
void *val_in_array(const void *needle, const void *array,
                     size_t nmemb, size_t size,
                     int (*compar)(const void *, const void *));

We're going to make our lives easier by returning a pointer to the object if found if we found any.
So as for the implementation:
{
    const char *ptr = array;
    for (int i=0; i<nmemb; i++, ptr += size)
        if (!compar(needle, ptr)
            return ptr;
    return NULL;
}

This works by advancing ptr over the input array and calling the comparison function for every element in the array. It knows how much to advance because you told it how much to advance in nmemb. Invocation is something like:
    int int_array[16];
    /* fill int_array */
    if (val_in_array(int_array, sizeof(int), 16, intcomp);

int intcomp(void *a, void *b)
{
    int aa = *(const int *)a;
    int bb = *(const int *)b;
    if (aa < bb) return -1;
    if (aa > bb) return 1;
    return 0;
}

You'll appreciate returning the pointer later. If it's not null; convert it back to the right pointer type and subtract the original array from it to get the index of the element.
    int *found = val_in_array(...);
    if (found) {
        int index = found - int_array;
        /* ... */
    } else {
        /* not found */
    }

bsearch is essnetially the same function, but for a sorted array and is much faster because it takes advantage of the array being sorted.