text:
Q: Unable to locate package ros-kinetic-depthimage-to-laserscan (On Raspberry Pi) I want to connect my microsoft kinect 360 with ROS on my Raspberry Pi3b. I've already installed Ubuntu and Ros on the Device. I follow the instructions on this link:
https://www.youtube.com/watch?v=eOUjvwyRz9U.
At the installation part
sudo apt install ros-kinetic-depthimage-to-laserscan

I get this Error:
E: Unable to locate package ros-kinetic-depthimage-to-laserscan

I hope you can help me.

A: Install rosdep and run rosdep update


text:
Q: Как сделать слайдер с меняющейся картинкой и полосой прокрутки текста? Добрый день! Нужно сверстать вот такой вот слайдер -
Я и в верстке новичок и js пользуюсь только на уровне подключения плагинов JQuery, и у меня возник вопрос как сделать такой слайдер?
Нужно чтобы при нажатии на стрелки менялась фоновая картинка и перемещался текст, который в активном состоянии становился бы оранжевым.
Интересует и как правильно разметить такой слайдер и скрипт. Может быть вы знаете сайты с такими слайдерами? Или готовые плагины, которые умеют так делать (я ничего толкового не нашла)?
Буду рада любой помощи, спасибо!
UPD: Через OwlCarusel сделала прокрутку картинки и стилизовала стрелки, но по-прежнему не понимаю как к этому добавить полосу с текстом..

A: Один из лучших готовых слайдеров это наверное Layerslider. Он может буквально все. Также отличный и стабильный слайдер OwlSlider.
Взгляните на них.

redpajama_set_name: RedPajamaStackExchange


text:
Q: EntityFramework 6 + MySQL : Model tables are not created automatically I tried to use EF6 and MySQL. I am sure the my connection to the database is working because the preferred database schema exists. However, only the __migration table exists.
I have the following codes
My Model
[Table("my_model")]
public class ModelA
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ModelAId { get; set; }

    public string ModelAProperty { get; set; }
}

My DBContext
public class ModelAContext : DbContext
{
    public ModelAContext() : base("DefaultConnection")
    {

    }

    static ModelAContext()
    {
        Database.SetInitializer( new DropCreateDatabaseIfModelChanges<ModelAContext>());
    }

    public DbSet<ModelA> MyModels { get; set; }
}

My Initializer
// Assuming this is run during the application initialization
    public static void InitializeDB()
    {
        using (var context = new ModelAContext())
        {
            if (!context.Database.Exists())
            {
                // Create the SimpleMembership database without Entity Framework migration schema
                ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
            }
            context.Database.CreateIfNotExists();
        }
    }

The corresponding table for ModelA was not created.
I always get a MySQL exception where a table (in this case app.my_model) does not exists.
Any help will be much appreciated.
P.S. If you have any good tutorial where I can setup my MySQL and EF6 in ASP.NET MVC4, it would be great. As of now, I can't seem to use the WebSecurity helper of MVC4.

A: In your Global.ascx ad
  AppDbContext db = new AppDbContext();
            db.Database.Initialize(true);


text:
Q: how to skip some rows in a multiple load with pandas I load more than 1000 files using pandas, but before that, I have to take of the first 4 lines in each file. How a can do it? I try usin skip but doesn´t work in this code below
from google.colab import files
uploaded = files.upload()

from glob import glob
import pandas as pd
dataframes = [pd.read_csv(f) for f in filesnames]
dataframes

Output:
[          Relatório Meteorológico da Estação: Guaratiba
 0     Dados normalizados para o Horário Brasileiro d...
 1     Dia         Hora      HBV   Chuva  DirVento  V...
 2                                          (graus)  ...
 3     01/03/2013  00:00:00          0.0         -   ...
 4     01/03/2013  00:15:00          0.0         -   ...
 5     01/03/2013  00:30:00          0.0         -   ...
 6     01/03/2013  00:45:00          0.0         -   ...
 7     01/03/2013  01:00:00          0.0         -   ...

A: To skip the first 3 rows, you can use the skip_rows argument of read_csv:
df = pd.read_csv(f, skip_rows=3)

You can keep all the headers by doing:
df = pd.read_csv(f, skip_rows=1) # Skip the first row, use second row as headers
df.drop(df.head(1).index, inplace=True) # Drop the first row of the dataframe

A: Please check if the following works:
dataframes = [pd.read_csv(f,skiprows=4) for f in filesnames]

A: it didn't work
I need to put the first information in a column (the first line dosen´t have index), the second line (index 0) will be remove, and de index 1 will be de header.
[          Relatório Meteorológico da Estação: Guaratiba
 0     Dados normalizados para o Horário Brasileiro d...
 1     Dia         Hora      HBV   Chuva  DirVento  V...
 2                                          (graus)  ...


text:
Q: regex time format validation: angular 2 I'm trying to add regex validation (or any better validation approach, if it exists) to validate time in the following format:
00:00:00:00 (hous:minutes:seconds:miliseconds)

none of the tutorials I saw online shows how to do this using angular 2. Can anybody point me to a nice tutorial or approach which I can follow to accomplish this?

A: Ill suggest you follow some standard like W3, you want something like this:
(?:(?:(?:(?<hh>\d{1,2})[:.])?(?<mm>\d{1,2})[:.])?(?<ss>\d{1,2})[:.])?(?<s>\d{1,2})

Its not the only answer and I encourage you to learn how to do it yourself. You can learn and test your regex expressions at https://regex101.com/

A: You can try the following regex pattern :
^((([0-1]?\d)|(2[0-3])):([0-5]?\d):([0-5]?\d):(\d?\d?\d))


text:
Q: TypeORM innerJoin table and filter by joined table This is my actual query:
const query = this.doctorsRepository.createQueryBuilder('doctor')
  .innerJoinAndSelect('doctor.services', 'services')

await query.getMany();

This is the result:
[
    {
      "id": 3,
      "created_at": "2021-09-09T14:11:09.779Z",
      "updated_at": "2021-09-09T14:11:09.779Z",
      "name": "Test Doctor Name",
      "bio": "Test Doctor Bio",
      "services": [
        {
          "id": 1,
          "created_at": "2021-08-18T17:35:52.506Z",
          "updated_at": "2021-08-18T17:35:52.506Z",
          "title": "new service by me"
        },
        {
          "id": 2,
          "created_at": "2021-08-13T15:58:01.918Z",
          "updated_at": "2021-08-13T15:58:01.918Z",
          "title": "testing service creation at night again & again"
        }
      ]
    },
    {
      "id": 2,
      "created_at": "2021-09-09T12:58:05.564Z",
      "updated_at": "2021-09-09T13:47:37.299Z",
      "name": "Doctor Name",
      "bio": "Doctor Bio",
      "services": [
        {
          "id": 26,
          "created_at": "2021-08-13T08:47:07.941Z",
          "updated_at": "2021-08-13T08:47:07.941Z",
          "title": "service 26"
        },
        {
          "id": 36,
          "created_at": "2021-08-13T08:49:22.732Z",
          "updated_at": "2021-08-13T08:49:22.732Z",
          "title": "service 36"
        },
        {
          "id": 1,
          "created_at": "2021-08-08T19:18:26.056Z",
          "updated_at": "2021-08-08T19:18:26.056Z",
          "title": "service 1"
        },
        {
          "id": 77,
          "created_at": "2021-08-13T10:12:55.529Z",
          "updated_at": "2021-08-13T10:12:55.529Z",
          "title": "testy 10"
        }
      ]
    }]

As you see, I have Doctor & Service entity that Doctor entity has Many-to-Many relation with service entity. Everything is ok until here.
But I wanna filter result by services ids, I mean I have an array of ids like this:
const servicesArray = [1, 2]

And I wanna filter result by services ids. I tested many ways but I didn't get my answer.
Note: This code didn't solve my problem:
andWhere('services.id in (:...ids)', {
  ids: servicesArray,
 })

And for better understanding this is what I expect:
Items that filtered by services ids (item that has services with the id of 1 and 2);
[
{
      "id": 3,
      "created_at": "2021-09-09T14:11:09.779Z",
      "updated_at": "2021-09-09T14:11:09.779Z",
      "name": "Test Doctor Name",
      "bio": "Test Doctor Bio",
      "services": [
        {
          "id": 1,
          "created_at": "2021-08-18T17:35:52.506Z",
          "updated_at": "2021-08-18T17:35:52.506Z",
          "title": "new service by me"
        },
        {
          "id": 2,
          "created_at": "2021-08-13T15:58:01.918Z",
          "updated_at": "2021-08-13T15:58:01.918Z",
          "title": "testing service creation at night again & again"
        }
      ]
    },
]

I also added :
query
  .addSelect('COUNT(services.id)', 'services_count')
  .groupBy('services.id')
  .addGroupBy('doctor.id');

But the problem isn't solved, because addSelect doesn't work with getMany, it works with getRawMany.


text:
Q: How to setup admob on IntelliJ Idea? It may sound that this question is a duplicate of:
How to properly configure AdMob using IntelliJ IDEA?
But it isn't! (Specially because that question is from 2011, and the google-process changed (As it seems)). I'm following this google-reference for proper setup.
First of all, there's the "Using Android Studio" option, and I have no idea of what that is. Then, I went to the next one: "Using Eclipse or another IDE", then there is a note, that was pretty straight-foward.
I've selected my project on IntelliJ Idea, pressed F4 (Open Module Settings) and went to SDKs in Platform Settings and just added the folder they asked (extras\google\google_play_services). Supposing that this is the correct way to "add the google ad library", I continued and added to the manifest file what they asked for. When I compile the app, I get the error:
D:\Computer Programming\IdeaProjects\Black Square\AndroidManifest.xml:8: error:
Error: No resource found that matches the given name (at 'value' with value '@integer/google_play_services_version').

So, as it seems, I did not import it correctly (And from this part on, I don't know how to proceed).

A: I was struggling with the same problem for a whole week. At the end, I've just ported my project to the latest Android Studio (currently 0.4.6).
Android Studio is based on IntelliJ Idea, so it has all advantages of the IntelliJ (at least as Community Edition), but at the same time has much better integration with Android SDK
I've just created a new project in Android Studio and then moved all relevant sources, resources and manifest to the newly created project.
After porting, adding admob support was as easy as adding these lines to build.gradle:
dependencies {
    compile 'com.google.android.gms:play-services:4.2.+'
}

Android Gradle Plugin automatically "explodes" references AAR of the Google Play Services into the build directory and takes all needed resources and libraries from there.


text:
Q: How does one style an HTML 5 audio player such that it always shows the progress bar in its "hover" state? I like to look at the native  player and see exactly how the song has progressed without having to hover over the progress bar of the player.
How does one style an HTML 5 audio player such that it always shows the progress bar in its mouse "hover" state?
Ideally, I'd like to just style the player with CSS. I can't seem to find how to do this.  Any of you guys or gals out there know how to do this?


text:
Q: Is JAVA_HOME fixed when executing a java command or can it be modified midcommand? Just to be clear, I DON'T WANT to change the JAVA_HOME during a java command (and take this change into account for said command), but I'm facing a situation where several java commands can be run simultaneously from some ksh scripts, and in those scripts JAVA_HOME is set (and exported) to either a 32-bits or 64-bits version before executing the java command itself.
So I am concerned there could be some "clashes" of some sort... Any advice on how to avoid any "overlaps", if they are even possible?

Note: there can potentially be a lot of script executions at the same time, and >the commands run with 32-bits version of Java cannot be run with 64-bits >version of Java for compatibility issues with other-party processes

Thanks in advance

A: JAVA_HOME is just a convention and it has no effect on the running JVM.
You can set the JAVA_HOME safely for each script, however do not use export! or you might end up with unexpected results.
Also, usually, the java application is located at JAVA_HOME/bin so you need to make sure that your script is pointing to the correct JVM 32/64.
HTH,
Gal.

A: Like all environment variables, it's fixed at the start of the command. See, for example, this question (it's about a Python program, but the same concept applies).
However, as others have pointed out, it doesn't actually have any effect on Java commands.


text:
Q: Установка приложения. Установка необходимых компонентов без интернета Я написал приложение на WPF и теперь хочу его установить на другой компьютер. Чтобы установить приложение нужно использовать установщик.
Какой установщик нужно использовать, чтобы он мог установить на компьютер необходимые компоненты для работы приложения не скачивая их с интернета? Например: .NET Framework 3.5 и т.п.

A: Попробуйте воспользоваться NSIS или Inno Setup, и при установке файлов сделайте проверку на Net Framework определённой версии если нету, то он запустит установщик Net, который необходимо скачать и запаковать в свой установщик, так-же можно свой написать, к примеру на C++, а не использовать NSIS или Inno Setup.


text:
Q: Error from meson build for a missing header which exists From this simple Meson build file I get an error on line *** about a missing header file:
# meson.build - src/

subdir('config')
subdir('testers')
subdir('utilities')

headers += [
]

mainPrj += [
    'entrypoint.cpp'
    ]

autoTest += [
    'entrypoint_test.cpp'
]

Source = [ headers, mainPrj ]
SourceTest = [ headers, autoTest ]

MyProgExe = executable('MyProg', Source)     ***
MyProgTestExe = executable('MyProgTest', SourceTest)

test('Internal test', MyProgTestExe)

This is the error message:

src/meson.build:***:0: ERROR: File dataStructures.hpp does not exist.

The header does exist, it is in directory src/config/, and it does not appear in src/meson.build file, but in src/config/meson.build:
# meson.build - src/config/

headers += [
    'dataStructures.hpp',
    'interface.hpp'
]

If I swap dataStructures.hpp and interface.hpp, I get the error with interface.hpp.
I must be doing something wrong with the meson.build files, but I cannot find what.

A: You do not need to list your header files. Just add include directories like this:
inc_dir = include_directories('path/to/include')

in your case:
inc_dir = include_directories('src/config')
MyProgExe = executable('MyProg', Source, include_directories: inc_dir, ...)

What I usually do is to declare project dependency:
project_dep = declare_dependency(include_directories: inc_dir, sources: srcs,
dependencies[...])

and use that for each target (e.g. app and test executables) like this:
src_main = ...
executable('app', sources:srcs_main, dependencies:[project_dep])
...
test_main = ...
executable('unit_tests', sources:[test_main, test_specific_srcs], dependencies:[project_dep])

A: If anybody has the same problem while building a shared_library, the answer Elvis gave also worked!
inc_dir = include_directories('src/config')
shared_library(
    ...,
    include_directories: inc_dir,
    ...,
)


text:
Q: Does there exist such a group? First Question: I was asked, "Find a group that has a subgroup of order $n$ for each positive integer $n$. I considered the nonzero complex numbers under multiplication, and noticed that the roots of the polynomial $x^n-1$ will generate a group. Is this right?
Second Question: I asked myself, "does there exist a group $G$ that has every subgroup up to isomorphism for each positive integer $n$?" For example, if we let $n=24$, there are $15$ different groups up to isomorphism. So I want the group $G$ to have $15$ subgroups of order $24$ that none of them are pairwise isomorphic. If anyone can phrase this question better, please edit my post.


text:
Q: How to initialize a boost::dynamic_bitset from std::bitset How can I initialize a boost::dynamic_bitset from std::bitset? The simplest solution is a for loop:
for(int i=0;i<bitset_size;i++)
    my_dynamic_bitset[i] = my_bitset[i];

Is there any shorter or faster way to do this?


text:
Q: Disable RadioButton inside Repeater Item I have the following Repeater which contains a radio button:
<asp:Repeater ID="RptLeaveRequests" runat="server"
        onitemdatabound="RptLeaveRequests_ItemDataBound">
<ItemTemplate>

    //displaying other data which is not relevant to qeustion

                    <asp:RadioButtonList ID="rbtVerified" runat="server" >
                        <asp:ListItem Value="1">Accept</asp:ListItem>
                        <asp:ListItem Value="2">Reject</asp:ListItem>
                    </asp:RadioButtonList>

                    <asp:TextBox ID="txtNotes" runat="server" ></asp:TextBox>

</ItemTemplate>
</asp:Repeater>

Now data is being populated from the method in the code:
DataTable dt = new LeaveLogic().GetManagerUnverifiedLeaveRequests(Convert.ToInt32(Context.User.Identity.Name));
                if (dt.Rows.Count > 0)
                {
                    RptLeaveRequests.DataSource = dt;
                    RptLeaveRequests.DataBind();
                }

how can loop through each row and disable/hide radio buttons if a record retrieved from the database (and DataTable dt) called ReadOnly is true?
Should this be placed in the Repeater_ItemDataBound method or somewhere else?

A: you can use like this
<asp:RadioButtonList ID="rbtVerified" runat="server" Enabled='<%#Eval("booleanValue") %>' >

But you need to make sure that you are binding the radio button list with boolean value.


text:
Q: xCode7 StackViews inside ScrollView overlapping views this is my first job with xCode and I'm migrating an Android App to IOs. I'm attempting to create a ScrollView with some items inside of its content view. Below is a print of the Storyboard tree:

When I run the app, the items below the selected StackView, including it, do not appear correcly on the simulator. They are all overlapped at the top of the screen:

I have already double checked all the constraints, along with other properties on the views but could not find the issue. Any help will be very appreciated.
Thanks!
=========================================
Thanks, Imran. This helped me find the issue. But I still would like to understand it. As you can see from the picture below, some of the views in my storyboard have this "wAny hR" property set. Literally all the stackviews and, the Labels and Buttons which were messy. Once I remove this property and set the "Installed" one, they showed up ok. Any thoughts on that?


text:
Q: Does java have a class that represents a timer? I'd like a timer class that allows me to call:
.start()   .getElapsedTime()   .stop()   .reset()
Does Java have such a class, or do I need to use my own (which I've already written).
From a best-practice point of view, I should use the Java class libraries classes if they exist, but I'm not sure whether this one does.
Can anyone give me a link to the javadoc for this class, if it exists?

A: There's a StopWatch class in Apache Commons Lang.

To start the watch, call start(). At this point you can:

*

*split() the watch to get the time whilst the watch continues in the background. unsplit() will remove the effect of the split. At this point, these three options are available again.

*suspend() the watch to pause it. resume() allows the watch to continue. Any time between the suspend and resume will not be counted in the total. At this point, these three options are available again.

*stop() the watch to complete the timing session.

It is intended that the output methods toString() and getTime() should only be called after stop, split or suspend, however a suitable result will be returned at other points.

API links

*

*Apache Commons Lang

*org.apache.commons.lang.time.StopWatch

*The Common Java Cookbook - Measuring Time

*

*With examples and further discussion

On using libraries
Yes, most definitely you should try to use good libraries whenever you can, instead of reinventing the wheel. The value of a well-designed, well-written, well-tested library is insurmountable, and Java has lots of it. The more users it acquires, the more mature it becomes, and any kinks would usually get fixed quickly.
Related questions

*

*Most useful free third party Java libraries?

A: Java has a Timer class, but I suppose that you are looking for a StopWatch or a Chronometer. There are many implementations of these available in the net.

A: About java.util.Timer.scheduleAtFixedRate(), be aware of this bug: http://bugs.sun.com/view_bug.do?bug_id=4290274


text:
Q: Parse Byte Array in Java Currently, I am inserting XML data into a byte array using the inputstream from server. My requirement is that it needs to remove a few XML nodes in the byte array. What is the best approach? Below are options I had:

*

*Convert the byte array to an XML file and do the parsing using DOM or SAX.

*Insert the data into an XML file instead of a byte array and parse using DOM and SAX parsers.
My doubt is if there is any way to remove XML nodes in a byte array like DOM and SAX parsers. Please guide me - thanks.

A: Use jdom2 library. It is the easiest to perform any edit functionality using jdom2

https://mvnrepository.com/artifact/org.jdom/jdom2/2.0.6

A: Wrap your array to ByteArrayInputStream and pass the stream to XMLInputFactory.createXMLEventReader to create SAX parser (or to any other InputStream-consuming method).
UPD: Or better pass original inputstream ("the inputstream from server") and collect your XML filter output to byte array.


text:
Q: Android: Getting notified when a screen capture is done Is there any way to get notified when a screen capture is performed using the soft key or the device hard key on android? Any way that works 2.3 onwards will help greatly.
Use case:
I already block screen capture using FLAG_SECURE. I want to show a Custom Dialog to the user when this action is performed. Android supplied mechanisms vary. Sometimes a notification is seen while at others, a blank screenshot is captured with no user feedback.

A:
Is there any way to get notified when a screen capture is performed using the soft key or the device hard key on android?

No, sorry.


text:
Q: Facebook Audience SDK I am trying to display Banner Ads in any of my android Apps the last couple of weeks.
I do get the Test-Banner if I add my device as testdevice.
I do get Interstitial Ads
But I do not get any Banner.
Logcat gives me "I/Facebook Error﹕ frequent load" on any of my devices (5 tested), also tested deifferent advertiser ids from facebook.
Does anybody else have this issues?
EDIT:
After installing the facebook app on any of these test devices I do get Banner Ads delivered.
Why do they only deliver ads to users with the facebook ad installed?

A: The Audience Network requires the fb app to be installed on the device to delivery ads as described here: https://developers.facebook.com/docs/audience-network/faq#a12. There's also a minimum time interval in between ad requests made from the same placement. If you make a new request within that interval, you'll see the frequent load error. Hope this helps!


text:
Q: How to make the hover affect when I move the cursor away from the button Hey I am using some codeto create hover effect on a button but for some reason when I move the cursor away from the button the reversed affect doesn't happen and the button returns to normal immediately, how can I make the reversed effect when I move the cursor away from the button?
here is the code I used:
#sides:hover {
  background-color: rgb(122, 131, 251);
  transition-duration: 0.9s;
  color: rgb(255, 255, 255, 1);
  opacity: 75%;
  cursor: pointer;
}

A: You should use transition-duration this way:
#sides {
  transition-duration: 0.9s;
}


text:
Q: Android can't connect to a Google Cloud Server using JSch I'm struggling already for a few days with a connection issue using JSch in Android app.
At First, I tried using user & password but got com.jcraft.jsch.JSchException: Auth fail
Here is the code I used for:
try {
    String command = "ls -la";
    String hostname = "host_ip";
    String user = "xxxxx";
    String password = "yyyyy";

    JSch jsch = new JSch();
    Session session = jsch.getSession(user, hostname, 22);

    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setPassword(password);
    session.connect(30000);

    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);

    InputStream input = channel.getInputStream();
    channel.connect();

    System.out.println("Channel Connected to machine " + hostname + " server with command: " + command);

    channel.disconnect();
    session.disconnect();
}
catch (Exception ex) {
    ex.printStackTrace();
}

Then I thought maybe to try use private key instead a password, but not matter where I have placed id_rsa file I got com.jcraft.jsch.JSchException: java.io.FileNotFoundException: path_to_file/id_rsa (No such file or directory)
Here is the code:
try {
    String command = "ls -la";
    String hostname = "host_ip";
    String user = "xxxxx";
    String password = "yyyyy";

    String privateKey = "path_to_file/id_rsa";

    JSch jsch = new JSch();
    jsch.addIdentity(privateKey);
    Session session = jsch.getSession(user, hostname, 22);
    session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(30000);

    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);

    InputStream input = channel.getInputStream();
    channel.connect();

    System.out.println("Channel Connected to machine " + hostname + " server with command: " + command);

    channel.disconnect();
    session.disconnect();
}
catch (Exception ex) {
    ex.printStackTrace();
}

I have read a lot of articles and different posts in Stackoverflow but nothing helped.
Thanks in advance.


text:
Q: Failed String Parsing to LocalDateTime using DateTimeFormatter I am trying to parse a simple string [08/May/2020:09:14:05 +0000] to LocalDateTime using DateTimeFormatter and LocalDateTime but it seems that it does not work for some reasons. I have tried different changes to the format like DD, hh, X, x, or Z but it doesn't work.
Here is the code:
String log = "[08/May/2020:09:14:05 +0000]";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[d/MMM/yyyy:HH:mm:ss x]");
LocalDateTime odt = LocalDateTime.parse(log, fmt);
System.out.println(odt);

Any guess?

A: All credit goes to Andreas. His suggestion in the comments is good enough to be posted as an answer.
    String log = "[08/May/2020:09:14:05 +0000]";
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("'['dd/MMM/uuuu:HH:mm:ss xx']'", Locale.US);
    LocalDateTime odt = LocalDateTime.parse(log, fmt);
    System.out.println(odt);

Output is:

2020-05-08T09:14:05

In the format pattern string the square brackets [ and ] are (usually) used to enclose optional parts of the format. Since you want to specify that literal square brackets are in the date-time string, enclose them in apostrophes in the format pattern string. This cancels the meaning that the brackets have otherwise.
Also use xx for UTC offset with hours and minutes without colon such as +0000.
Finally always specify locale when the string includes locale sensitive parts such as a month abbreviation. In this case I think that any English-speaking locale will work, including Locale.ENGLISH, Locale.ROOT, Locale.UK, Locale.US and many others.

A: Get rid of the square brackets.  And add another x to the timezone format.
log = log.replaceAll("\\[", "");
log = log.replaceAll("]", "");
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[d/MMM/yyyy:HH:mm:ss xx]");

You can add the brackets back in with
System.out.println("[" + odt + "]");

Also, you may want to add another 'd' to the day of the month.
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("[dd/MMM/yyyy:HH:mm:ss xx]");


text:
Q: Exceptions thrown during a Set operation in a Property are not being caught When I attempt to run a function inside of a Set clause of a Property, any exception that would arise is never caught by my global exception handler. I don't understand why that happens. Here is my code (3 parts)
MainWindow.xaml.cs
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel_();
    }
}

public class ViewModel_ : INotifyPropertyChanged
{
    public ViewModel_()
    {
    }

    public string Texting
    {
        get { return _Texting; }
        set
        {
            _Texting = value;
            OnPropertyChanged("Texting");
            throw new Exception("BAM!");
        }
    }
    private string _Texting;

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

MainWindow.xaml
<Window x:Class="TestExceptionHandling.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox Text="{Binding Path=Texting,
        UpdateSourceTrigger=PropertyChanged}" />
</Grid>

App.xaml.cs (where global exception handler is)
public partial class App : Application
{
    public App()
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        MessageBox.Show("SOMETHING IS WRONG!");
    }
}

A: As said by Bob Horn, binding properties don't blow up, if they are coming from target element(TextBox) i.e. from your View. Look into your output window, you will see message something like this -
A first chance exception of type 'System.Exception' occurred in WpfApplication4.exe
An exception of type 'System.Exception' occurred in WpfApplication4.exe but was not handled in user code
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=Name; DataItem='VM' (HashCode=28331431); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') Exception:'System.Exception: BAM!

But, try setting the same property from your ViewModel's constructor, application definitely gonna blow up.
As a side note, this is not valid for all exception's, try doing this -
public string Texting
{
    get { return _Texting; }
    set
    {
        _Texting = value;
        OnPropertyChanged("Texting");
        throw new StackOverflowException("BAM!");
    }
}

This will definitely caught up by your global exception handler since application can't be run in StackOverflow mode.


text:
Q: How to sort unanswered questions by date? I saw the answer to this question, but no where mentioned about sorting by date which I am asking in this question.
How to sort unanswered questions by date?

A: If you are referring to date asked, you can search answers:0 (add [tagname] to the search if you wish to search by tag) and then select the "newest" tab. Here is a link to an example of that search method pre-done. If you want to search by date of lastest activity instead of date asked, do the steps above and use the "active" tab instead of the "newest" tab.


text:
Q: Closing an App on Mac using Ruby code I can open an app using
file_to_open = "/Applications/Revu.app"
system %{open "#{file_to_open}"}

But I'm not sure how to write the code to close it using Ruby. Any help is appreciated.

A: Shell out to AppleScript:
system %{ osascript -e 'tell application "Revu" to quit'}


text:
Q: Frontend Form Checkbox Update ACF Field I've got a frontend form with text, select and checkbox inputs the text and selects update and work just fine, using update_post_meta() however the checkboxes aren't updating. Since they're stored in a serialized array do I need to use a different function or just set it up differently?
update_post_meta($post_id, 'appliances', esc_attr(strip_tags($_POST['customMetaAppliances[]'])));

Here's the code to output the checkboxes on the frontend as well, which is working perfectly, its just that the checked options aren't saving to the database.
<?php

$allCheckbox = get_field('appliances'); //Checked value from backend

$field_key = "field_5a0a1264370c0"; //Get value using key
$post_id = get_the_ID();
$field = get_field_object($field_key, $post_id);
$count = 0;
foreach($field['choices'] as $lab => $val){
if(is_array($allCheckbox) && in_array($val, $allCheckbox)){
    $checked = 'checked = "checked"';
    //$enable = '';
} else {
    $checked = '';
    //$enable = 'disabled=""';
}
?>

<input type="checkbox" name="customMetaAppliances[]" id="customMetaAppliances" value="<?php echo $lab; ?>" <?php echo $checked; ?> /><?php echo $val; ?>

<?php
    $count++;
    if ($count == 3) {
        echo '

';
        $count = 0;
    }
} ?>

When viewing the row within the database this is whats being passed, so the array of checkboxes is being ignored?

UPDATE:

So this makes sense but it seems the array from name="customMetaAppliances[]" isn't being passed from the checkboxes? What do you guys think?

A: To be compatible with ACF you should first find out how ACF is saving checkboxes values to database. As I now this is serialized array. When we know that we must save our frontend checkboxes in the same way. The good news is you can pass only array to update_post_meta and WordPress will take care of serialization.
The problem with your code is that you probably not passing array of checkbox values. You should investigate this part: esc_attr(strip_tags($_POST['customMetaAppliances[]'])).
Two things which bother me here:

*

*esc_attr and strip_tags functions are expecting string as argument not an array they may return unexpected results

*if you want to get array of checkboxes from post request you should use field name without square brackets customMetaAppliances
I think you can replace saving part with code:
$customMetaAppliances = filter_input( INPUT_POST, 'customMetaAppliances', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
update_field( 'customMetaAppliances', $customMetaAppliances, $post_id );

Personaly when I have installed ACF I use update_field instead of update_post_meta.
I created fully working class which will display form on the frontend after post content and save values to post ACF fields on submit.
class WPSE_287946_Form {

    /**
     * Class constructor
     */
    public function __construct() {

        $this->define_hooks();
    }

    public function save_form() {

        if( isset( $_POST['save'] ) ) { // Submit button

            $post_id     = filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
            $name        = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
            $color       = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
            $accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );

            update_field( 'name', $name, $post_id );
            update_field( 'color', $color, $post_id );
            update_field( 'accessories', $accessories, $post_id );

            // Redirect user because POST request on single post page will trigger 404 page.
            wp_redirect( get_permalink( $post_id ) );
        }
    }

    /**
     * Display form
     */
    public function display_form( $content ) {

        $name        = get_field( 'name' );
        $color       = get_field( 'color' );
        $accessories = get_field( 'accessories' );

        ob_start();

        ?>

        <form method="post">

                <?php $this->display_text( 'name', 'Name', $name ); ?>

                <?php $this->display_select( 'color', 'Color', $this->get_available_colors(), $color ); ?>

                <?php $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories ); ?>

                <input type="hidden" name="id" value="<?php esc_attr_e( get_the_ID() ) ?>">
                <input type="submit" name="save" value="Submit" />

        </form>

        <?php

        $output = ob_get_contents();
        ob_end_clean();

        return $content . $output;
    }

    /**
     * Display text field
     */
    private function display_text( $name, $label, $value = '' ) {
        ?>
        <?php esc_html_e( $label, 'wpse_287946' ) ?>
        <input type="text" name="<?php esc_attr_e( $name ) ?>" value="<?php esc_attr_e( $value ); ?>">
        <?php
    }

    /**
     * Display select field
     */
    private function display_select( $name, $label, $options, $value = '' ) {
        ?>
        <?php esc_html_e( $label, 'wpse_287946' ) ?>
        <select name="<?php esc_attr_e( $name ) ?>">
            <?php $this->display_options( $options, $value ); ?>
        </select>
        <?php
    }

    /**
     * Display options
     */
    private function display_options( $options, $value ) {

        foreach( $options as $option_value => $option_label ):
            $selected = ( $option_value === $value ) ? ' selected' : '';
            ?>
            <option value="<?php esc_attr_e( $option_value ) ?>"<?php esc_attr_e( $selected ) ?>><?php esc_html_e( $option_label, 'wpse_287946' ) ?></option>
            <?php

        endforeach;
    }

    /**
     * Display checkboxes field
     */
    private function display_checkboxes( $name, $label, $options, $values = array() ) {

        $name .= '[]';

        ?>
        <?php esc_html_e( $label, 'wpse_287946' ) ?>
        <?php

        foreach ( $options as $option_value => $option_label ):
            $this->display_checkbox( $name, $option_label, $option_value, $values );
        endforeach;
    }

    /**
     * Display single checkbox field
     */
    private function display_checkbox( $name, $label, $available_value, $values = array() ) {
        $checked = ( in_array($available_value, $values) ) ? ' checked' : '';
        ?>

            <input type="checkbox" name="<?php esc_attr_e( $name ) ?>" value="<?php esc_attr_e( $available_value ) ?>"<?php esc_attr_e( $checked ) ?>>
            <?php esc_html_e( $label, 'wpse_287946' ) ?>

        <?php
    }

    /**
     * Get available colors
     */
    private function get_available_colors() {

        return array(
            'red' => 'Red',
            'blue' => 'Blue',
            'green' => 'Green',
        );
    }

    /**
     * Get available accessories
     */
    private function get_available_accessories() {

        return array(
            'case' => 'Case',
            'tempered_glass' => 'Tempered glass',
            'headphones' => 'Headphones',
        );
    }

    /**
     * Define hooks related to plugin
     */
    private function define_hooks() {

        /**
         * Add action to save form
         */
        add_action( 'wp', array( $this, 'save_form' ) );

        /**
         * Add filter to display form
         */
        add_filter( 'the_content', array( $this, 'display_form' ) );
    }
}

new WPSE_287946_Form();

A: Shouldn't the name of the checkbox be name="customMetaAppliances[]" ? That way you get an array of them in $_POST.
now you're passing just the value of last one in the form, if it's not checked it's empty, and not saved.


text:
Q: How can I make this bash script create a file owned by a regular user? I have a simple bash program, file structure is:
$ tree
.
├── includes
│   └── vimrc.vim
└── test_sourcing_vimrc.sh

.
file: test_sourcing_vimrc.sh

#! /bin/bash

self_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

sudo -s -u lando cat includes/vimrc.vim > test_output

.
file: includes/vimrc.vim (contains a .vimrc content)

" vim settings

set number
set laststatus=2
syntax enable

My intention is to

*

*run the script as a root user (the script needs these privileges for other reasons) e.g.
sudo ./test_sourcing_vimrc.sh

*sudo to a non-root user "lando" - who already exists

*cat the contents of includes/vimrc.vim into a new file test_output

*test_output should be owned by "lando" but its owned by root, e.g.
-rw-r--r-- 1 root    root     5620 Sep 24 19:00 test_output
How can I get this script to create a file owned by correct non-root user?

A: Another solution is:
sudo install -o lando -m0775 -p -S includes/vimrc.vm test_output

The -m0775 sets the permissions that the copied file receives; these permissions are actually the default so that can be omitted if they're the ones you want. The -p makes the modification time of the copied file be the same as the original. The -S makes it that if test_output already exists, it doesn't get clobbered unless the install has already successfully managed to copy the source file. Depending on your needs, these may be unnecessary. I'm noting them anyway for others who may come across this question and have somewhat different needs.
Finally, since the containing script is already being run as root, you can omit the initial sudo.

A: solved
changed
sudo -s -u lando cat includes/vimrc.vim > test_output

to
sudo -s -u lando <<EOF
cat includes/vimrc.vim > test_output
EOF


text:
Q: write/generate xml from the given xml schema I have to send data to some external service in xml format.
They have provided xml schema as below,
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.
w3.org/2001/XMLSchema">
<xs:element name="TRANSACTION">
<xs:complexType>
<xs:sequence>
<xs:element name="LOGIN">
<xs:complexType>
<xs:sequence>
<xs:element name="USERID" type="xs:string" />
<xs:element name="PASSWORD" type="xs:string" />
<xs:element name="TRANID" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="CUSTOMER">
<xs:complexType>
<xs:sequence>
<xs:element name="CUSTSSN" type="xs:unsignedInt" />
<xs:element name="CUSTFNAME" type="xs:string" />
<xs:element name="CUSTLNAME" type="xs:string" />
<xs:element name="CUSTADDRESS" type="xs:string" />
<xs:element name="CUSTCITY" type="xs:string" />
<xs:element name="CUSTSTATE" type="xs:string" />
<xs:element name="CUSTZIP" type="xs:unsignedShort" />
<xs:element name="CUSTHOMEPHONE" type="xs:unsignedInt" />
<xs:element name="CUSTMOBILEPHONE" type="xs:unsignedInt" />
<xs:element name="CUSTEMAIL" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:element>
</xs:schema>

Based on above schema, how should I write my xml?

A: In general XSD describes a set of documents which are conformant with a schema. For most schemas there are many different documents which are valid against the schema. In your case the schema prescribes everything expect the content of the strings, so something like:
    <TRANSACTION>
        <LOGIN>
            <USERID>uu</USERID>
            <PASSWORD>pp</PASSWORD>
        </LOGIN>
 <!-- omitted some of body -->
        <CUSTOMER>
            <CUSTSSN>123</CUSTSSN>
            <CUSTFNAME>Cust</CUSTFNAME>
  <!-- omitted-->
        </CUSTOMER>
    </TRANSACTION>

would do - you should be able to fill in the bits I have left out


text:
Q: Formula to get price to sell at depending on margin $sp$ = sell price
$cp$ = cost price
$p$ = profit
$m$ = margin
So to get $p,$ we do:
$$sp - {sp\over6} - 0.08sp - 0.024sp - cp$$
or, with figures:
$$12.99 - {12.99 \over6} - 12.99 \times0.08 - 12.99 \times0.024 - 8.63$$
This gives $0.84$ profit.
To get margin, we do:
$0.84 / (12.99 / 1.2)$
This gives: $7.8\%$ margin
What would the formula be if we wanted to get the sell price / price to sell at, with a margin of $5\%$?
Apologies for the formatting, I'm new here.

A: You want:
$$\frac{p}{sp/1.2} = 0.05 \quad (1)$$
$$p= sp - {sp\over6} - 0.08sp - 0.024sp - cp \quad (2)$$
$$cp = 8.63$$
Substitute $p$ as in $(2)$ to $(1)$ and solve for $sp$

A: You say profit
$$p = s_p - \frac{s_p}{6} - 0.08s_p - 0.024s_p - c_p$$
and margin is
$$m = \frac{p}{s_p / 1.2} $$
We can simplify these two expressions to give
$$ p = \frac{547}{750}s_p - c_p \quad \text{ and } \quad m = \frac{6p}{5s_p} $$
We then substitute:
$$ m = \frac{\frac{547}{125}s_p - 6c_p}{5s_p} = \frac{547}{625} - \frac{6c_p}{5s_p} $$
Rearranging:
$$ s_p = \frac{6c_p}{\frac{547}{125} - 5m} = \frac{750c_p}{547 - 625m} $$
If margin is $5\%$ and $c_p = 8.63$ then $s_p = 12.55$.


text:
Q: Searching in a json in python I am using requests.get to get an output.[{"id": "e644b06c-8f5b-4bdf-84a0-7266dffc6979", "securityResourceId": "e48e8536-02ff-424d-856a-dab30af23919", "name": "helloWorld",  So in the name tag i need to search if it contains xyz and if it does append that name to an array.If you could help id be obliged.Thanks

A: you can add .json() to the end of a request to get a dict out of that request (if the request returned a json).
arr = []
dict = requests.get('website').json()
if 'xyz' in dict.get('name'):
    arr.append(dict['name'])

A: you can parse JSON into dictionary using json library.
after that you can search the contents with either re or fuzzywuzzy to get matching pattern.
snippet:
import json, re
input_string = '[{"test":"something"},{"xyz":"something else","foo":"bar"}]'
obj = json.loads(input_string)
arr = []
for item in obj:
   for key in item:
       match = re.match("xyz",key)
       if match is not None:
          arr.append(item)
          continue


text:
Q: How to convert array first value as key and second value as value Hi I am working on some array operations.
I need to convert first value of array as key and second value of array as value.
I have one variable $testArray which stores array like below.
 Array
(
    [0] => Array
        (
            [0] => Color
            [1] => White on Red
        )

    [1] => Array
        (
            [0] => Depicted Text
            [1] => EMPTY
        )

    [2] => Array
        (
            [0] => Depth [Nom]
            [1] => 0.004 in
        )

    [3] => Array
        (
            [0] => Language
            [1] => English
        )

    [4] => Array
        (
            [0] => Length [Nom]
            [1] => 10 in
        )

    [5] => Array
        (
            [0] => Material
            [1] => Adhesive Vinyl
        )

    [6] => Array
        (
            [0] => Mounting
            [1] => Surface
        )

    [7] => Array
        (
            [0] => Width [Nom]
            [1] => 14 in
        )

    [8] => Array
        (
            [0] => Wt.
            [1] => 0.056 lb
        )

)

Expected output :
    Array
(
    [0] => Array
        (
            [Color] => White on Red
        )

    [1] => Array
        (
            [Depicted Text] => EMPTY
        )

    [2] => Array
        (
            [Depth [Nom]] => 0.004 in
        )

    [3] => Array
        (
            [Language] => English
        )

    [4] => Array
        (
            [Length [Nom]] => 10 in
        )

    [5] => Array
        (
            [Material] => Adhesive Vinyl
        )

    [6] => Array
        (
            [Mounting] => Surface
        )

    [7] => Array
        (
            [Width [Nom]] => 14 in
        )

    [8] => Array
        (
            [Wt.] => 0.056 lb
        )

)

I have already tried with array function array_keys and array_values but it won't working

A: Assuming that structure will always be the same, you could do this:
$output = array();
foreach($testArray as $v){
    $output[] = array($v[0] => $v[1]);
}

See it in action here.

A: Simple solution using array_map function:
$result = array_map(function($v){
    return [$v[0] => $v[1]];
}, $testArray);


text:
Q: Get data from server and use it in polymer element I would appreciate some help in something I'm trying to do with Polymer.
I have an element:
<dom-module id="internal-content">
  <template>
    <style is="custom-style" include="iron-flex iron-flex-alignment iron-positioning"></style>
    <style>
      internal-menu{
        width: 20%;
        height: 100%;
      }
      internal-associates, internal-networks, internal-letter, internal-help{
        width: 80%;
        height: 100%;
      }
    </style>

    <div class="horizontal center layout">
      <internal-menu></internal-menu>

      <internal-associates id="internal-associates" data="{{userData.associates}}"></internal-associates>
      <internal-networks id="internal-networks" data="{{userData.socialNetworks}}" style="display: none"></internal-networks>
      <internal-letter id="internal-letter" data="{{userData.farewellLetter}}" style="display: none"></internal-letter>
      <internal-help id="internal-help" style="display: none"></internal-help>
    </div>

    <paper-toast-error id="errorInServer"
  text="Ha habido un problema en servidor al acceder a sus datos. Por favor, vuelva a intentarlo. Si el error persiste póngase en contacto con nosotros
  a través del email v.punzano@gmail.com">
    </paper-toast-error>

  </template>
<script>
  (function() {
    'use strict';
    Polymer({
      is: 'internal-content',
      properties: {
        userData: {
          type: Object
        }
      },

      ready: function(){
       $.ajax({
         type: "GET",
         url: "/getUserData",
         data: {firebaseID: document.querySelector('#firebaseLogin').user.uid},
         error: function(xhr, ajaxOptions, thrownError){
           document.querySelector('#errorInServer').openToast();
         },
         success: function(msg) {
           this.userData = msg;
           // return msg;
         }
       });
     }
   });
 })();

What I want to do is render the elements internal-associates, internal-networks and internal-letter with the data retrieved in the ajax call, in order to use the dom-repeat templates inside this elements to render the arrays within the data.
The problem with the code I attach here is that the elements have been registered in the DOM before the data is retrieved.
I can attached or provide more information if needed.
Regards and thanks in advance.

A: There are several issues with your code:

*

*Use iron-ajax instead of jquery: Whereas using external libraries is per se no issue, using iron-ajax can simplify your code a lot

*As pointed out by @a1626 the this in your success handler is not the Polymer object you wish to use here

*Your update code (this.userData = msg;) won't force Polymer to update the object. Use this.set('userData', msg); instead.

*If you really have issues with your Subnodes hide them while you don't have any data. See https://www.polymer-project.org/1.0/docs/devguide/templates#dom-if


text:
Q: How to horizontally align all characters like a typewriter I want to make a document that looks like an old top secret file written on a typewriter. The problem is that when I want to use a center environment, the alignment of the characters is off. Is there a way to make sure that the boxes of all the characters are aligned while still making use of the center environment?
MWE
\documentclass[a4paper]{article}

\title{Your Paper}
\author{You}

\begin{document}
\ttfamily
\raggedright
\begin{center}
Top Secret Document
\end{center}
This is a top secret document containing secret information about a secret thing which has remained secret for many years. This is a top secret document containing secret information about a secret thing which has remained secret for many years.
\end{document}

A: In response to Nathanael comment, I update my earlier answer with a more powerful method, able to cope with multi-paragraph material, pagebreaks being allowed.
The extra inter-paragraphs vertical skips (\parskip) inside the specially centered material will be lost, though. As this is usually 0pt plus some stretchable glue this effet is not very significant.
\documentclass[a4paper]{article}
\usepackage[paperheight=11cm,paperwidth=12cm,vscale=0.75,hscale=0.7]{geometry}
\usepackage{xcolor}
\usepackage{lipsum}

\title{Your Paper}
\author{You}

% from Werner's answer

\newcommand{\vmark}{\mbox{}\rlap{\smash{\color{red}\rule[-3\baselineskip]{.5pt}{4\baselineskip}}}}

\newcommand{\Vmark}{\mbox{}\rlap{\smash{\color{blue}\rule[-\baselineskip]{.5pt}{3\baselineskip}}}}

\newlength{\dimenA}
\newlength{\dimenB}

% command \CenterIt
\newcommand\CenterIt[1]{\settowidth{\dimenB}{#1}%
\noindent\hspace{\dimexpr((\linewidth-\dimenB)/2/\dimenA)*\dimenA }#1\par}

% and now a *much* fancier tool, multi-paragraph-able, and allowing page breaks.

\makeatletter
\newbox\tmpbox
\newenvironment{ttcentered}{%
  \edef\@tempa
     {\endgroup
      \setbox\z@\vbox{\setbox\tmpbox\vbox{}%
                      \noexpand\centering
                      \begingroup
                      \aftergroup\noexpand\ttcenter@
                      \aftergroup}%
                      \aftergroup\noexpand\ttcenter@post
                      \def\noexpand \@currenvir   {\@currenvir }%
                      \def\noexpand \@currenvline {\on@line }%
     }\@tempa}{}%

% remove or comment the \Vmark for real use.
\def\ttcenter@{\endgraf
  \loop
        \setbox\z@\lastbox
        \unskip\unpenalty\unskip\unpenalty
  \ifvoid\z@\else
        \setbox\tw@\hbox{\strut
\Vmark
                         \unhbox\z@}%
  \setbox\tmpbox
         \vbox{\moveright
                \dimexpr((\linewidth-\wd\tw@)/2/\dimenA)*\dimenA\relax
                \box\tw@\penalty\z@
                \unvbox\tmpbox}%
 \repeat
 \global\setbox\@ne\vbox{\unvbox\tmpbox}}

\def\ttcenter@post{\vspace{\dimexpr\baselineskip-\ht\strutbox-\prevdepth}%
                   \unvbox\@ne
                   \prevdepth\dp\strutbox}

\makeatother

\begin{document}

\ttfamily \settowidth{\dimenA}{x}

\raggedright
\CenterIt{\vmark Top Secret Document}
\CenterIt{\vmark This is a Top Secret Document}
\CenterIt{\vmark This is a truly Top Secret Document}

This is a top secret document containing secret information about a secret thing
which has remained secret for many years. This is a top secret document
containing secret information about a secret thing which has remained secret for
many years.

\begin{center}
  \begin{ttcentered}
    This is a top secret document containing secret information about a
    secret thing which has remained secret for many years. This is a top
    secret document containing secret information about a secret thing
    which has remained secret for many years.

    \lipsum[1]
  \end{ttcentered}
\end{center}

% debugging:
% \showoutput

    We check the vertical spacing induced by the center environment and
    set up some centered text without extra vertical spacing (apart from
    the \string\parskip=\the\parskip):

  \begin{ttcentered}
    This is a top secret document containing secret information about a
    secret thing which has remained secret for many years. This is a top
    secret document containing secret information about a secret thing
    which has remained secret for many years.
  \end{ttcentered}

Back to normal raggedright (to confirm absence of extra vertical
spacing; apart from \string\parskip=\the\parskip).

%\showoutput
\end{document}

First answer:
A method based on measuring things first. On each line. (\vmark copied from Werner's answer)
\documentclass[a4paper]{article}
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\newcommand{\vmark}{\mbox{}\rlap{\smash{\color{red}\rule[-3\baselineskip]{.5pt}{4\baselineskip}}}}
\usepackage{calc}
\title{Your Paper}
\author{You}

\newlength{\dimenA}
\newlength{\dimenB}

\newcommand\CenterIt[1]{\settowidth{\dimenB}{#1}%
\noindent\hspace{\dimexpr((\linewidth-\dimenB)/2/\dimenA)*\dimenA }#1\par}

\begin{document}
\ttfamily
\settowidth{\dimenA}{x}

\raggedright

\CenterIt{\vmark Top Secret Document}
\CenterIt{\vmark This is a Top Secret Document}
\CenterIt{\vmark This is a truly Top Secret Document}

This is a top secret document containing secret information about a secret thing which has remained secret for many years. This is a top secret document containing secret information about a secret thing which has remained secret for many years.
\end{document}

A: One option is to use a two-step process:

*

*Use the center environment to identify the location of the text center with respect to the other document elements.

*Use a \phantom to horizontally align and manually center the contents.

\documentclass{article}
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\newcommand{\vmark}{\mbox{}\rlap{\smash{\color{red}\rule[-3\baselineskip]{.5pt}{4\baselineskip}}}}
\begin{document}
\ttfamily\raggedright

\begin{center}
\vmark Top Secret Document
\end{center}
This is a top secret document containing secret information
about a secret thing which has remained secret for many years.
This is a top secret document containing secret information
about a secret thing which has remained secret for many years.

\hrulefill

\bigskip

\leavevmode\phantom{This is a top secret do}\vmark Top Secret Document

\bigskip

This is a top secret document containing secret information
about a secret thing which has remained secret for many years.
This is a top secret document containing secret information
about a secret thing which has remained secret for many years.

\end{document}

After the first center alignment, it is obvious that an appropriate horizontal placement would be somewhere around the c of document.


text:
Q: Add document to Firestore from Beam with auto generated ID I would like to use Apache Beam Java with the recently published Firestore connector to add new documents to a Firestore collection. While I thought that this should be a relatively easy task, the need for creating com.google.firestore.v1.Document objects seem to make things a bit more difficult. I was using this blog post on Using Firestore and Apache Beam for data processing as a starting point.
What I actually only want is to write is a simple transformation, mapping MyClass objects to Firestore documents, which are then added to a Firestore collection.
What I now ended up with is a Beam SimpleFunction, which maps MyClass objects to Documents:
public static class Mapper extends SimpleFunction<MyClass, Document> {

    @Override
    public Document apply(final MyClass record) {
      final String project = "my-project";
      final String database = "(default)";
      final String collection = "my-collection";
      final String documentId = someUnecessaryIdComputation();
      return Document
          .newBuilder()
          .setName("projects/" + project + "/databases/" + database + "/documents/" + collection
              + "/" + documentId)
          .putFields("key",
              Value.newBuilder().setStringValue(record.getValue()).build())
          // ...
          .build();
    }

  }

and a DoFn transforming these Documents to Write objects with configured update (can probably be also simplified to a SimpleFunction but was copied from the blog post):
private static final class CreateUpdateOperation extends DoFn<Document, Write> {

    @ProcessElement
    public void processElement(ProcessContext c) {
      final Write write = Write.newBuilder()
          .setUpdate(c.element())
          .build();
      c.output(write);
    }
  }

I'm using these two functions in my pipeline as follows:
pipeline.apply(MapElements.via(new Mapper()))
  .apply(ParDo.of(new CreateUpdateOperation()))
  .apply(FirestoreIO.v1().write().batchWrite().build());

The major disadvantages here are:

*

*I have to specify a document ID and can not use an auto-generated one as with the "plain" Java SDK

*I have to specify the project ID and the database name although they should be available. At least for the Java SDK, I have don't have to set them.

Is there any way to add documents using the Firestore connector without explicitly setting document ID, project ID and database?

A: I agree, this is not the most convenient API (and I don't see a better one at the moment). It seems to be designed for modifying existing documents, not creating new ones.
I think it would make sense to have a higher-level transform; I filed https://issues.apache.org/jira/browse/BEAM-13994 . In the meantime, you could do something like
class FirestoreWrite extends PTransform<PCollection<Map<String, Object>>, PDone> {
  private String projectId;  // Auto-infer from environment
  private String database = "(defaut)";
  private String collection;

  public PDone expand(PCollection<Map<String, Object>> data) {
    return data
        .apply(ParDo.of(new DoFn() {
          @ProcessElement
          public void processElement(ProcessContext c) {
            builder = Document
                .newBuilder()
                .setName("projects/" + projectId + "/databases/" + database + "/documents/" + collection + "/" + randomDocumentId());
            // [loop over data setting values from c.element()]
            c.output(builder.build());
          }
        }))
        .apply(new CreateUpdateOperation())
        .apply(FirestoreIO.v1().write().batchWrite().build());
  }
}

which would be generally re-usable and likely worth contributing to Beam.


text:
Q: Oracle SQL - Dynamic pivot Can someone please help me on this SQL query?
I have a simple table that i need to pivot dynamically. the table consists of 3 fields as below.
Table
Part_no
Forecast_date
Forecast_qty

I would like to pivot the table on forecast_date so that I would see part_no as a row, forecast_date as the column heading and forecast_qty showing for each part/date combination.
Is this possible?
[


text:
Q: jquery variable selector issue html:
<input id="input_1" type="text" value="some text"/>
<input id="input_2" type="text" value="some text"/>

js:
var input_1 = $('#input_1'),
input_2 = $('#input_2');

now I need to remove these value. So I removed value one by one.
  example:
  input_1.value('');
  input_2.value('');

but how can I remove these variables value in one line?
( without this method:  input_1.value('').end().input_2.value(''); )

A: You want to make use of add method.
input_1.add(input_2).val("");

A: $("#input_1, #input_2").val('');

A: You could try jQuery each()(https://api.jquery.com/each/)
$('input[id^='input_']').each(function( index ) {
     $(this).val(''); // reset each element value
});

FYI
input[id^='input_'] selector selects all input elements with id attribute started with 'input_' e.g input_1, input_2 etc.

A: If you want to empty the value of multiple elements, then using class selector is an option for you.
Like that :
var input_vars = $(".elementClass");
input_vars.val("");

A: Maybe via array?

var clearMe = ['input1', 'input2'];

    for (i = 0; i < clearMe.length; i++) {
        var thisClear = clearMe[i];

       $('#'+thisClear).val('');
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" name="test" value="testvalue1">
<input type="text" id="input2" name="test" value="testvalue2">
<input type="text" id="input3" name="test" value="testvalue3">

The same with variables:

var clear1 = $('#input1');
var clear2 = $('#input2');
var clearMe = [clear1, clear2];

    for (i = 0; i < clearMe.length; i++) {
       clearMe[i].val('');
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" name="test" value="testvalue1">
<input type="text" id="input2" name="test" value="testvalue2">
<input type="text" id="input3" name="test" value="testvalue3">

or.. simply:

var clear = $('#input1, #input2');
clear.val('');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" name="test" value="testvalue1">
<input type="text" id="input2" name="test" value="testvalue2">
<input type="text" id="input3" name="test" value="testvalue3">

A: Add a common class to both the textbox element and then use that class to clear the value.
$(".class").value("");

A: It works for me. Thanks everyone.
input_1.add(input_2).val("");


text:
Q: Customized validation rule on laravel form request validation I do have a registration  form in my laravel 5.4 application and laravel form request validation is used for server side validation. Some fields in this form are populated dynamically using calculations in javascript which need to be validated against user inputs.
The user input fields in the form are 'quantity', 'rate' and 'discount'.
The populated fields are 'total' and 'bill_amount'.
What i need to validate are :

*

*Check 'total' equal to 'quantity' * 'rate'.

*Check 'bill_amount' equal to 'total' - 'rate'

I would prefer laravel form request validation methods for this validation. I have tried to use methods like After Hooks and conditionally adding rule etc. and failed.

In simple words the requirement is : check if a field is equal to product of other two fields, and invalidate if not equal and validate if equal.(using form request validation.)

Thanks in advance!

A: After a long time I was able to find this solution.
Form request After Hooks can be used to achieve the result:
[I was unable to find this logic before]
public function withValidator($validator)
    {
        $quanty     = $this->request->get("quantity");
        $rate       = $this->request->get("rate");
        $billAmount = $this->request->get("bill_amount");

        $validator->after(function ($validator) {
            if(($quanty * $rate) != $billAmount) {
                $validator->errors()->add('bill_amount', 'Something went wrong with this field!');
            }
        });
    }


text:
Q: Shift array to make first and last columns adjacent I'm struggling how to explain this in the question title so I'll try better here.
I have an array which contains 360 columns and 180 rows which represents each degree of latitude and longitude on earth. For clarity, my data looks like the following:
longitudes = [0, 1, 2 ... 358, 359]
latitudes = [90, -89 ... -89, -90]
data = np.random.randint(5, (180, 360))

It looks like this, where longitude '0' is equal to 0E and '359' is equal to -1E.
As you can see, Africa is split at the start and end of the array and I would like to shift the array so that the first columns corresponds to -180E and the last columns corresponds to 180E, like the traditional world view (map) - this will make subsetting the array to 'cookie cut' Africa out.
How do I shift/transform my array so that the first and last column are adjacent?
(Extra: since you can think of my array as a cylinder, as geographically, the first and last rows are adjacent, but how do I change where the 'cylinder is cut' - the analogy I've been thinking of)

A: Solution was to use numpy.roll().
I firstly found the index of the column corresponding to 180E using:
idx = (longitude.index(180))

Then, I 'rolled' the data based on this index to move 180E to the furthest left column using:
rolled_data = np.roll(data, idx, axis=1)

This successfully centred the 0E column to create my desired output.

A: please see this answer: Efficient way to shift a list in python
Seems to do the same as you want.
From the accepted answer:
Collections.deque
from collections import deque
items = deque([1, 2])
items.append(3) # deque == [1, 2, 3]
items.rotate(1) # The deque is now: [3, 1, 2]
items.rotate(-1) # Returns deque to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3]


text:
Q: How can I manage multiple threads in Ruby on Rails (equivalent of a Java thread factory)? I'm using Ruby on Rails 5 although I'm fairly a novice to Ruby/Rails.  I have read about creating threads using
   t = Thread.new {
      sleep(rand(0)/10.0)
      Thread.current["mycount"] = count
      count += 1
   }

However, I'm wondering if there is a standard way of managing a bunch of application-created threads in Ruby/Rails.  I'm familiar with Java, which has a thread factory.  That allows a certain number of threads to concurrently run while others must wait in a queue.  I'm wondering how I would do something similar in Ruby/Rails.
Note that I'm not talking about the types of threads that are generated automatically when a web page is requested.  I'm talking about threads that I (the application owner) creates.

A: Especially if you're using ActiveRecord inside your threads, you need to be careful about concurrency issues with for example database connections leaking.
Usually if you want to launch a new thread, you want to do something asynchronously in the background without having the user's request hang on an expensive action. For this there are some great libraries like Sucker Punch and Sidekiq. I'd recommend using one of these instead of creating and managing threads manually.
Hope this helps

A: I think https://github.com/ruby-concurrency/concurrent-ruby is the most used library with utils for concurrency in ruby.
It has a lot of useful things including Thread Pools (http://ruby-concurrency.github.io/concurrent-ruby/file.thread_pools.html) which I think is what you are looking for.
Keep in mind that MRI Ruby has GIL, so you only have parallelism if your threads are waiting for IO. For heavy computation you might want to use jRuby or look elsewhere :)


text:
Q: How do I know in which countries is my app available through App Store? Each country's AppStore restricts apps by language. If I have my app's descriptions in languages A, B and C, how do I know in which countries it will become available? There seems to be no easy way of knowing this other than checking App Stores for each of the 200 countries one by one, unless I'm missing something of course.
Additionally, if I have an English description, will my app be available in countries that are restricted to British, Australian and other variations of English?

A: You can also check the availability of the application published on apple store connect, by opening the edit option for the availability of regions and countries.
The steps are as follows:

*

*Open app info on the App Store Connect,

*In the General tab select the Pricing and Availability option,

*Under the Availability section next to All Countries or regions selected, click Edit,

*The Country or Region Availability window opens. Here you can see and select the countries and regions in which the application may be available.

A: There is no such restriction per language (if there is, I would be interested about any documentation respecting that restriction).
What happens is: if you have languages A, B & C, then you need to have one that is the main language, let's say it's B. And let's say A is English, B is Portuguese and C is Spanish.
Any country that has English as their language (e.g. Australia, USA) will have A language.
Any country that has Spanish as their language (e.g. Ecuador, Spain) will have C language.
Any other country will show Portuguese language in the description.
See screenshot, where it states "Principal" that is the main language:


text:
Q: Change Splash Screen from Ionic Browser I am having the following splash screen when starting my app:

I've only run
ionic cordova platform add browser
ionic cordova build browser
my config.xml
<preference name="ScrollEnabled" value="false" />
<preference name="android-minSdkVersion" value="19" />
<preference name="BackupWebStorage" value="none" />
<preference name="SplashMaintainAspectRatio" value="true" />
<preference name="FadeSplashScreenDuration" value="300" />
<preference name="SplashShowOnlyFirstTime" value="false" />
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="3000" />
<preference name="StatusBarBackgroundColor" value="#000000" />

Appreciate the help!

A: You have to change

value='screen'

with your own image (like assets/logo.png) in the config.xml file.
You can also change defaults sizes :
<preference name="SplashScreenWidth" value="300" /> <!-- defaults to "170" -->
<preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" -->

The documentation of the splashscreen plugin : https://github.com/apache/cordova-plugin-splashscreen

A: Yes, change
value='screen'

to
value='/assets/imgs/logo.png'.

If you want to edit splash picture, go to
plugins/cordova-plugin-splashscreen/src/browser/SpalshScreenProxy.js.

There is a default route for splashscreen pic /img/logo.png, it's not functional.


text:
Q: Is there a way of making optional atributes in java? I need to code this class in java. I thought of making a bunch of constructors but i dont think thats the best way to do it. Id like to know if java has some sort of optional parameters or attributes to make this simpler.

A: You can do it with one constructor with varargs, since all fields of your class are of type String:
public class Address {
    private String street;
    private String city;
    private String postalCode;
    private String state;
    private String country;

    public Address(String... params) {
      street = params[0];
      city = params[1];
      //etc. Just take care to pass the arguments in the order you are
      //assigning them when you call the constructor. Also check the size
      //of varargs first so you don't assign arguments that don't exist.
    }

}

And then call it like so to set only the street and city:
Address adress = new Address("myStreet", "myCity");
An alternative is to have one constructor with all the arguments, and if you don't want to set a value, pass null to the constructor in place of the corresponding parameter:
Address adress = new Address("myStreet", "myCity", null, null, null);


text:
Q: BufferGeometry normals react-three-fiber I'm trying to create custom shapes. I've created a triangle, but I'm struggling to create normals in order to have the material reflect shadows. In another question using useLayoutEffect was the suggested soltuion. How is this done?
 const mesh = useRef<THREE.Mesh>(null!);

 const vertices = new Float32Array( [
    point1.x, point1.y, point1.z,
    point2.x, point2.y, point2.z,
    point3.x, point3.y, point3.z,
  ] );

  return (
    <mesh
      ref={mesh}
      position={[position.x, position.y, position.z]}
    >
      <bufferGeometry attach="geometry">
          <bufferAttribute
              attachObject={["attributes", "position"]}
              array={vertices}
              count={vertices.length / 3}
              itemSize={3}
                />
        </bufferGeometry>
        <meshPhongMaterial color={color} side={THREE.DoubleSide} />
    </mesh>
  );

A: I found a solution with:
onUpdate={self => self.computeVertexNormals()}

I'm a complete beginner on React and ThreeJs so i'm not sure yet how hooks etc should be used for effiency.
    <mesh
      ref={mesh}
      position={[position.x, position.y, position.z]}
       >
      <bufferGeometry attach="geometry" onUpdate={self => self.computeVertexNormals()}>
          <bufferAttribute
              attachObject={["attributes", "position"]}
              array={vertices}
              count={vertices.length / 3}
              itemSize={3}
                />
        </bufferGeometry>
        <meshPhongMaterial color={color} side={THREE.DoubleSide} />
    </mesh>


text:
Q: How to Dynamically bind an image from my backend server I am currently using Vue js and trying to dynamically bind images that I'm getting from my database. I'm getting my path but the images aren't showing up. My front end is on localhost:8080 and my back end on localhost:3000.
In my app.js file, I'm establishing the the public folder as the static directory,
inside that folder I have my uploads directory which is where my images are being sent to.
app.use(express.static(path.join(__dirname, 'public')))

I'm sending my images there through multer:
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public')
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname)
  }
})

This is an example of how I'm seeing the image's source code popping up on the inspector.
src="public/uploads/2020-03-27T12:16:43.535Zaaa.jpeg"

I want to be able to display them dynamically in my components, but the images aren't showing up.
I'm also using Vuex and storing them in an object inside my states.

A: I think you should access your image using the full address
src="http://localhost:3000/uploads/2020-03-27T12:16:43.535Zaaa.jpeg"


text:
Q: MYSQL select and limit by quantity of 'group by' My query is as follows:
            $query = "SELECT report,";
            $query.=    "GROUP_CONCAT(DISTINCT analyst) AS analysts, ";
            $query.=    "GROUP_CONCAT(DISTINCT region) AS regions, ";
            $query.=    "GROUP_CONCAT(DISTINCT country) AS countries, ";
            $query.=    "GROUP_CONCAT(DISTINCT topic) AS topics, ";
            $query.=    "GROUP_CONCAT(DISTINCT date) AS dates, ";
            $query.=    "GROUP_CONCAT(DISTINCT link) AS links, ";
            $query.=    "GROUP_CONCAT(DISTINCT province) AS provinces ";
            $query.=    "FROM reports GROUP BY report ORDER BY dates DESC ";

I would like for MySQL to GROUP BY report, and also to limit that number (of reports) to 10. Any suggestions?

A: Simply add LIMIT 10 to the end of your query.


text:
Q: How to download Yosemite Beta from the Beta Program? I signed up on the OS X Beta Program site to test Yosemite. Was given a redemption code and automatically directed to App Store. Redemption code was already filled into the manual input box in App Store but there was no option to download. Tried again, and App Store said redemption code already used. Can anyone suggest how I get the download?

A: Go to your Purchases in the Mac App Store. There you should see it.


text:
Q: Countable Transitive model where $\exists A\subset \omega_1\;(L[A]\vDash\, \neg CH)$ It is well known that for every subset $A\subset \omega_1$ if $V=L[A]$ then $L[A]\vDash GCH$. In particular $L\vDash \exists A\subset \omega_1\,(L[A]\vDash\, GCH)$. Nonetheless, it is also consistent with ZFC the negation of that statement. Specifically, it can be proved that there exists a model of $ZFC$ plus "$\exists A\subset \omega_1\,(L[A]\vDash\neg CH)$". My question is indeed related with this fact.
It's obviuous that the model that we want construct can't be $L$ or whatever which satisfies $V=L[A]$ for some $A\subset \omega_1$. So we would start with a countable transitive model $M$ of $V=L$ and force with the Cohen forcing $Fn((\aleph_2)^M\times\omega, 2)$ to get a generic extension $M[G]$ in which $(V\neq L\;\wedge\; 2^{\aleph_0}=\aleph_2)^{M[G]}$. Now, working in $M[G]$,  there exists $A_0\subset \omega_2$ coding a well-order of $\omega_2$ of ordertype $2^{\aleph_0}$ so if we attach $A_0$ to $L$ to bild up $L[A]$ we finally have $M[G]\vDash \exists A\subset \omega_2\,(L[A]\vDash  2^{\aleph_0}=\aleph_2)$.
Here is the point where my question arise. If now, we would force over $N=M[G]$ with the forcing $Fn(\omega,(\omega_1)^{M[G]})$ we would construct a generic extension where $\omega_2^{N}=\omega_1^{N[H]}$ so that $A_0$ is a subset (in $N[H]$) of $\omega_1$. However I'm not sure if $(L[A]\vDash  2^{\aleph_0}=\aleph_2)^{N[H]}$ is the case because I have not any information about $(2^{\aleph_0})^{N[H]}$.
So, could somebody help me to prove that in the generic extension $N[G]$ the statement $(L[A]\vDash  2^{\aleph_0}\neq\aleph_1)^{N[H]}$ holds?
Thank you so much.


text:
Q: CPU running hotter at idle when using grub boot parameters So, my laptop has been "freeze crashing" randomly (System totally unresponsive, mouse freezed, clock not going forward, no keyboard commands have any effect, and the only way to get out of it is hard rebooting using physical power button), from anywhere to a few minutes to several hours of using my computer.
So naturally, I investigated the issue and tried to find a fix. After looking at the kernel log i saw that the last logged events before freezing is several "Hardware Errors":
kernel: mce: [Hardware Error]: Machine check events logged

So, I search it up and try to find solutions. And I did, I found this post. Which basically tells me to add a few boot parameters. And it does fix the issue, I haven't had any more Hardware Errors logged, or any random freezes ever since. These are the boot parameters:
noapic pci=assign-busses apicmaintimer idle=poll reboot=cold,hard

But the issue is, now my laptop is idling at a way higher temperature when using these boot parameters. Around 70 degrees Celsius, instead of 35-40. Now, obviously I've checked System Monitor to see if there is anything taking up CPU usage, but there's nothing. It's using anywhere between 0 to 3% of CPU utilization on all 4 threads, nothing out of the ordinary.
And I know its the boot parameters causing this issue, because I've tried removing them, and after rebooting, fans aren't spinning as loudly and its idling at a normal temperature. But, the Hardware Errors are back, and so are the random freezes.
I am quite a novice at Linux stuff, so I literally have no idea what these boot parameters do. Can someone experienced tell me what it is they're doing, and why they're causing my CPU to idle so much hotter?
EDIT #1
So thanks to the help of matigo and Doug, I was told that the idle=poll parameter is disabling the idle system for the CPU, which obviously make the CPU run hotter and create more waste heat.
When removing that boot parameter, the Hardware Errors are back.
So, my freezes and Hardware Errors seem to have something to do with how the CPU switches between idle states.
My CPU is an Intel Core i7-7500U
This is the output from running grep . /sys/devices/system/cpu/cpu0/cpuidle/state*/name:
/sys/devices/system/cpu/cpu0/cpuidle/state0/name:POLL
/sys/devices/system/cpu/cpu0/cpuidle/state1/name:C1
/sys/devices/system/cpu/cpu0/cpuidle/state2/name:C1E
/sys/devices/system/cpu/cpu0/cpuidle/state3/name:C3
/sys/devices/system/cpu/cpu0/cpuidle/state4/name:C6
/sys/devices/system/cpu/cpu0/cpuidle/state5/name:C7s
/sys/devices/system/cpu/cpu0/cpuidle/state6/name:C8
/sys/devices/system/cpu/cpu0/cpuidle/state7/name:C9
/sys/devices/system/cpu/cpu0/cpuidle/state8/name:C10

So basically what I need help with is this, to get rid of these Hardware Errors and crashes without completely disabling the CPU idle system, if possible.

A: The boot parameter idle=poll basically disables the idle system, rendering idle as no-op spin cycles. So, yes you would expect a lot more waste heat becuase the CPUs never go to sleep.
Here is an example from my test server, using turbostat:
doug@s19:~$ sudo turbostat --Summary --quiet --show Busy%,Bzy_MHz,IRQ,PkgWatt,PkgTmp,RAMWatt,GFXWatt,CorWatt --interval 15
Busy%   Bzy_MHz IRQ     PkgTmp  PkgWatt CorWatt GFXWatt RAMWatt
0.01    938     558     36      1.34    0.68    0.00    0.89
0.02    800     455     36      1.33    0.67    0.00    0.89 <<< All idle states enabled
60.14   4799    109298  47      29.48   28.82   0.00    0.89 <<< transition sample
99.76   4800    180297  47      47.24   46.59   0.00    0.89 <<< All idle states disabled, except poll.
99.76   4800    180311  49      47.65   46.99   0.00    0.89
99.76   4800    180305  49      47.82   47.17   0.00    0.89

Note: the intel_pstate CPU frequency scaling driver "sees" the CPUs as busy, but top does not:
top - 19:23:43 up  7:14,  3 users,  load average: 0.00, 0.00, 0.00
Tasks: 214 total,   1 running, 213 sleeping,   0 stopped,   0 zombie
%Cpu0  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu1  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu2  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu3  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu4  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu5  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu6  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu7  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu8  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu9  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu10 :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu11 :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :  31936.7 total,  31137.0 free,    312.3 used,    487.5 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.  31227.9 avail Mem


text:
Q: Issue with Wordpress category search I made multiple custom search on my wordpress site to find post with category search. Like this:
    <select id="category-select" name="category-select">
       <option value="6">Todo</option>
       <option value="7">Spain</option>
       <option value="8">Europe</option>
       <option value="30">Rest of the World</option>
      </select>
<input type="text" id="autoc-input" name="autoc-input" autocomplete="off" placeholder="">

My form sends correctly all the parameters, for example if i search Barcelona for the category Spain i got this url:

?s=Barcelona&cat=7

I can't get any result from this query, but if i search just for my input or category. With this i got all the post from the category on the search page:

?s=cat=7

And with this all the post that contains Barcelona.

?s=Barcelona

I can't find the issue to get the results with more than one parameter. How can i fix this?

A: You can search post by modify the query using pre_get_post filter. add this code inside your functions.php file
add_filter('pre_get_posts', 'search_by_category');
function search_by_category($wp_query)
{
    if (isset($_GET['cat']) && !is_admin()) {
        $wp_query->set('category__in', array($_GET['cat']));
    }
}

Before using any query variable you must have to register/add using add_query_var.
function add_category_query_string() {

    global $wp;
    $wp->add_query_var('cat');

}

add_filter('init', 'add_category_query_string');

let me know if it works for you .

A: Wordpress search is very incomplete to do good post search. I find an answer editing search.php on the top of my template file.
$s = $_GET['s'];
$cat = $_GET['cat'];
$custom_query_args = array(
                        's' => $s,
                        'cat' => $cat,
                        'posts_per_page'   => 11,
                        'order'            => 'DESC',
                        'post_type'        => 'post',
                        'post_status'      => 'publish'
                    );

// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );

// Pagination fix
$temp_query = $wp_query;
$wp_query   = NULL;
$wp_query   = $custom_query;

Like this i got all the results of the selected category.


text:
Q: How to get non repeated element in array?    (
      "userServiceIds": "1,2,3",
      "enggServiceIds": "4,5,6,2,1",
   )

As In these array we need Only enggServiceIds only where It must not be repeated in userServiceIds
As my required result is : - 4,5,6 only
the code must be run in PHP
I have tried this code
$input = array("$data[userServiceIds]" , "$data[enggServiceIds]");
            $result = implode(',',$input);
            $str = implode(',',array_unique(explode(',', $result)));

but the result is :- 1,2,3,4,5,6
As my required result is : - 4,5,6 only

A: As the input is JSON, convert it to array first. Then using array_diff
$json = '{
  "userServiceIds": "1,2,3",
  "enggServiceIds": "4,5,6,2,1"
}';

$aData = json_decode($json, true);

$aResult = array_diff(explode(',',$aData['enggServiceIds']), explode(',',$aData['userServiceIds']));

print_r($aResult);

A: read up on array_diff
$userServiceIds = [1,2,3];
$enggServiceIds = [4,5,6,2,1];

var_dump(array_diff($enggServiceIds, $userServiceIds));

returns:
array(3) {
  [0]=>
  int(4)
  [1]=>
  int(5)
  [2]=>
  int(6)
}

live preview

A: solution:
$array1 = array(1,2,3);
$array2 = array(3,4,5,6);
$resultarray = array();
$resultarray = array_diff($array2, $array1);

result:
Array ( [1] => 4 [2] => 5 [3] => 6 )


text:
Q: Как создать папки в просмотре проекта QtCreator Проект разрастается и есть необходимость в размещение .c, .h, .ui в отдельные папки, для простоты работы.
Погуглил нашел.
Сделал и получил ошибку:
:-1: error: No rule to make target 'choicegraphwindow.ui', needed by
'ui_choicegraphwindow.h'.  Stop.

Что делал:

*

*Создал каталог choicegraphwindow

*Добавил в каталог choicegraphwindow файлы choicegraphwindow.h , choicegraphwindow.cpp , choicegraphwindow.pri , choicegraphwindow.ui

*В файл choicegraphwindow.pri давил:
# -----------------------------------------------------------
# operate objects
# -----------------------------------------------------------
# Header files
HEADERS += choicegraphwindow.h

# Source files
SOURCES += choicegraphwindow.cpp

# Form files
FORMS += choicegraphwindow.ui

*В файл .pro находящимся в корневой папки проекта добавил:
#Include file(s)
include(choicegraphwindow/choicegraphwindow.pri)

Удалил из .pro
    HEADERS += choicegraphwindow.h

    SOURCES += choicegraphwindow.cpp

    FORMS += choicegraphwindow.ui

После открыл проект выполнил qmake. При сборки получил ошибку.


text:
Q: How do I change the arrow length in a tikz file Edit:
I have the following code in which I want to change the length of arrows:
\documentclass[preview,border=2pt,2pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{shapes,backgrounds}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.shapes}
\usetikzlibrary{arrows.meta}
\tikzset{decorate sep/.style 2 args=
    {decorate,decoration={shape backgrounds,shape=circle,shape size=#1,shape sep=#2}}}
\tikzset{>={Latex[width=1mm,length=3mm]}}

\begin{document}
    \begin{tikzpicture}
    \tikzstyle{line} = [line width=.4pt]
    \tikzstyle{line1} = [->,line width=.2pt]

    \def\r{0.5pt} %define the radius of spot
    \def\ax{10.2} %define the length of x-axis
    \def\ay{4} %define the length of y-axis
    \def\x{9} %define the length of x
    \def\y{3} %define the height of T=1
    \def\z{0.7} %define the height between the arrow and label

    \draw[arrows=<->,line width=0.6pt]
    (0,\ay) coordinate node [below left] {$T$} -- (0,0) coordinate node[below] {$0$} -- (\ax, 0) coordinate node [below left] {$x$};

    \draw[line] (0,\y) -- (2,\y) -- (4,0);
    \draw[line] (2,0) -- (4,\y) -- (5,\y) -- (7,0);
    \draw[line] (5,0) -- (7,\y) -- (\x,\y);
    \draw[densely dotted] (\x,\y) -- (\x,0);

    \node[below] at (2,0) {$1.6$};
    \node[below] at (4,0) {$1.7$};
    \node[below] at (5,0) {$1.75$};
    \node[below] at (7,0) {$1.85$};
    \node[below] at (\x,0) {$2$};

    \node[left] at (0,\y) {$1$};
    \node[left] at (0,\y/2) {$0.5$};

    \draw[line1] (1.2, \y+\z) -- (1,\y);
        \node[above] at (1.2, \y+\z) {$short$};
    \draw[line1] (4.7, \y+\z) -- (4.5,\y);
        \node[above] at (4.7, \y+\z) {$medium$};
    \draw[line1] (8.2, \y+\z) -- (8,\y);
        \node[above] at (8.2, \y+\z) {$tall$};

    \end{tikzpicture}
\end{document}

I want to change length of arrows at the last three lines, e.g. "\draw[line1] (1.2, \y+\z) -- (1,\y)...", but I am not sure how to do it and need help. Thanks.

A: Like this?

Instead arrows are used modified pin in nodes placed on path of fuzzy functions. By this the diagram code is much shorter:
\documentclass[preview,border=2pt,2pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}

\begin{document}
    \begin{tikzpicture}[
aligned pin/.style args = {[#1]#2:#3}% based on https://tex.stackexchange.com/questions/367130
    {pin={[pin edge={{Straight Barb[angle=60:2pt 3]}-,
                     semithick, draw=black, shorten <=2pt},%
           coordinate,
           label={[%
                append after command={%
                node[inner sep=0pt, outer sep=0pt,%font=...
                     at=(\tikzlastnode.#2),%
                     anchor=#1,%
                    ]{#3}%
                }%
            ]center:{}}%
         ]#2:{}}%
    },
          pin distance = 7mm,
            lbl/.style = {inner sep=0pt,
                          aligned pin={[south west,xshift=-1ex]60:#1}},
           line/.style = {},
                        ]
    \def\r{0.5pt} %define the radius of spot
    \def\ax{10.2} %define the length of x-axis
    \def\ay{4} %define the length of y-axis
    \def\x{9} %define the length of x
    \def\y{3} %define the height of T=1
    \def\z{0.7} %define the height between the arrow and label
% axis
    \draw[arrows=<->,line width=0.6pt]
    (0,\ay) coordinate node [below left] {$T$} -- (0,0)   node[below] {$0$}
                                               -- (\ax,0) node[below left] {$x$};
% fuzzy functions
\draw[line width=.4pt]
    (0,\y) -- node[lbl=short] {} (2,\y) -- (4,0) node[below] {1.7}
    (2,0) node[below] {1.6}   -- (4,\y) -- node[lbl=medium] {} (5,\y)
                              -- (7, 0) node[below] {1.85}
    (5,0) node[below] {1.75}  -- (7,\y) -- node[lbl=tall] {} (\x,\y);
\draw[densely dotted] (\x,\y) -- (\x,0) node[below] {2};

    \node[left] at (0,\y) {$1$};
    \node[left] at (0,\y/2) {$0.5$};
    \end{tikzpicture}
\end{document}

A: Principle to draw shorter line as are follows from given coordinates is use the option \shorten > = <amount> (to make arrows shorten on destination coordinate) and shorten < = <amount> (to make it shorted on the start coordinate). For illustration serve the following example:
\documentclass[preview,border=2pt,2pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}

\begin{document}
    \begin{tikzpicture}
\draw[shorten > = 1cm, -Straight Barb]
            (0,0) -- (2,0);
\draw[red]  (0,0.2) -- (2,0.2);
    \end{tikzpicture}
\end{document}

This concept you can use at arrow of your choice (i.e. at last three arrows as I use in my first answer, where instead separated explicit drawn arrows and nodes above them are used pin which is in its style definition shortened for 2pt).


text:
Q: How to load multiple images dynamically in XSLT with javascript / jQuery? Normally I can find what I need here without having to post myself, but I'm stumped with this one. Go easy on me!
I have some XSLT that pulls a number of user records staff name (SharePoint 2010). I need to pass a javascript function the staff name so it can use it to create a URL for a staff image, and pass the value back to replace the image src for each of the images.
Here's some of the code I'm trying to put together:

function loadStaffPic(staffName) {

  /* Code to use staffName to retrieve loginID from
     SharePoint OM goes here and returns the variable loginID */

  var filename = loginID.replace("\\","_");
  var picURL = "http://www.mywebsite.com/images/" + filename + ".png";

  document.getElementById("StaffPic").src = picURL;
}
<xsl:template>
  <xsl:template name="dvt_1.rowview">
    <img id="StaffPic{generate-id()}" onload="loadStaffPic({@Staff_x0020_Name})" src="placeholder.png" alt="{@Staff_x0020_Name}" />
  </xsl:template>

Can I use onload in the img tag like this? And if so, how can I target the image with the generated ID?
I'm assuming some kind of a loop is required...
By the way, if there is a better jQuery option that would be even better.
If I've not put enough information please let me know.
Chris

A: Thanks Tim C for your replies - they put me on the right track to find the answer.
The answer itself was actually simple:
I changed the img onload event:
onload="loadStaffPic({@Staff_x0020_Name})"

to
onload="javascript:loadStaffPic('{@Staff_x0020_Name}')"

And now it works :)
Now on to the next issue! Thanks mate.


text:
Q: Javascript Polymer: how to break/stop function I've created an HTML webpage with some polymer in it. Now, I'm looking for a way to stop my polymer function.
My code is the following:
Polymer({
  is: 'serverenelement-app',
  leegmaken: function() {

if(this.shadowRoot.getElementById("regel1").value.length != 0 && this.shadowRoot.getElementById("radio1").checked == true) {
  this.shadowRoot.getElementById("regel1").value = "";
  this.shadowRoot.getElementById("radio1").checked = false;
}
else if (this.shadowRoot.getElementById("regel1").value.length == 0 && this.shadowRoot.getElementById("radio1").checked == true) {
  alert("Kan niet bevestigd worden.\nControlleer of de status en het tafelnummer beide zijn ingevuld.");
  break leegmaken;
  }
else if (this.shadowRoot.getElementById("regel1").value.length != 0 && this.shadowRoot.getElementById("radio1").checked == false) {
  alert("Kan niet bevestigd worden.\nControlleer of de status en het tafelnummer beide zijn ingevuld.");
  break leegmaken;
  }
}
  });

I've tried breaking it like this. I found this method on another forum, yet this doesn't work.
My console says the following:

Uncaught SyntaxError: Undefined label 'leegmaken'

Can someone tell me how to fix this problem of mine? I couldn't find a solution, which is why I'm asking here. Thanks in advance.


text:
Q: Delaying HttpResponse sending in Kestrel based web server Due to my company's applications architecture, I need to develop a Kestrel based web server. The main feature that this web server must have is that it needs to maintain a requests queue whose response will be sent at some point in the future (when another app notifies that it can be sent).
Considering that HttpContext is reused for each request, I don't think it'll be possible.
Does anyone have any idea on how I can deal with this problem?
Thanks in advance.