text:
Q: Error 462 in VBA: populate MS Word With Excel I am trying to populate word content controls using input from a spreadsheet. My code either doesn't work OR consistently work one time out of 2. I get the error 462.
Can someone help me to figure out what the problem is?
Thanks!
Private Sub Accept_Click()

Dim directory As String
Dim wrdApp As Word.Application
Dim doc As Word.Document
Dim fd As Office.FileDialog
Dim dt As String

Set wrdApp = CreateObject("Word.Application")

directory = Application.ActiveWorkbook.Path

Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd
    .InitialFileName = directory
    .AllowMultiSelect = False
    .Title = "Select doc letter"
    .Filters.Add "All", "*.*"

    If .Show = True Then
        txtfilename = .SelectedItems(1)
    End If
End With

wrdApp.Visible = True
On Error GoTo Handler

'i get error on the next line:
Set doc = wrdApp.Documents.Open(txtfilename, , False, , , , , , , , , True)

Documents(txtfilename).Activate

For Each cc In ActiveDocument.StoryRanges(wdPrimaryHeaderStory).ContentControls
    If cc.Tag = "uptitle" Then cc.Range.Text = mill_box.Text
Next

For Each cc In ActiveDocument.StoryRanges(wdMainTextStory).ContentControls
    If cc.Tag = "client" Then cc.Range.Text = TextBox1.Text & Chr(10) & TextBox2.Text _
 & ", " & TextBox3 & Chr(10) & TextBox4 & " , " & TextBox5 & Chr(10) & TextBox6
    If cc.Tag = "mill" Then cc.Range.Text = mill_box.Text

Next
ActiveDocument.Windows.Application.WindowState = wdWindowStateMaximize

Unload Me

ActiveDocument.Activate

Exit Sub
Handler:
Set wrdApp = Nothing
Set doc = Nothing
Unload Me
MsgBox "error"

End Sub

A: Interesting error!
Reading the info from this page (which was Google hit #2 for me on "error 462" - LMGTFY :) ) points to an answer discussed in a Microsoft knowledge base article:

*

*You create a Word Application object through code, and assign it to a variable.

*When you reference any of Word's Application members (like ActiveDocument) without the qualifying Application variable in front of it, VBA creates a hidden variable for it instead.

*All seems fine, since VBA can call Word through both your own variable and the hidden one.

*When you now set your own variables to Nothing, the hidden variable will still be there keeping Word alive.

*When you come around a second time, the implicit hidden variable messes things up.

Your code also accesses ActiveDocument and Documents(txtfilename) instead of your own doc and wrdApp.
I do not know if this is a solution to your problem (no time to check it through), but it seems very applicable.

A: When it goes through without an error you are unloading Me and then exiting the sub. You don't set wrdApp and doc to Nothing like you do when there is an error. If you fix that logic so those get set to nothing on a successful run does it keep happening?

A: After a few days of trial and errors, here is the code that finally get things done. Thank you for everyone for taking your time to help me in this matter.
Private Sub Accept_Click()

Dim directory As String
Dim wrdApp As Word.Application
Dim doc As Word.Document
Dim fd As Office.FileDialog

On Error Resume Next

'this part is not necessary, but end users will know they can't have other word
'docs open when working with this file.
Set wrdApp = GetObject(, "Word.Application")
Set doc = wrdApp.Documents("Welcome letter.docx")
If Error <> 0 Then
    Call Killword
End If

On Error GoTo Error_Handler

Set wrdApp = CreateObject("Word.Application")
directory = Application.ActiveWorkbook.Path
Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd
    .InitialFileName = directory
    .AllowMultiSelect = False
    .Title = "Select welcome letter"
    .Filters.Add "All", "*.*"

    If .Show = True Then
        txtfilename = .SelectedItems(1)
    End If
End With

'here is the thing: i had to instantiate the doc before making wrdapp visible.
Set doc = wrdApp.Documents.Open(txtfilename, , False, , , , , , , , , True)
  wrdApp.Visible = True
doc.Activate

'from now on I have no choice than to refer to doc (not documents(1) or activedocuments! neither work)
For Each cc In doc.StoryRanges(wdPrimaryHeaderStory).ContentControls
    If cc.Tag = "uptitle" Then cc.Range.Text = mill_box.Text
Next

For Each cc In doc.StoryRanges(wdMainTextStory).ContentControls
'here goes the code i need to execute on my word document. can be anything.

Next
doc.Windows.Application.WindowState = wdWindowStateMaximize

Unload Me

Exit Sub

Error_Handler:
    Select Case Err.Number
        Case 429, 91
            Err = 0
            Resume Next
        Case Else
            MsgBox ("An unexpected error has occured." & vbCrLf & vbCrLf & _
            "Error number: " & Err.Number & vbCrLf & "Error description: " & Err.Description)
            Resume Next
    End Select

'Set wrdApp = Nothing
'Set doc = Nothing
Unload Me

End Sub


text:
Q: Grid and limit issues with Matplotlib I was trying to create a sinewave graph using Matplotlib for the parameters given as below.

Create a figure of size 12 inches in width, and 3 inches in height.
Name it as fig.
Create an axis, associated with figure fig, using add_subplot. Name it
as ax.
Create a numpy array t with 200 values between 0.0 and 2.0. Use the
'linspace' method to generate 200 values.
Create a numpy array v, such that v = np.sin(2.5np.pit).
Pass t and v as variables to plot function and draw a red line passing
through the selected 200 points. Label the line as sin(t).
Label X-Axis as Time (seconds).
Label Y-Axis as Voltage (mV).
Set Title as Sine Wave.
Limit data on X-Axis from 0 to 2.
Limit data on Y-Axis from -1 to 1.
Mark major ticks on X-Axis at 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4,
1.6, 1.8, and 2.0.
Mark major ticks on Y-Axis at -1, 0, and 1.
Add a grid, whose linestyle is '--'.
Add a legend.

Wrote the below and it almost came as required, but the expected graph is slightly different to what i write. I did gave the x and y limits but the graph seems to be taking further than that.
import numpy as np
import matplotlib.ticker as ticker
fig = plt.figure(figsize=(12,3))
ax = fig.add_subplot(111)
t = np.linspace(0.0,2.0,200)
v = np.sin(2.5*np.pi*t)
ax.set(title='Sine Wave', xlabel='time (seconds)', ylabel='Voltage (mV)', xlim = (0,2), ylim=(-1,1))
xmajor = [0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
ymajor = [-1,0,1]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(xmajor))
ax.yaxis.set_major_formatter(ticker.FixedFormatter(ymajor))
plt.plot(t, v, label='sin(t)',color = 'red')
plt.legend()
plt.rc('grid', linestyle='--', color='black')
plt.grid(True)

plt.show()

My plot and expected:

couple of points here

*

*The axis is not limiting to what i provided

*the grid seems to be different.

Any ideas how to fix this please.
Updated Picture:

A: Your problem is with ticker.FixedFormatter. First, consider this solution:
import numpy as np
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,3))
ax = fig.add_subplot(111)
t = np.linspace(0.0,2.0,200)
v = np.sin(2.5*np.pi*t)
ax.set(title='Sine Wave', xlabel='time (seconds)', ylabel='Voltage (mV)', xlim = (0,2), ylim=(-1,1))
plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0])
plt.yticks([-1, 0, 1])
plt.plot(t, v, label='sin(t)',color = 'red')
plt.legend()
ax.grid(color='black', linestyle='--', dashes=[8, 6], alpha=0.5)
plt.grid(True)

plt.show()

which results the following graph:

Notice I changed ax.xaxis.set_major_formatter to plt.xticks which allows you directly to manipulate xticks.
You used FixedFormatter, which means the ticks location are fixed and you just name them - that's why the first 3 ticks on yaxis where -1, 0, 1 (your input), regardless of what their values was. Unless you have a good reason to use matplotlib.ticker (aka set locations of ticks or format them) I recommend to use simple plt.xticks to set the values of them.
Second change was to directly control the grid by using ax.grid instead of drawing a rectangle, which I believe is more correct. As you were pretty specific in your request on the dashed line (default "--" is different then what you ask for) I added dashed=[float, float] param. It allows you control the size of the dashes - you can maniputlate them as desired. The alpha param was added to give it more 'greyish' style but you can remove it

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between btrfs raid1 and btrfs -m dup -d dup on a single device I've been using btrfs for about two years on multiple devices.
I am planning to test some btrfs configurations on a HDD (Single platter) which has non reliable sectors. A dozen of sectors on the HDD are sometimes not readable.
Would there be any difference in terms of data integrity and overall read and write speed in these setups:
1 TB HDD
-1 TB btrfs partition created with `mkfs.btrfs -d dup -m dup /dev/sda1`

1 TB HDD
-500 GB partition
-500 GB partition
--500 GB btrfs Raid 1 `mkfs.btrfs -m raid1 -d raid1 /dev/sda1 /dev/sda2`

A: I would suggest using the variant with dup instead of putting multiple partions on the same device and raiding those. The raid variant is bad because the raid requests both copies to be read while data is accessed (this is good for normal multi-device raid because if either device is faster the data is available sooner). With single device rotational device this causes read head to skip between different partitions so if you have multiple requests in the queue (the usual case) you end up with really bad performance. Increasing queue depth and CFQ scheduler can reduce overall latency a bit but it's better to avoid that mess.
The dup variant should be sane enough to read only one copy usually and only fallback to another copy if sector is not readable.
I'm not sure about dup implementation but I would guess that dup does not put the copy 1/2 device away from the first copy so dup probably increases the write performance, too. With single device raid the write performance will be bad, too, because one logical write operation needs to be written in two locations on physical rotational device and the difference is always 1/2 device so you end up with an algorithm that practically implements the overall worst case behavior for a rotational device.

A: One difference between DUP and RAID1 i can think off:

*

*If you have (like me) some SSDs that when not being used start to say that random sectors are not readable

*Then DUP can be PANIC, since one of that non readable sectors on the BTRFS partition header and BTRFS can not mount, read, etc. anything stored on it. While with RAID1 you mount the other (if there is not one of that non readable sectors on the other BTRFS partition header) and do a scrub to re-write non readable sectors.

*RAID1 implies two partitions each one with its header, so if one header got damaged (re-format partition), and the other partition header is correct, you can mount the other partition and acces on degraded mode and fix it (add another new partiton, delete the missing one, balance on RAID1 level)

Now my personal story with KingDian SSDs, that suffer form random non readable sectors after a long period of time (more than eigth days) without power; and how BTRFS RAID1 can come in save and let use such SSDs (until a collision on non readable sectors).
First i want to say thanks to BTRFS and its DUP (i will test it in a near future) and RAID1 (already tested with perfect results); it let me use my SSDs from brand KingDian. For brands Yucun and Samsung i do not yet see the "non readable sectors" problem that shows all three SSDs from brand KingDian.
I have in use a total of 11 SSDs, one KingDian died, so i only use now 10) and one KingDian 1TiB SSD that i am afraid to start using it (i was planing to use it in FAT32 or NTFS for TV playback my legally buy DVDs converted to H.264/2xAAC).
The problem with KingDian SSDs is really weird so i will tell what i do step by step to see the problem:

*

*Create a partition for only a 90% and format it, till some days ago i used Ext4 (Linux) / NTFS (Windows System partition); i really hate Windows but i am forced to used it.

*Install system on that partition

*Use the system every day --> No problem shown

*Power off and leave it of for more than eigth days --> Problem appears on KingDian SSs

*To see the problem i boot with a Live Linux distro (DVD / USB / etc), i mainly use SystemRescueCD, but any other that has "ntfsclone" / "partclone.*" / "partimage" or just a plain "dd" will serve

*I do a clone of the partition saving as a file (like saving system partition on BackUp media)

*The problem appear, there are some sectors (between a few upto near 25 or 30)  that are not readable

*I take note (on a paper) what sectors are not readable

*Now the weird thing begins, i correctly power off and leave it off for another eigth or more days

*I repeat steps 4 to 7 to see what sectors are now not readable, the list changes a lot, most times both lists have no one in common, so all non readable sectors had become readable and others that were readable now are not readable

*I can repeat this a lot of times (with no write to the SSD at all) and all lists of non-readable sectors tend to not have any sector in common (among sometimes one is on two lists)

Why this SSDs (only with Brand KingDian) do such ugly and weird thing? randomly say some sectors are not readable after a long period (more than eigth days) without power supply, and after another period (more than eigth days) without power supply they became readable again.
The top weird is that after being non readable and then become readable again, they all allways have the correct data.
Also more, i consult SMART data and it says that there is no new reallocated sector (it has some because i once used on Windows a tool to force reallocation of non readable sector).
SMART info also says there is no read error, while some sectors are not readable, and also says there is no write error.
Obviously there is no "read" error, nothing "read" with "wrong" data... that is technically different to not been able to read... and SMART data has no field i can see that shows a non readable error count... etc.
By the way, if i re-write non readable sectors with data, they become readable again without any sector been re-mapped, maybe because the internal ones that are used are not the failing ones (remember SSD on writes uses different places to extend the live, SSD uses an internal map LBA - Real position inside chips).
By the way, cloning a partition with 30GiB  of data on it and without that problem only took less than a minute (the SSD can read at 550MiB/s sustained while cloning the partition, aka, mostly secuential reads); but with 25 non readable sectors it took more than 24 hours (with ignoring such errors or else it does not end) and it will have some "corrupted" data (the one could not been read).
Here is where BTRFS cames in saving me:

*

*Firstly i was using two partitions in the same SSD on RAID1 level of BTRFS for DATA and METADATA

*Now i know about DUP instead of RAID1, i will test with DUP; and that will let me aboid running two clone partitions backup each time, just one; that would be great (it it works)

How it becames in saving me? Easy: Prior to do a clone to the BackUP media, i laund a scrub on what i want to clone so that non readable sectors will cause BTRFS to overwrite them with the other copy (hopping there is no non readable sector for both copies at the same time and same position).
With two partitions it worked fine (slow, but worked) and do not loose some sectors on the cloned data; now i must test with DUP on one partition instead of RAID1 on two identical size partitions.
It does not reduce the time to do the BackUP (also scrub takes its extra time), but at least i can be sure all data is correct... till one day two non readable sectors occur for the same data (colision) on the same position at the same time, that will be unrecoveable.
The other option is obvious: Not use at all any KingDian SSD anymore, taht are till now the only ones i had used that presents that problem (non readable sectors after long periors without power).
Imagine you go out on vacations, cut general power of the house, came back and your SSDs have non readable portions!!! Big problem for home user, not for datacenters where SSDs are allways powered.
Great BTRFS!!! Now think the other ugly part (for me), how to do something similar for the NTFS partition (windows system partition)? No way at all, NTFS has not that option (remember Windows HOME versions, not SERVERS, etc).
So thanks BTRFS, Linux is much better than i thought a few days ago... i am a Linux user since decades... but was refuse to try BTRFS because all BAD info about full corruption, etc.; till i encounter SSD problem and need something with redundancy.
The other option i was thinking of was ZFS, much more complicated, not integrated on GRUB2 bootloader, not integrated on Kernel (and maybe never will be because licensing system), etc.; so i fanally tried (yesterday) BTRFS... and what a surprise, it seems really stable, relative easy to use (warning when adding a ne disk, it adds it in RAID0, not RAID1, i do not use RAID5/6/etc nor want to use such), easy to recover from catastrofistic damage (re-format one of the two partitions) without data loose (on non KingDian SSDs), etc.
Of course i do not use sub-volumes, snapshots, etc... just only as a plain filesystem for Linux root "/" in RAID1; as i said i must test with DUP instead of RAID1, but i am afraid (i am a lot paranoid) i will stay with TWO partition on the same SSD on RAID1, since non-readable sector on partition header will imply all BTRFS not recoverable/readable.
If i can still se KingDian SSD among they present such randomly non readable sectors failire it would a money save, SSDs are not cheap since i only want to use single bit cell SSDs and that is really expensive, more as size increases (i say i am a lot paranoid), and have more than 10 off-line backup copies of all data with historic of more than one hundred last states (too paranoid, i know).

A: Late to the party, but anyway. I was wondering about the same question and in the man I read (about dup):
"For example, a SSD drive can remap the blocks internally to a single copy thus deduplicating them. This negates the purpose of increased redunancy (sic) and just wastes space"
Perhaps raid1 would be a way to avoid that concern (or not).

A: In regards to the SSD remapping blocks. The SSD internally does not recognize the partitions, it treats any sector the same. So having the same file (data) as two copies on the same partition is the same result as having two copies on separate partitions. Not all SSD manufactures code the internal storage the same; some may perform block deduplication and others don't.
For an SSD drive:
Theoretical data integrity would be the same, any sector has a chance of failure, but the duplicate data/metadata provides redundancy. Read/write performance also the same. SSD does not have a seek or read time difference across the drive.
For an rotating drive:
Theoretical data integrity would be the same, any sector has a chance of failure, but the duplicate data/metadata provides redundancy. Read/write performance also the same. Read performance I cannot speak to, as testing would need to be performed. Read can be done from either file copy (in dup) or either partition. However, I do not know if BTRFS is able to optimize this; ie use the copy/partition which is faster at the front of the platter(faster). Write performance would be degraded more with two partitions, as both copies must be written for the IO to be completed. The partition in the second half of the platter will always be slower to seek/read/write.
Note: While RAID mirror is being used, since it is on a single physical device, any device failure means complete data loss. This mirror only protects against sector failures.

A: I've found at least one difference:
You can mount your degraded raid1 rw only once. The failing chance of a partition while other partition of your device is healthy may be slim, nevertheless this is a difference.
Source:
https://btrfs.wiki.kernel.org/index.php/Gotchas#raid1_volumes_only_mountable_once_RW_if_degraded

raid1 volumes only mountable once RW if degraded
Even if there are no single profile chunks, raid1 volumes if they become degraded may only be mounted read-write once with the options -o degraded,rw.
Notes:

*

*This does not happen (reportedly) when there are more than 2 devices.

*This does not happen with raid10 profile volumes.

*This is often due to the "Incomplete chunk conversion" issue, where there are single chunks left.
Possible recoveries:

*

*If it is still read-write, you can convert the chunks from profile raid1 to profile single (or profile dup) if you have enough space).

*If it is still read-write, you can btrfs device replace the missing device.

*When a raid1 volume is stuck as read-only for either reason it can only be recovered by dumping its contents, recreating it and restoring the contents.

A: Per the Glossary

DUP:
A form of "RAID" which stores two copies of each piece of data on the same device. This is similar to RAID-1, and protects against block-level errors on the device, but does not provide any guarantees if the entire device fails. By default, btrfs uses DUP profile for metadata on filesystems with one rotational device, single profile on filesystems with one non-rotational device, and RAID1 profile on filesystems with more than one device.

vs.

RAID-1:
A form of RAID which stores two complete copies of each piece of data. Each copy is stored on a different device. btrfs requires a minimum of two devices to use RAID-1. This is the default for btrfs's metadata on more than one device.

So, both store two copies of the data, but RAID-1 requires the copies to be stored on two different devices, while DUP allows both copies to be stored on the same device.
If you have two or more disks, you probably want RAID-1.


text:
Q: Unable to play video from Amazon S3 using PreSignedURL in iOS in ReactNative I have a transcoded video in Amazon S3 bucket and have generated a presigned URL to play it on mobile app developed using ReactNative. It is perfectly working on Android, but not on iOS. It is throwing AVFoundationErrorDomain while playing it.
<Video
    resizeMode={'contain'}
    source={{uri:myPreSignedURL,type:"mp4"}}
    onError={(err)=>{
     console.log(err)
     }}
     style={{flex:1}}
     >
</Video>

Here is the error :
{"error": {"code": -11800, "domain": "AVFoundationErrorDomain", "localizedDescription": "The operation could not be completed",
"localizedFailureReason": "An unknown error occurred (1718449215)", "localizedRecoverySuggestion": ""},
"target": 11939}

Could you please guide me?


text:
Q: how do i provide my cursors in gtk-common-themes for use on snap packages Inglés
Hello, I wanted to provide my Eevee and Vulpix cursors in gtk-common-themes to solve the DMZ-White recognition problem when using my cursors in Snap programs and thus publish version 2.0 in Pling with compatibility with Snap programs but I don't know with what program I must use to develop and provide it in gtk-common-themes that is protected by SquashFS I am a rookie developer in (https://snapcraft.io). how do i provide a cursor in gtk-common-themes?


text:
Q: Read [Outlook Options] settings with C# (Interop 15.0 or Redemption) I am developing an educational application that tests users skills in Outlook and I am stuck in trying to access the settings in the [Outlook Options] dialog, more specifically the [Empty Deleted Items folders when exiting Outlook] as well as the [Check spelling as you type] option, but I will probably need others in the future as well.
I am guessing they should be somewhere in the Outlook Application model but the fact that I cannot find any option from that dialog whatsoever implies that I might be wrong.
We are also using Redemption, but as far as I could tell Redemption does not expose these properties.
So, what is the object model that exposes these properties?

A: Just for reference sake. Just found the values using a registry tracking app.
The  [Empty Deleted Items folders when exiting Outlook] setting is located in
[HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Outlook\Preferences]
"EmptyTrash"=dword:00000001

and the [Check spelling as you type] is in
[HKEY_CURRENT_USER\Software\Microsoft\Shared Tools\Proofing Tools\1.0\Office]
"OutlookSpellingOptions"=dword:00000004

A: These options are not exposed though any API. They are stored in the registry.


text:
Q: xcode 4 not showing main project window Today I just opened the project I was working on XCODE 4, and only one XML file is being shown... the main editor window with the file explorer seems to be hidden. Is there any way to show it up?
This only happens with a specific project :-S that actually is a phone gap project
THks

A:


text:
Q: Migration to Azure Service Fabric - Architectural considerations We are on Azure since 2010 and had a great benefit from a performance and reliability in our application. Azure offers a lot of enterprise-level services and I think that the new "Azure Service Fabric" is great.
What I cannot understand by reading the documentation is the approach on migrating an "old" Cloud Service to the new Service Fabric. Why do we want to migrate? For horizontal scaling and more reliability.
Currently we have a single-instance cloud service, that spins up a lot of subservices. Those subservices are great candidates for microservices. The only problem is that some of these subservices are "runners", i.e. they just cycle on our users database and decide whether an operation (service) has to be run for a particular user or not.
How would you migrate a service like this considering that more than one instance may run this service?
Thanks

A: First thing to keep in mind is that once a service is started it keeps running, and his lifecycle and uptime is controlled by Service Fabric (ex: it will restart it automatically if it crashes). Second thing to keep in mind is that you will end-up with multiple instances of the service running at the same time (on different nodes), so they will end-up doing the exact same thing on different nodes of your cluster.
Your first reflex could be to have one stateless service kind/instance per runner "subservice" that keeps running and leverage the RunAsync (https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-advanced-usage). Personally, I wouldn't take that approach, since this could then require some kind of synchronization between services to prevent useless concurrency, since they do the exact same thing independently.
A better approach would be to have your runner services need to run only once in a while when requested by the "main" service acting as an orchestrator, you could have a Queue based approach where the "main" service submit tasks (messages) to be processed by the runners, who are listening concurrently on the same Queue, making sure that maximum one service instance would complete the task.
For the Queue, think Service Bus or Reliable Concurrent Queue (https://learn.microsoft.com/enus/dotnet/api/microsoft.servicefabric.data.collections.preview.ireliableconcurrentqueue-1).


text:
Q: Standalone MLCK generation for I2S I'm looking at switching a rough hardware design from using a master-IC generated MCLK signal for I2S to using a standalone MCLK generator circuit. I'm a bit new to this area of electronics, but from what I've read I'd need to create a buffered clock signal to avoid any drops in clock between chips. What's the rationale for this? Are there any good example circuits you could point me in the direction of?
Edit -
I've done a rough design for a 12.228 MHz clock with an inverter. It'd be great to get some critique before trying to lay it!

A: In your schematic the R5 in series with C16 don't serve any purpose. Your loop to the crystal should come from after R5, like this:

Then R5/C16 cause the required phase shift, and form a low-pass filter preventing the oscillator to oscillate at the 3rd or 5th harmonic. Also, connecting the inverter's output directly to the crystal will overdrive it.

A: You mainly need to buffer a clock if it is going to lots of places or very far. Since you are only going from the clock generator to the I2S chip, that isn't a problem.
Except at high speed (>500 MHz) and/or long traces it isn't drops you need to worry about. It is reflections due to changes in impedance for the trace. This is why sometime clocks will be terminated with a series resistor at the source or a resistor to ground or the 1/2 way voltage at the end.
If you wish to buffer it, there are numerous parts to do that.


text:
Q: Trying to add smooth Image transition between background images This is the code I currently have:
  $('ul.whats_new_ul li').click(function(){
      var tab_id = $(this).attr('data-tab');
      $('ul.whats_new_ul li').removeClass('current');
      $('.tab-content').removeClass('current');
      $(this).addClass('current');
      $("#"+tab_id).addClass('current');

      if(tab_id == 'Messages'){
          $('#what_new_back').css('background-image', 'url(img/mobile-app/global/whts_new.jpg)' );
      }else if(tab_id == 'gift'){
          $('#what_new_back').css('background-image', 'url(img/mobile-app/global/gift_back.jpg)' );
      }else if(tab_id == 'locators'){
          $('#what_new_back').css('background-image', 'url(img/mobile-app/global/locater.jpg)' );
      }else if(tab_id == 'menu'){
          $('#what_new_back').css('background-image', 'url(img/mobile-app/global/menu_back.jpg)' );
      }
  });

to see it clearer in action - this link here - under section What's New
I wondering how do I add a smooth transition between clicks and make sure the background image has the slideUp animation when each tab is clicked?

A: See this please:
Animate background image change with jQuery
It is not possible to animate the background itself, but it is possible to animate the element containing the background.

A: Without your HTML and CSS I can't give you a correct response but I think that this demo can help you
http://css3.bradshawenterprises.com/cfimg/
Basically you can't animate backgrounds, you need to use divs or imgs and animate them.
"Demo 6 -Fading between multiple images on click"

You can use a wrapper (#backgrounds, #content), use position:absolute and z-index.
Something like

  ...

    ...


text:
Q: How to use inversifyjs container as service locator
I'm writing socket server for my IOT project (stm32f100 + WIFI esp)
I have implemented communication protocol such as GET query:
method=test&data[]=1&data[]=2...etc
I want to implement method resolver which will fetch service (controller) by method name from inversifyjs container with it's dependencies, but I can't find how to inject container into method resolver

A: You can have multiple controllers:
container.bind<Controller>("Controller")
    .to(TestController)
    .whenTargetNamed("test");

container.bind<Controller>("Controller")
    .to(UserController)
    .whenTargetNamed("user");

container.bind<Controller>("Controller")
    .to(OrderController)
    .whenTargetNamed("order");

...

Then you can implement something like the following:
function getService(service: string) {
    container.getNamed<Controller>("Controller", service);
}

You can then resolve based on the method argument:
const orderController = getService("order");
const userController = getService("user");


text:
Q: Does resource id changes everytime an application starts I am storing my images in drawable and their resource id in SQLite database.My database is created when the application starts for the first time.
Is it good to save the image ids in database or does the id's change every time an application start?
if id's change then while fetching back image id's I may receive an error.So,is storing image ID in database a good idea?
i need the images path to be stored in database with other relative data that's why i am storing the image id's in data base.

A: One approach would be storing the drawables in strings.xml as a string array something like this:
 <string-array name="location_flags">
    <item>@drawable/ic_image_name</item>
    <item>@drawable/ic_image_name</item>
    <item>@drawable/ic_image_name</item>
    <item>@drawable/ic_image_name</item>
    <item>@drawable/ic_image_name</item>
    <item>@drawable/ic_image_name</item>
    <item>@drawable/ic_image_name</item>
</string-array>

Then reading this array in your activity code :
TypedArray locationFlags=getResources().obtainTypedArray(R.array.location_flags);

Then applying the for loop you can get the Drawable something like this:
for(int i=0i<locationFlags.length();i++)
 {

   Drawable drawable = locationFlags.getResourceId(i, -1);
 }

Be sure to recycle the TypedArray after using it, since its a shared resource :
 locationFlags.recycle();

A: the best way was to store image name directly into database and fetch it,then use
int resID = this.getResources().getIdentifier("your photo name fetched from database","drawable","package name");

image.setResourceID(resID);

A: It is Bad idea to store ids, But what is your purpose??
better idea is to store thumbnails to database rather than ids..
this helped me
may this example help you
do following steps

*

*get thumbnails of your image
final int thumbnailSize = 128;// define your size
Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath),
                THUMBSIZE, THUMBSIZE);

*Convert it into Byte array
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.thumbnail);
ByteArrayOutputStream out = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, out);
byte[] buffer=out.toByteArray();

*Save it as Blob
ContentValues cv=new ContentValues();
 cv.put(CHUNK, buffer);       //CHUNK blob type field of your table
 long rawId=database.insert(TABLE, null, cv); //TABLE table name
I havnt used this but this may help you


text:
Q: What is a family of lines? And furthermore, how do we define the dimension of the family? My question derives from the stating of the Wolff axiom - Let $\mathcal{L}$ be a two-dimensional family of lines in $\mathbb{R}^3$ such that no (affine) plane contains more than a one-dimensional family of lines in $\mathcal{L}$.

A: The affine group $GL(3, \Bbb R) \ltimes \Bbb R^3$ acts transitively on the space $X$ of lines in $\Bbb R^3$, and so we may view $X$ as a homogeneous space $(GL(3, \Bbb R) \ltimes \Bbb R^3) / H$, where $H$ is the stabilizer of some line in $\Bbb R^3$, which endows $X$ with the structure of a smooth manifold. If a subset $\mathcal{L} \subseteq X$ is, e.g., an embedded submanifold of $X$, we can declare its dimension to be its dimension as a manifold.


text:
Q: Synchronize threads from different processes using semaphore I have problem  with semaphore in C. I have a parent process and a child process. Both can create 3 threads and I must display the beginning and the end of threads and I must impose the next condition: the thread with id 1  from parent process must display its beginning after the thread with id 2 from child process display its end. I use a semaphore, but when I do wait, the thread with id 1 from parent process it doesn't remain stuck at semaphore and continue to display the beginning. I can't use function usleep() or sleep().
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <semaphore.h>

sem_t* s=NULL;

void* function1(void* arg)
{
   int* nrth=(int*) arg;
   sem_t   * s=NULL;

   s=sem_open("mysemaphore",O_EXCL);
   if(s==NULL)
       perror("Error");

   if(*nrth==1)
       sem_wait(s);

   printf("Begin P1, thread %d\n",*nrth);
   printf("End P1, thread %d\n",*nrth);

   sem_close(s);
   return 0;

}

void* function2(void* arg)
{
    int* nrth=(int*) arg;

    sem_t   * s=NULL;
    s=sem_open("mysemaphore",O_EXCL);
    if(s==NULL)
        perror("Error");

    printf("Begin P2, thread %d\n",*nrth);
    printf("End P2, thread %d\n",*nrth);

    if(*nrth==2)
       sem_post(s);

    sem_close(s);

    return 0;
}

int main()
{
   sem_unlink("mysemaphore");
   s=sem_open("mysemaphore",O_CREAT,0644,1);
   if(s==NULL)
      perror("ERROR!");

   pthread_t threads[4];
   int index[4];
   pthread_t threads2[4];
   int index2[4];

   if(fork()==0)
   {

      printf("Begin: process 2 \n");

       for(int i=1; i<=3; i++)
       {
          index2[i]=i;
          pthread_create(&threads2[i],NULL,function2,&index2[i]);
       }
       for(int i=1; i<=3; i++)
       {
          pthread_join(threads2[i],NULL);
       }
       printf("End: process 2 \n");
   }
   else
   {
       printf("Begin: process 1\n");

       for(int i=1; i<=3; i++)
       {
          index[i]=i;
          pthread_create(&threads[i],NULL,function1,&index[i]);
       }

       for(int i=1; i<=3; i++)
       {
           pthread_join(threads[i],NULL);
       }
       printf("End: process 2 \n");

       wait(NULL);
   }
   return 0;
}

A: You are destroying your semaphore in both function1() and function2() when you call sem_destroy(), after which the behavior of that semaphore is undefined.  That may be your biggest problem.
You should be using sem_close() instead after you are finished using the semaphore that you obtained from sem_open().


text:
Q: Delphi Problemas ao Listar Sub-Nó do XML Tenho o código abaixo, porém no nó do [ICMS]. ele põe na mesma
linha não estou conseguindo ler os filhos. Acontecendo o mesmo com o
[PIS] e [COFINS].*
Ele não obedece o nível 2. Como pegar ou checar se tem mais Niveis ou nó?
Agradeço a quem puder ajudar...
procedure TForm1.Button1Click(Sender: TObject);
var Doc: IXMLDOMDocument;
    node_pai,
    node_filho: IXMLDOMNode;
    node_lista: IXMLDOMNodeList;
    i, j: Integer;
begin
    Memo1.Lines.Clear;
    Doc := CoDOMDocument.Create;
    Doc.load(

'<imposto>                        '+
'    <vItem12741>8.25</vItem12741>'+
'    <ICMS>                       '+
'       **<ICMS00>**              '+
'           <Orig>0</Orig>        '+
'           <CST>00</CST>         '+
'           <pICMS>18.00</pICMS>  '+
'           <vICMS>4.53</vICMS>   '+
'       </ICMS00>                 '+
'   </ICMS>                       '+
'   <PIS>                         '+
'       <PISAliq>                 '+
'           <CST>01</CST>         '+
'           <vBC>25.15</vBC>      '+
'           <pPIS>0.0000</pPIS>   '+
'           <vPIS>0.00</vPIS>     '+
'       </PISAliq>                '+
'   </PIS>                        '+
'   <COFINS>                      '+
'       <COFINSAliq>              '+
'           <CST>01</CST>         '+
'           <vBC>25.15</vBC>      '+
'           <pCOFINS>0.0000</pCOFINS>'+
'           <vCOFINS>0.00</vCOFINS>  '+
'       </COFINSAliq>                '+
'   </COFINS>                        '+
'</imposto>                          '
);
    Doc.async  := False;
    node_lista := Doc.selectNodes('//'+Edit1.Text);

    repeat
        node_pai := node_lista.nextNode;
        if (node_pai = nil) then
            Break;

        Memo1.Lines.Add(node_pai.baseName);
        // Nó do Pai ou Nível 1
        for i := 0 to node_pai.childNodes.length -1 do
        begin
            node_filho := node_pai.childNodes[i];
            if (node_filho <> nil) and
               (node_pai.childNodes[i].childNodes.length > 1) then
            begin
                // Nó do filho ou Nível 2
                for j := 0 to node_pai.childNodes[i].childNodes.length -1 do
                   Memo1.Lines.Add('<' +
                   node_pai.childNodes[i].childNodes.item[j].nodeName + '> '
                   + node_pai.childNodes[i].childNodes.item[j].text);
            end
            else
               // Nó do Pai ou Nível 1
               Memo1.Lines.Add('<' + node_pai.childNodes.item[i].nodeName +
               '> ' + node_pai.childNodes.item[i].text);
        end;
    until (node_pai = nil);
end;

Trecho do XML
<imposto>
    <vItem12741>8.25</vItem12741>
    <ICMS>
        <ICMS00>
            <Orig>0</Orig>
            <CST>00</CST>
            <pICMS>18.00</pICMS>
            <vICMS>4.53</vICMS>
        </ICMS00>
    </ICMS>
    <PIS>
        <PISAliq>
            <CST>01</CST>
            <vBC>25.15</vBC>
            <pPIS>0.0000</pPIS>
            <vPIS>0.00</vPIS>
        </PISAliq>
    </PIS>
    <COFINS>
        <COFINSAliq>
            <CST>01</CST>
            <vBC>25.15</vBC>
            <pCOFINS>0.0000</pCOFINS>
            <vCOFINS>0.00</vCOFINS>
        </COFINSAliq>
    </COFINS>
</imposto>

A: Pelo o que entendi você acesso o nó pai que seria "", porém só fez uma tratativa para os possíveis filhos dele.
Quando acessar o pai, precisará realizar um loop nele e criar uma condição para cada um dos filhos que você quer acessar e assim por diante.
É um trabalho um tanto quanto desgastante, no meu caso comecei a trabalhar diretamente com String, lendo o arquivo XML e trabalhando e manipulando a string no XML para conseguir os resultados desejados, o que poupou muito tempo de desenvolvimento.


text:
Q: How can I bootstrap an AngularJS module using variables? I have a preloader module which retrieves some environment data. It then bootstraps the AngularJS app. I'd like to make this module reusable (as it should be) by passing variables for module and element values. This would allow the preloader to be used for both header and footer apps separately, for example.
I can't find the resource I worked from to build this, but here's an article that outlines the use case and solution. Basically, we're applying an Angular app to a legacy Perl Catalyst template wherein we're unable to include some critical environment data. Grabbing it via an ajax call was the best workaround.
Here's the gist of it:
angular.module('Preload', [])

.run(['$http', '$q', function ($http, $q) {

    // create an array of promises to be combined later
    // (in case we ever need more than one)
    var promises = [];

    // call environment setup api
    var env = $http({
        method: 'GET',
        url: '/api/v3/environment_urls/',
        params: {}
    }).success(function (data, status, headers, config) {

        // store the retrieved data as a value in the Preload module
        angular.module('PreloadInjections').value('environment', data);
    });

    promises.push(env);

    // resolve combined promise when all included promises are resolved
    var combinedPromise = $q.all(promises);

    // manually bootstrap app when all promises are resolved
    combinedPromise.then(function () {
        var el = document.getElementById('ng-header'); // <----- VARS USED HERE
        angular.bootstrap(el, ['alUser']); // <----------------- VARS USED HERE
    });
}]);

All that's called from the document like so:
<script>
    angular.element(document).ready(function() {
        angular.bootstrap(null, ['Preload']); // <---------- VARS DEFINED HERE SOMEHOW
    });
</script>

In the last two functional lines there I'd like to replace the respective arguments with variables. I can't figure out how to pass them in. The AngularJS bootstrapping docs mention a third config argument, but it's apparently not set up to handle arbitrary data.
How can I pass those values into the module when it's called from the document file?


text:
Q: Combining Blockquote and p Tags with Quotes CodePen Link
I'm trying to surround my bockquote's with " characters. However, I can't get this to work flexibly for all of the HTML scenarios below:

  no p tag

one p tag should be on a new line

one p tag should be on a new line

two p tag should be on a new line

The SASS I've been trying:
blockquote {
  quotes: """ """ "'" "'";

  &:before {
    content: open-quote;
  }

  &:after {
    content: close-quote;
  }

  p {
    display: inline;
    // OR
    display: block;
  }
}

If I use display: inline, it works but in the case where there are two paragraphs, I lose the line break between them and both paragraphs are shown on one line.
If I used display: block, or display: inline-block, My paragraphs are now separated with a new line but the quote characters are then also on new lines instead of flowing with the paragraph text.
I don't have any control over the HTML. I want to avoid JavaScript. This is what I would like to see:
"no p tag"

"one p tag should be on a new line"

"one p tag should be on a new line
two p tag should be on a new line"

A: You can consider display:inline and force the line break using another technique like below:

blockquote {
  border: 1px solid red;
  position: relative;
  font-size: 2em;
}

blockquote:before {
  content: open-quote;

}

blockquote:after {
  content: close-quote;
}

blockquote p {
  margin: 0;
  display:inline;
}
/* a line break between two P */
blockquote p + p::before {
  content:"";
  display:block;
}

  no p tag

one p tag should be on a new line

one p tag should be on a new line

two p tag should be on a new line

one p tag should

two p tag should be on a new line

two p a new line

A: Consider absolute positioning

blockquote {
  border: 1px solid red;
  display: inline-block;
  position: relative;
  padding: 0 0.5em;
  font-size: 2em;
  margin: .5em;
}

blockquote:before,
blockquote:after {
  position: absolute;
}

blockquote:before {
  content: open-quote;
  left: 0;
  top: 0;
}

blockquote:after {
  content: close-quote;
  right: 0;
  bottom: 0;
}

blockquote p {
  margin: 0;
}

  no p tag

one p tag should be on a single line

one p tag should be on it's own line

two p tag should be on a new line


text:
Q: Reading File into Vector Delimited by Comma and New Line Say that I want to read in a .txt file and is formatted in such a way
Max,1979
Wade,1935
Hugh,1983
Eric,1936

Here is the code I am using to

*

*Read in the file.

*Store it into a vector of string and int (For names and years respectively)
void calcAges(){
while (getline(infile, line, ',')){
    names.push_back(line);
    years.push_back(line);
}
}

void printNames(){
cout << "\n\tDisplaying data...\n";

    for (int i = 0; i < counter; i++){
        cout << (i + 1) << ".\tName: " << names[i] << "\tYear: " << years[i] << endl;
    }
}

Output should look like:
1.    Name: Max    Year: 1979
.
.
.
and so on...

However, I'm having trouble trying to make it so the file I read into my "infile" split at both a comma and a new line. I am storing these variables into a vector array so I can sort and switch later on. I am stumped at this point.

A: The new line is considered as a normal character once you have given ',' as delimiter. So use getline() without specifying a delimiter (default is new line) and try to extract the name and year from the string you have obtained. It can be done pretty easily using find_first_of() and substr()
Example:
while(getline(infile,str))
{
     int index = str.find_first_of(',');
     string name = str.substr(0,index);
     string date = str.substr(index+1);
      // Do something with name and date

}

A: A StringStream is much more powerful when it comes to these kind of operations. However, in your case (which is considered rather simple) you can get away with simple operations on strings.
I would suggest reading each line into your temp string then split it on the comma and add the values into your vectors, something like the following:
void calcAges(){
    while (getline(infile, line)){  // Read a whole line (until it reads a '\n', by default)
        names.push_back(line.substr(0,line.find(",")); // Read from the beginning of the string to the comma, then push it into the vector
        years.push_back(std::stoi(line.substr(line.find(",") + 1)); // Read from the comma to the end of the string, parse it into an integer, then push it into the vector
    }
}

I'm assuming that you're using std::string from the <string> library as the type for your line variable.
I didn't compile and test this by the way, so I'm not sure it would work as is, but I wrote it just to give you an idea about the logical approach
Cheers


text:
Q: How to get a post's associated taxonomies and terms in wp api v2 I am using angular to get a list of posts back from the post endpoint for the wp api.
These posts have different taxonomies and terms associated with them.
I want to use angular's search filters to quickly get through the list but I want to do it on each taxonomy's terms associated to the post.
The problem is, the post endpoint does not show associated taxonomy or terms for each post.
What's the best approach here?

A: Ok, I just stumbled upon the answer buried deep in the github issues page:
https://github.com/WP-API/WP-API/issues/1403
The answer is:

the reason is that the terms / meta etc are different objects, and in
  typical REST design going a GET on a single resource, will give you
  that resource, not that resource and a bunch of other ones too.
  However, you can pass _embed to the request which will include the
  linked resources in the response, for example see
  http://demo.wp-api.org/wp-json/wp/v2/posts/111?_embed


text:
Q: Adding or removing an array from or to a list of array I want to do something like this, the code is
import numpy as np
import random
a = [np.array([2,4,5]), np.array([3,4,6]), np.array([3,7,8])]
b=np.array([4,6,7])
for i in range(5):
    e = random.choice(a)
    a.remove(e)
    a.append(b)

But we can't remove or add arrays like that. I want to remove the array e and add array b to a, so how can I do that?

A: Try:
import numpy as np
import random
a = [np.array([2,4,5]), np.array([3,4,6]), np.array([3,7,8])]
b=np.array([4,6,7])
for i in range(5):
    a = list(np.delete(a, random.randint(0,len(a)-1), 0))
    a.append(b)


text:
Q: I have a Error: error: unreachable statement Error:error: missing return statement I have a Error:

error: unreachable statement  Error:error: missing return statement

It is running this code:
public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerlayout;
    private ActionBarDrawerToggle mToggle;

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

        mDrawerlayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this,mDrawerlayout,R.string.open,R.string.close);

        mDrawerlayout.addDrawerListener(mToggle);
        mToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
        if(mToggle.onOptionsItemSelected(item)){
           return true;
        }
    }
}

A: In onOptionsItemSelected() after 1st line if() is unreachable code pls use below.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
   return true;
}else{
   return false;
 }
}

A: call super.onOptionsItemSelected(item) after you have called mToggle.onOptionsItemSelected(item)
  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mToggle.onOptionsItemSelected(item)){
           return true;
        }
        return super.onOptionsItemSelected(item);
    }

A: In your code
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
    if(mToggle.onOptionsItemSelected(item)){
       return true;
    }

Your first statement is a return keyword, and that leaves the current method skipping the the next block of code.

A: You are returning from onOptionsItemSelected and there is still some code after return statement. Simply change to below
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(mToggle.onOptionsItemSelected(item)){
       return true;
    }
    return super.onOptionsItemSelected(item);

}


text:
Q: Reducing training dataset for architecture testing I want to quickly test many CNN architectures on the MNIST dataset, but I don't want to train each on the whole dataset.
Is it possible to reduce the training dataset size and still be able to accurately determine which model is better?
If so, what's minimum size I can reduce it to?

A: To give one counterexample, there is a recent paper To Pretrain or Not to Pretrain by Wang, Khabsa, and Ma (2020), quoting the authors:

Our  findings  in  this  paper  indicate  that  increasing the number
of training examples for 'standard' models such as LSTM leads to
performance gains that are within 1 percent of their massively
pre-trained counterparts. [...] One  way  to  interpret  our  results
is  that 'simple' models have better regularization effect when
trained on large amount of data, as also evidenced in the concurrent
work (Nakkiran and Sutskever, 2020).

So it might be the case that different architectures would have different performance depending on the data size you use for training. In this study, with large enough dataset, they were able to find a simpler model, that had performed almost as well as the complicated one.


text:
Q: Was one number short of getting the first prize! Context:
The number on my lottery ticket: 26381
The official result for the first prize: 26384
(In my country, it's 2/6/3/8/1 - five different numbers. The numbers can repeat and are already printed on the tickets).
And I want to say "You missed one number, otherwise you would have won the first prize".So is "Was one number short of getting the first prize!" a correct sentence to express what I mean?
If not, how can I say that (I prefer an exclamatory sentence, if possible!)?

A: Without explaining it, one number short may be misunderstood such as 4 or 5; 6 or 7, and so on. In short, number in series. But, out of many, in such cases, I use an idiom (since you asked for exclamatory!) hair's breadth.

Ah....missed the lottery jackpot by a hair's breadth.

Or just missed is simple and easily understood.

Ah...just missed the jackpot

Now, that's an idiomatic expression. If you want to emphasize on the digit, you may say,

Missed the first prize by one digit

But here, you then need to explain what that digit is.

The last digit is '4' and I have '1.'

As I said, it's just one way to tell this with exclamation. Wait for others to respond.

A: I think any native speaker would understand one number short in the context of a lottery to mean that you had all but one of the numbers (not all but one of the digits that make up a number).
Suppose these were the winning numbers:
2, 16, 33, 41, 59
If you had 58 instead of 59, or 44 instead of 59, you could still say I was one number short of winning the lottery.


text:
Q: Fastest fgets implementation in C The known fgets libc function implementation uses fgetc() inside, how can I use read() with bigger buffer or other method instead to speed up the function?
For example I read /proc/pid/maps file to search some strings. The file's format is known, currently I use the fgets implementation in the link with read(fd, &c, 1); instead of getc. I think reading single byte from file is slower than reading 200 bytes. So I want to modify the function to read N bytes from file and then finds a line break. I think replacing 1 byte read can speed up the function somehow.

A: You're totally misunderstanding the standard I/O function. Even fgetc is buffered. Test the issuance of actual read calls with strace. On my computer, reading /proc/1/maps:
read(3, "5634f9cf6000-5634f9e44000 r-xp 0"..., 1024) = 1024
read(3, "                   /lib/x86_64-l"..., 1024) = 1024
read(3, "             /lib/x86_64-linux-g"..., 1024) = 1024
read(3, "                   /lib/x86_64-l"..., 1024) = 1024
read(3, ".0.0\n7feb2b2dc000-7feb2b4db000 -"..., 1024) = 1024
read(3, "0-7feb2b8e7000 r--p 00002000 fd:"..., 1024) = 1024
read(3, "00 rw-p 0001a000 fd:00 145004   "..., 1024) = 1024
read(3, "ux-gnu/liblzma.so.5.2.2\n7feb2c1b"..., 1024) = 1024
read(3, "6_64-linux-gnu/libgcrypt.so.20.2"..., 1024) = 1024
read(3, "000 fd:00 135558                "..., 1024) = 1024
read(3, "--p 0000e000 fd:00 136910       "..., 1024) = 1024
read(3, "001e000 fd:00 131385            "..., 1024) = 1024
read(3, "1.1.0\n7feb2da14000-7feb2da15000 "..., 1024) = 1024
read(3, "0 rw-p 00000000 00:00 0 \n7feb2de"..., 1024) = 1024
read(3, "-237.so\n7feb2e492000-7feb2e69100"..., 1024) = 1024
read(3, " \n7feb2ed15000-7feb2ed36000 rw-p"..., 1024) = 637
read(3, "", 1024)                       = 0

The read calls attempt to read 1024 bytes, not just one.
The program is
#include <stdio.h>

int main(void) {
    FILE *f = fopen("/proc/1/maps", "r");
    while (1) {
        char buf[2048];
        if (! fgets(buf, 2048, f)) {
            break;
        }
    }
}

Should 1024 bytes not be enough for you, you can change the size of the underlying buffer with setvbuf(3)!

A: Here an hint for you (but shall be modified to read more than one byte a time)
... And we've the function fgetsR() that uses the function read()  instead of fgetc(). In the code below there're two functions:

*

*fgets0() is a K&R fgets() function

*fgetsR() is a fgets() function that uses read() instead of fgetc().

The function fgetsR is used in the main to read a file (specified into the command line) and display its contents.
#include <unistd.h>

#include <stdlib.h>
#include <time.h>
#include <malloc.h>

char * fgets0(char *dst, int max, FILE *fp);
char * fgetsR(char *dst, int max, FILE *fp);

char * fgets0(char *dst, int max, FILE *fp)
{
    int c;
    char *p;

    /* get max bytes or upto a newline */

    for (p = dst, max--; max > 0; max--) {
        if ((c = fgetc (fp)) == EOF)
            break;
        *p++ = c;
        if (c == '\n')
            break;
    }
    *p = 0;
    if (p == dst || c == EOF)
        return NULL;
    return (p);
}

char * fgetsR(char *dst, int max, FILE *fp)
{
    int c;
    char *p,x;

    /* get max bytes or upto a newline */

    for (p = dst, max--; max > 0; max--) {
        if ((c = read(fileno(fp),&x,1)) == EOF || !c)
            break;
        *p++ = x;
        if (x == '\n')
            break;
    }
    *p = 0;
    if (p == dst || c == EOF || !c)
        return NULL;
    return (p);
}

int main(int argc, char *argv[])
{
    FILE * f = NULL;
    char buffer[1024];

    if (argc<2) {
        puts("You have to specify a file to read!");
        return 1;
    }

    f=fopen(argv[1],"r");

    while(fgetsR(buffer,sizeof(buffer),f)) {
        printf("%02X %s",*buffer,buffer);
    }

    fclose(f);

    return 0;
}

I don't think that solution is the better and faster. The main() above needs some workaround to control the flow when errors occur.


text:
Q: Convertir un number a string el valor dentro de una clase tengo el siguiente problema, tengo una clase en un archivo .ts el cual almaceno en esa variable de tipo any ya que tengo un formulario dinamico.
El detalle es que almaceno en ese valores numericos y quiero convertirlos en string. intente ponerlo con la funicon de Number(cp) pero me marca error en el documento.

export class InformacionProyectoInstitucion
        cp.: any
        programa_educativo: any

Este lo recibo en una variable importando la clase a mi componente y esto previamente lo extraigo del html del form y la variable informacion_Proyecto:
Donde tengo problemas es en el campo de codigo postal ya que deberia enviarlo como string en el json pero yo lo tengo numerico por cuestiones de diseño que me pidieron.

import { InformacionProyectoInstitucion } from 'src/app/api/apis_generales/modelos_instituciones/informacionProyectoInstitucion';

AddNuevoAsesor() {
    this.informacionContacto = new InformacionContactoInstitucion();
    this.informacion_Contacto.push(this.informacionContacto);
  }

 informacion_Proyecto = [];

 if(this.informacion_Proyecto.length){
      for (let proyecto of this.informacion_Proyecto) {
        this.apisProyectosService.createProyecto(JSON.parse(JSON.stringify(proyecto))).subscribe({
          next: (v) =>{
            if(v != null ){
              this.refreshTable();
              this.messageService.add({severity: 'success', summary: 'Completado', detail: 'Proyecto creado correctamente.', life: 3000});
            }else{
              this.messageService.add({severity: 'error', summary: 'Error', detail: 'Error proyecto no se pudo crear.', life: 3000});
            }
          },
          error: (e) =>{
            this.messageService.add({severity: 'error', summary: 'Error', detail: 'Error al guarda el proyecto', life: 3000});
            console.error(e);
          },
          complete: () => console.info('complete')
        });
      }
    }
    <button pButton pRipple pTooltip="Agregar nuevo proyecto" tooltipPosition="bottom" (click)="AddNuevoProyecto()"></button>

<input pInputText type="number" placeholder="Código postal" [(ngModel)]="proyecto.cp" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==5) return false;"/>

A: Lo resolví de la siguiente manera después de la iteración del for:
Bueno prácticamente lo que hago es iterar esa parte del for donde asigno mi variable, declaro otra variable y solo recurro al parámetro que requiero convertir y y lo cambio con la función toString y listo.

for (let proyecto of this.informacion_Proyecto) {
              let cp1 = proyecto.cp;
              proyecto.cp = cp1 > 0 ? cp1.toString() : '';
}

Espero sea de ayuda, para alguien más, saludos.


text:
Q: How does #error in C/C++ work? I am guessing from # that it is only a compile-time utility. How can it be used in C/C++ programs?
Did not find much about it on the internet. Any links would be helpful.

A: Here is a link to the documentation of the Gnu preprocessor explaining the #error and #warning directives: http://gcc.gnu.org/onlinedocs/cpp/Diagnostics.html
In particular:

The directive #error causes the
  preprocessor to report a fatal error.
  The tokens forming the rest of the
  line following #error are used as
  the error message.

See also this question about the portability of these directives.

A: It causes the compiler (or preprocessor) to output the error message.  In C++, it also renders the translation unit ill-formed (i.e., it causes compilation to fail).
If you have several macros that could be defined and you want to be sure that only certain combinations of them are defined, you can use #error to cause compilation to fail if an invalid combination is defined.
It can also be useful if you want to be sure that some block of code is never compiled (for whatever reason).

A: Useful to check compiler settings as well as verifying macro value combinations.  Some random examples:
#if !defined(_DLL)
#  error This code will only work properly when compiled with /MD
#endif

#if _WIN32_WINNT < 0x502
#  error Sorry, Windows versions prior to XP SP2 are not supported
#endif

#if defined(_APPLE) && defined(_LINUX)
#  error Conflicting operating system option selected, choose one.
#endif


text:
Q: Is it possible to get result from Test PumpWidget Flutter I am trying to get the result of a widget after the page is close
like this
 Navigator.pop(context,result);

is it possible to access the result value from test.
See my test code.
testWidgets("Test list dialog selection result", (tester)async{
   tester.pumpWidget(const MaterialApp(home: SampleWidget(),));

   tester.pumpAndSettle();

   // Taps the button in the page
   // The button is set to close the page and add a result value

   tester.tap(find.text("Click Me"));

   tester.pumpAndSettle();

   //Is there a way to access the result value here
 });

See the sample widget here
import 'package:flutter/material.dart';

class SampleWidget extends StatefulWidget {

  const SampleWidget({Key? key}):super(key: key);

   @override
   _SampleWidgetState createState() => _SampleWidgetState();
 }

 class _SampleWidgetState extends State<SampleWidget> {

  String text = "Click Me";

   @override
   Widget build(BuildContext context) {
     return Scaffold(
       appBar: AppBar(title: const Text("Welcome"),),
       body: Container(
         color: Colors.white,
         child: Center(
           child: TextButton(
             onPressed: (){
               Navigator.pop(context, "Hey, some result");
             },
             child: Text(text),
           ),
         ),
       ),
     );
   }
 }


text:
Q: Is there a quadratically closed field strictly between the quadratic closures of $\mathbb{Q}$ and $\mathbb{Q}(\sqrt[3]{2})$? Let $K$ be the quadratic closure of $\mathbb{Q}$, and $K'$ the quadratic closure of $\mathbb{Q}(\sqrt[3]{2})$. Is there a quadratically closed field $L$ strictly between $K$ and $K'$, i.e. such that $K \subsetneq L \subsetneq K'$?
It is a particular case of my previous question, so this is inspired by questions about ruler and compass constructions. If we could find some element $r \in K' \setminus K$ such that $\sqrt[3]{2}$ is of degree $3$ in $\mathbb{Q}(r)$, then the quadratic closure of $\mathbb{Q}(r)$ would not contain $\sqrt[3]{2}$, because the quadratic closure only adds elements whose degrees are powers of $2$, and therefore we could define $L$ as this quadratic closure. The degree of $r$ over $\mathbb{Q}$, if there is such a $r$, is a power of $2$, because we have
$$ [\mathbb{Q}(\sqrt[3]{2},r) : \mathbb{Q}] = [\mathbb{Q}(\sqrt[3]{2},r) : \mathbb{Q}(\sqrt[3]{2})] \cdot [\mathbb{Q}(\sqrt[3]{2}) : \mathbb{Q}] = 2^n \cdot 3$$
so
$$ [\mathbb{Q}(r) : \mathbb{Q}] = \frac{[\mathbb{Q}(\sqrt[3]{2},r) : \mathbb{Q}]}{[\mathbb{Q}(\sqrt[3]{2},r) : \mathbb{Q}(r)]} = \frac{2^n \cdot 3}{3} = 2^n.$$
We also have the reverse implication: if there is a quadratically closed field $L$ strictly between $K$ and $K'$, then $\sqrt[3]{2}$ must be of degree $3$ over $L$, otherwise it would be of degree smaller than $3$, and there is no element of degree $2$ over $L$, so it would be contained in $L$, and for any element $r \in L \setminus K$, $\sqrt[3]{2}$ would be of degree $3$ over $\mathbb{Q}(r)$.
To sum up, the question reduces to: is there an $r$ which is of degree a power of $2$ over $\mathbb{Q}$ and which is not polyquadratic over $\mathbb{Q}$, but which is polyquadratic over $\mathbb{Q}(\sqrt[3]{2})$?
You can find the formulas for the roots of a quartic polynomial here. We see that the solutions are contained in the quadratic closure of $\mathbb{Q}(\sqrt[3]{2})$ if the intermediate parameter $f$ is an integer or if it is equal to $\sqrt[3]{2}$. So if we could find such an irreducible quartic over $\mathbb{Q}$ and such that its roots are not polyquadratic, we would conclude. But that becomes quite far fetched.
Edit: Now cross-posted (not by me) on Mathoverflow.

A: The question has been answered positively on Mathoverflow in two different ways. I post here a copy of my solution:
Let $K$ be the quadratic closure of $\mathbb{Q}$, and $L$ be the quadratic closure of $\mathbb{Q}(\sqrt[3]{2})$. The roots of the polynomial $P(x) := x^4 + 36x + 54$ are not in $K$, but they are in $L$, and $P$ is irreducible because it is irreducible modulo $5$, hence any root $\alpha$ of it is of degree $4$, and the quadratic closure of $\mathbb{Q}(\alpha)$ is strictly between $K$ and $L$. (I used https://www.alpertron.com.ar/POLFACT.HTM for the calculations modulo 5.)
First, why are the roots of $P$ not in $K$? It is because mod $7$, it decomposes in $(x+6)(x^3+x^2+x+2)$, which are irreducible, and the discriminant of this polynomial is $-5038848$, which is not divisible by $7$, therefore by Dedekind's theorem there is a cycle of order $3$ in the Galois group of $P$ (Again, calculation modulo 7 with https://www.alpertron.com.ar/POLFACT.HTM, and calculation of the discriminant with https://planetcalc.com/8188/.)
Finally, it is in the quadratic closure of $\mathbb{Q}(\sqrt[3]{2})$, because we can look at the explicit formula for the roots of a quartic:

In our case, $a = b = 0$, therefore $e = \sqrt{(27c^2)^2-4(12d)^3} = 11664$, and $f = \sqrt[3]{27c^2 + e} = \sqrt[3]{2^6 \cdot 3^6} = 2^2 \cdot 3^2$. Except that, only square roots and $\sqrt[3]{2}$ appear in the formula, thus the roots are in $L$.


text:
Q: homeomorphism from square to disk I am looking at an exercise to find a homeomorphism from $[-1,1] \times [-1,1]$ to the unit disk.
A possible solution may be $$y_{i} = \frac{\left \| x \right \| x_{i}}{ max(|x_{1}|,|x_{2}|)}$$
for a point $x$ from the unit disk to a point y from the unit square. And $0$ is mapped to $0$.
But what is the thought process to come up with that?
Some idea seems to be to look at the intersection point with the square but I don't really understand that.

A: Your formula is not quite correct, you need absolute values around $x_1$ and $x_2$ in the denominator.
The thought process for arriving at a formula starts by drawing a picture: the unit disk, which I'll denote $D$, is inscribed in the square $S = [-1,1] \times [-1,1]$, tangent to the midpoint of each of the four sides of that square.
Now consider any ray in the Euclidean plane based at the origin, denoted $R$. On $R$ there are two special points: the point $D(R)$ which is the last point of $R$ in $D$, namely the point where $R$ intersects the unit circle; and the point $S(R)$ the last point of $R$ in $S$, which is the last point where $R$ intersects the boundary of the square $S$.
So, the idea of the homeomorphism is: map the origin $\mathcal O$ to itself; and then for each ray $R$, map the point $D(R)$ to the point $S(R)$, and then extend this to a map of the segment $\overline{\mathcal O D(R)}$ to the segment $\overline{\mathcal O S(R)}$. To define that extension, simply scale the first segment (whose length equals $1$) to the second segment (whose length equals the norm $\|S(R)\|$) by multiplying by a scalar equal to $\|S(R)\|$.
Now comes the tricky part: given $x=(x_1,x_2) \in D$, I have to determine the correct scalar to multiply by, so I have to think about the ray $R_x$ that starts from the origin, then passes through $x$, and then through $D(R_x)$, and then through $S(R_x)$, and then I have to compute the norm of $S(R_x)$. A little thought shows that
$$S(R_x) = \frac{x}{\text{max}\{|x_1|,|x_2|\}}
$$
which has norm
$$\|S(R_x)\| = \frac{\|x\|}{\text{max}\{|x_1|,|x_2|\}}
$$
and so the final formula for the desired map is
$$x \mapsto \|S(R_x)\| \, x = \frac{\|x\| \, x}{\text{max}\{|x_1|,|x_2|\}}
$$
Letting $y$ be the image point with coordinates $y=(y_1,y_2)$ then you can write this formula as
$$y_i = \frac{\|x\| \, x_i}{\text{max}\{|x_1|,|x_2|\}}
$$


text:
Q: Add different default and custom tags to Visual Studio XML Documentation I am just learning how to use the XML documentation capabilities in visual studio and C#.
The default XML tags used in the documentation are "summary", "param name", and "returns".
I'd like to add "remarks" to the default tags.  I'd also like to add custom tags.
I've looked through MSDN, the XML documentation tutorials, and stackoverflow and haven't found the way to do this.  Any suggestions are much appreciated, and thanks!
Mark

A: This thread describes a solution for VB, but says that it is not available for C#.  Follow the links to vote to have this feature included in the next version of Visual Stuido.


text:
Q: Ambiguous overload for 'operator=' when trying to invoke the move assignment operator I am trying to clarify-understand move semantics and, for that, I wrote the following code. I used a raw pointer as a data member only to practice in finding all the dangerous spots and also apply idioms like copy & swap.
#include <iostream>
#include <utility>

class Example {
protected:
  int* intPtr;

public:
  Example() : intPtr{nullptr} {
    allocate();
    std::cout << "Example() called" << "\n";
  }

  Example(int value) : intPtr{nullptr} {
    allocate();
    assign(value);
    std::cout << "Example(int) called" << "\n";
  }

  ~Example() {
    deallocate();
    std::cout << "~Example called" << "\n";
  }

  Example(const Example& anExample) :
    intPtr{anExample.intPtr ? new int(*anExample.intPtr) : nullptr} {
    std::cout << "Example(const Example&) called" << "\n";
  }

  Example(Example&& anExample) noexcept {
    intPtr = anExample.intPtr;
    anExample.intPtr = nullptr;
    std::cout << "Example(Example&&) called" << "\n";
  }

  Example& operator=(Example&& anExample) noexcept {
    if(this != &anExample){
      intPtr = anExample.intPtr;
      anExample.intPtr = nullptr;
      std::cout << "Move assignment op called" << "\n";
    }
    return *this;
  }

  Example& operator=(Example anExample) {
    std::swap(intPtr, anExample.intPtr);
    std::cout << "Copy assignment op called \n";
    return *this;
  }

  void assign(int value) {
    if (intPtr != nullptr && *intPtr!=value)
      *intPtr = value;
    else {
      std::cout << __FUNCTION__ << ": intPtr is either null, or its memory contains already the value you want.\n";
    }
  }

private:
  void allocate() {intPtr = new int{};}

  void deallocate() {delete intPtr;}

  friend std::ostream& operator<<(std::ostream& strm, const Example& anExample) {
    return strm << *anExample.intPtr;
  }

};

int main() {

  Example ex1;
  std::cout << "----------------" <<std::endl;
  Example ex2{ex1};
  std::cout << "----------------" <<std::endl;
  Example ex3 = ex2; // invokes copy constructor
  std::cout << "----------------" <<std::endl;
  Example ex4;
  std::cout << "----------------" <<std::endl;
  ex4 = ex3; // invokes copy assignement operator
  std::cout << "----------------" <<std::endl;
  Example ex5 = std::move(ex1); // invokes move constructor
  std::cout << "----------------" <<std::endl;
  ex4 = std::move(ex5); // compilation error!
  return 0;
}

The last line gives the following error
main.cxx:116:22: error: ambiguous overload for 'operator=' (operand types are 'Example' and 'std::remove_reference<Example&>::type' {aka 'Example'})
  116 |   ex4 = std::move(ex5);
      |                      ^
main.cxx:36:12: note: candidate: 'Example& Example::operator=(Example&&)'
   36 |   Example& operator=(Example&& anExample) noexcept {
      |            ^~~~~~~~
main.cxx:45:12: note: candidate: 'Example& Example::operator=(Example)'
   45 |   Example& operator=(Example anExample) {
      |            ^~~~~~~~

Why is the right hand side's type std::remove_reference<Example&>::type. What am I doing wrong here and how to invoke the move-assignement operator properly?
Every other comment is welcome.

A: Example& operator=(Example anExample) is a general assignment operator. It copies lvalues and moves rvalues.
If you want to distinguish copy from move assignment you need Example& operator=(const Example & anExample).
Alternatively you could remove Example& operator=(Example&& anExample).


text:
Q: Eloquent InnoDB cannot add foreign key (error 1215) I am trying to create a table with foreign keys with eloquent ORM and InnoDB engine and it is failing with error :
General error: 1215 Cannot add external index constraint.
The thing is that it works on mariaDB, i tried on an other computer.
This is the table :
DB::schema()->create('client', function($table){
        $table->engine = 'InnoDB';

        $table->increments('id')
              ->comment('Identifiant du client');

        $table->string('cli_nom', 25)
              ->comment('Nom ou raison sociale du client');

        $table->string('cli_activite', 5)
              ->comment('Code NAF activité');

        $table->text('cli_activite_desc')
              ->comment('Description du code NAF');

        $table->integer('cli_adresse_id')
            ->unsigned()
            ->comment('Id de l adresse du client');

        $table->integer('cli_type')
            ->comment('1:client ou 0:prospect');

        $table->integer('cli_theme_couleur_id')
            ->unsigned()
            ->comment('Id de la couleur de personnalisation d interface');

        $table->integer('cli_theme_id')
            ->unsigned()
            ->comment('Id du theme acheté par le client');

        $table->timestamps();

        $table->foreign('cli_adresse_id')
              ->references('id')->on('adresse')
              ->onDelete('restrict');

        $table->foreign('cli_theme_couleur_id')
            ->references('id')->on('theme_couleur')
            ->onDelete('restrict');

        $table->foreign('cli_theme_id')
            ->references('id')->on('theme')
            ->onDelete('restrict');
    });

I also tried to add index() to the fk:
            $table->integer('cli_adresse_id')
            ->unsigned()
            ->index()
            ->comment('Id de l adresse du client');

EDIT
This is the referenced table :
 DB::schema()->create('adresse', function($table){
        $table->increments('id')
            ->unsigned()
            ->comment('Identifiant de l adresse');

        $table->integer('adr_num')
              ->comment('Numéro de rue');

        $table->string('adr_voie', 250)
              ->comment('Rue ou voie dans la ville');

        $table->string('adr_cp', 10)
              ->comment('Code postal de l adresse');

        $table->string('adr_ville', 250)
              ->comment('Nom de la ville de l adresse');

        $table->integer('adr_pays')
              ->comment('Identifiant du pays');

        $table->timestamps();
    });


text:
Q: facebook request dialog not returning repsonse I have the following code displaying the request dialog. The function sends the requests to the users I select but the problem is that it DOES NOT RETURN THE SELECTED USERS IDS
$('#request_btn').click(function(){send_request()});

function send_request()
{
var message = 'Bla Bla';
var title   = 'Bla Bla'

FB.ui({
        method: 'apprequests',
        message: message,
        title: title,
        max_recipients: 20
},
function (response)
{
    if (response && response.request_ids)
    {
        alert('success')
    }

});

return false;
}

A: It should be returning the request IDs, not the user IDs, are you sure that's not happening?
The example at http://www.fbrell.com/fb.ui/apprequests is working fine for me


text:
Q: cannot load the information from netlify-cms I have a sveltekit app with netlify-cms added to it.
I have followed this tutorial on sapper.
https://dev.to/avcohen/svelte-sapper-netlify-cms-3mn8
I have the ability to input information through the website. But I do not have the ability to see the information.
I think most of the info I give is irrelevant but here it is:
the error that pos up on trying to see the information is
500

Cannot read property 'title' of undefined
TypeError: Cannot read property 'title' of undefined

the console that appears on the side is:
    Error with Permissions-Policy header: Unrecognized feature: 'interest-cohort'.
Test#/:1 GET https://xxx.netlify.app/blog/Test 500
index.js:25 netlify-cms-app 2.15.40
bootstrap.js:83 netlify-cms-core 2.48.0
bootstrap.js:106 Uncaught TypeError: Cannot read property 'appendChild' of null
    at bootstrap.js:106
    at Object._ [as init] (bootstrap.js:134)
    at Module.<anonymous> (index.js:10)
    at n (bootstrap:19)
    at bootstrap:83
    at netlify-cms.js:1
    at universalModuleDefinition:9
    at universalModuleDefinition:1
(anonymous) @ bootstrap.js:106
_ @ bootstrap.js:134
(anonymous) @ index.js:10
n @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ netlify-cms.js:1
(anonymous) @ universalModuleDefinition:9
(anonymous) @ universalModuleDefinition:1
config.js:429 GET https://xxx.netlify.app/blog/config.yml 500
(anonymous) @ config.js:429
(anonymous) @ config.js:567
(anonymous) @ index.js:8
dispatch @ VM181:14608
_ @ bootstrap.js:116
(anonymous) @ index.js:10
n @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ netlify-cms.js:1
(anonymous) @ universalModuleDefinition:9
(anonymous) @ universalModuleDefinition:1
config.js:439 Uncaught (in promise) Error: Failed to load config.yml (500)
    at config.js:439
    at async config.js:567

my endpoint is :
    import path from "path";
    import fs from "fs";
    import grayMatter from "gray-matter";
    import marked from "marked";

    const getPost = (fileName) => {
      return fs.readFileSync(
        path.resolve("static/posts/", `${fileName}.md`),
        "utf-8"
      );
    };

    export function get(req, res, _) {
      const { slug } = req.params;

      const post = getPost(slug);
      const renderer = new marked.Renderer();

      const { data, content } = grayMatter(post);
      const html = marked(content, { renderer });

      if (html) {
        res.writeHead(200, {
          "Content-Type": "application/json",
        });

        res.end(JSON.stringify({ html, ...data }));
      } else {
        res.writeHead(404, {
          "Content-Type": "application/json",
        });
    console.log(res, "helps");
        res.end(
          JSON.stringify({
            message: `Not found`,
          })
        );
      }
    }

the page to view the information on:

<svelte:head>
    <title>{post.title}</title>
</svelte:head>

{post.title}

    {@html post.html}

I am not very experienced with endpoints or sveltekit, can you help find out why the information is not being shown?


text:
Q: LIKE %...% Meta Query I have a serialized array as a meta value and I'm trying to run WP Query where it finds a specific value in the serialized array.
Here's an example of the serialized array field:
a:6:{i:0;s:3:"173";i:1;s:3:"172";i:2;s:3:"171";i:3...

Here's my query, but it doesn't work:
The ID's are numberic I'm doing a search for as well.
$practiceArgs = array(
    'post_type' => 'attorney',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'meta_query' => array(
                        array(
                              'key' => 'practice_area',
                              'value' => $post->ID,
                              'compare' => 'LIKE',
                              'type' => 'NUMERIC'
                              )
                        )
);

I've tried using 'value' => '%'.$post-ID.'%' in my queries, but it doesn't seem to work as well.
Anyone ever had any experience working on this?

A: I ran into this issue once, but it's definitely not a nice place to be. The way you're approaching this you'll never have a consistent result -- your search will turn a lot of false positives (i.e. searching for post ID 43 will return 143, 243, 1431, 1432, etc.
The way I see it, you have two options:

*

*Rethink the way you're saving your meta data; use arrays for data
that's only needed when rendering the post, but not for data that you
need to query to filter posts. For the latter, use individual meta
keys in your db -- it's much faster, the queries are easier to code,
and you can rest assured that you'll have full control over what the
queries return. Don't be concerned with using too many rows in the
postmeta table: that's why they're there for.

*If for some reason you must have multiple fields packed in one db
row, don't rely on default serialization: go for CSV, preferably with
some sort of prefix, something that won't return false positives.
Something like "id:43,id:54,foo:bar,id:57,", then search for
'id:{post_ID},' (note that all values should end with commas in
order to safely use double wildcards on a LIKE search. It's sort of a hack, but it's more reliable than what you're going for right now.

For what it's worth, regarding the original question, WP already adds both wildcards when doing LIKE comparisons using query_posts, so you don't have to do anything.

A: Wordpress LIKE is not like Mysql Like, so 'value' => '%'.$post-ID.'%' doesn't work.
You could try the REGEXP version. For example:
'meta_query' => array(
    array(
        'key'       => 'attorney',
        'value'     => '^'.$post-ID,
        'compare'   => 'REGEXP',
    )
)

Should search for all elements where attorney begins with $post-ID value.

A: I came across this same issue today. In both our situations, there is in fact a nice solution. Because the serialized data we are searching for, are simply IDs, and they are always wrapped in quotations, we just need to include the quotations as part of the query. This eliminates the problem of encountering false positives in the search results.
You just need to modify the meta query to as follows:
array(
    'key' => 'practice_area',
    'value' => '"'.$post->ID.'"',
    'compare' => 'LIKE',
)

This way, it searches for the whole ID, including the double quotes before and after it within the serialized array. No false positives will be included.

A: You can't use LIKE with numeric (at least I am pretty sure you can't). numeric will try to convert the whole value to a number. That will fail, as it isn't a number.  That is the first mistake.
Secondly, to get a literal %, you need to double it to %%. Note: I can't remember about meta_query strictly speaking.  I am extrapolating from what it takes to get a % to pass through $wpdb->prepare I think it is the same though. Edit: This appears to only be true with $wpdb->prepare. The code has been edited.
I have not tested this, as I'd need to setup some things in my database and don't have time right now, but I think it will work.
$practiceArgs = array(
    'post_type' => 'attorney',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'meta_query' => array(
      array(
        'key' => 'practice_area',
        'value' => $post->ID,
        'compare' => 'LIKE'
      )
    )
);

I hope that is the push you need. If it doesn't work I will revisit.
Edit: I inserted your (broken) serialized array into my database and ran the code above. If I get everything set up correctly-- the meta_fields, the post types, etc.-- the code above works. If it isn't working for you you've got something else going on-- maybe you think there should be a match where there isn't.
I am assuming that you are going to have an array like that for every one of your 'attorney' posts. If you do, that should work. I might lean toward multiple practice_area rows though, instead of using a serialized array. = is a more efficient query than LIKE, especially when you have wildcards, and your results should be more accurate. Indexing (MySQL database) should work better as well.


text:
Q: Two vertical lines in chart - chart.js
I am using chart and it is working fine too , I followed Chart Docs to understand how chart working but I am seeing two lines in chart , I was expecting only one line for y-axis , I have posted my entire code in this post , please find read one which marked as answer.
Any pointer would be appreciated.


text:
Q: Fitting a quadratic using regression when the y-intercept needs to be 0 I'm trying to fit a quadratic $a_0 + a_1x + a_2x^2$ by Polynomial Regression:
$$
\begin{pmatrix}
n &  \Sigma x_i  & \Sigma x_i\\
\Sigma x_i &  \Sigma x_i^2  & \Sigma x_i^3\\
\Sigma x_i^2 &  \Sigma x_i^3  & \Sigma x_i^4\\
\end{pmatrix}
\begin{pmatrix}
a_0\\
a_1\\
a_2\\
\end{pmatrix}=
\begin{pmatrix}
\Sigma y_i\\
\Sigma x_iy_i\\
\Sigma x_i^2y_i\\
\end{pmatrix}
$$
by Gaussian Elimination on the augmented matrix:
$$
\left[
\begin{array}{ccc|c}
n &  \Sigma x_i  & \Sigma x_i & \Sigma y_i\\
\Sigma x_i &  \Sigma x_i^2  & \Sigma x_i^3 & \Sigma x_iy_i\\
\Sigma x_i^2 &  \Sigma x_i^3  & \Sigma x_i^4 & \Sigma x_i^2y_i\\
\end{array}
\right]
$$
I'm not a matrix whizz, so how do I solve this using the same method when I know I want the y-intercept of the curve, $a0$, to be 0?

A: If you want $a_0$ to be $0$, then the curve you are trying to fit has equation $y = a_1 x + a_2 x^2$. If you derive the normal equations starting from this equation, you get
$a_1 \sum x_i^2 + a_2 \sum x_i^3 = \sum x_i y_i\\
a_1 \sum x_i^3 + a_2 \sum x_i^3 = \sum x_i^2 y_i$
Or
$\left[\begin{array}{cc|c}
\sum x_i^2 & \sum x_i^3 & \sum x_i y_i\\
\sum x_i^3 & \sum x_i^4 & \sum x_i^2 y_i
\end{array}\right]$
Derivation of Normal Equations
$y = a_1 x + a_2 x^2$
The error $\epsilon_i$ in the $i$th term is the difference between the predicted value $y(x_i)$ and the observed value $y_i$:
$\epsilon_i = y(x_i) - y_i = a_1 x_i + a_2 x_i^2 - y_i$
The total error is the sum of squares of these errors:
$E = \displaystyle\sum_i \epsilon_i^2 = \displaystyle\sum_i(a_1x_i + a_2x_i^2 - y_i)^2$
To find the values of the parameters $a_1$ and $a_2$ that minimize the total error, let $\dfrac{\partial E}{\partial a_1} = \dfrac{\partial E}{\partial a_2} = 0$:
$
\dfrac{\partial E}{\partial a_1} = \sum 2x_i(a_1 x_i + a_2 x_i^2 - y_i) = 0 \Rightarrow a_1 \sum x_i^2 + a_2 \sum x_i^3 = \sum x_i y_i\\
\dfrac{\partial E}{\partial a_2} = \sum 2x_i^2(a_1 x_i + a_2 x_i^2 - y_i) = 0 \Rightarrow a_1 \sum x_i^3 + a_2 \sum x_i^4 = \sum x_i^2 y_i\\
$


text:
Q: How to create an uncleared file? I am a beginner C++ programmer.
I want to create a binary file, that is uncleared with the previous information that was in it. This is easy to do with RAM, simply by making an array, but how do I do this on a hard drive?
How do I create a uncleared file?
In other words how do I retrieve data that was not "cleared" but just marked "empty".
However, if the OS does not allow it, can I launch linux from USB and run my software?

A: To keep the content of a file to be written on, you can open a file in append mode with:
[ofstream ofs ("filename", ios::binary | ios::app);][1]

All output operations append at the end of the file.  Alternatively, you could also use ios::ate so that the output position starts at the end of the file (but afterwards it's up to you).
With the usual read operations you can retrieve preexisting content, by first positionning yourself using seekp().


text:
Q: How to use a Future in a StreamBuilder in Flutter I'm trying to build my first mobile application with flutter and firebase.

*

*Error:
The argument type 'Future Function()' can't be assigned to the parameter type 'String'
 class ShowUserData extends StatefulWidget {
   @override
   _ShowUserDataState createState() => _ShowUserDataState();
 }

 class _ShowUserDataState extends State<ShowUserData> {

   final email = () {
     final userEmail =
         FirebaseAuth.instance.currentUser().then((user) => user.email);
     print('userEmail + $userEmail');
     return userEmail;
   };

   @override
   Widget build(BuildContext context) {
     return StreamBuilder(
         // stream: user.getUserData().asStream(),
         stream: Firestore.instance.collection('users').document(email).snapshots(),
         builder: (context, snapshot) {
           if (!snapshot.hasData) {
             return Text("Loading");
           }

           print('snapshot + $snapshot');
           var userDocument = snapshot.data;
           print('userDocument + $userDocument');
           return Text(userDocument['firstName']);
         });
   }
 }

A: For the first part of your code, consider something like this:
   Future<String> getUserEmail() async {
     final userEmail =
         FirebaseUser user = await FirebaseAuth.instance.currentUser();
     String userEmail = user.email;
     print('userEmail + $userEmail');
     return userEmail;
   };

That should solve that error (hence answering your question). Although the rest of the code will still fail. You should read up on futures and async programming.

Now my suggested solution for the whole thing.
Since you have 2 different async sources that create your stream, you might want to consider creating your own Stream! (Yes, streams are powerful like that).
In sequence, you're wanting to

*

*await on the future: .currentUser()

*use the result of that to create your firestore snapshot stream

Try something like this
class ShowUserData extends StatefulWidget {
   @override
   _ShowUserDataState createState() => _ShowUserDataState();
 }

 class _ShowUserDataState extends State<ShowUserData> {

   Stream currentUserStream() async* {
     FirebaseUser user = await FirebaseAuth.instance.currentUser();
     String userEmail = user.email;
     yield* Firestore.instance.collection('users').document(userEmail).snapshots();
   };

   @override
   Widget build(BuildContext context) {
     return StreamBuilder(
         // stream: user.getUserData().asStream(),
         stream: currentUserStream(),
         builder: (context, snapshot) {
           if (!snapshot.hasData) {
             return Text("Loading");
           }

           print('snapshot + $snapshot');
           var userDocument = snapshot.data;
           print('userDocument + $userDocument');
           return Text(userDocument['firstName']);
         });
   }
 }


text:
Q: How to get accurate timestamp from a signal handler on a posix-conform way? (Related post on meta)
As we can see in signal (7), gettimeofday() isn't a reentrant function, thus it can't be used in signal handlers.
But I want to get the clock on a posix-conform way - for timestamping from signal handlers - which is more accurate as a second.
Is there a way to do it?

A: According to the man page signal(7), the POSIX
function clock_gettime() is listed as a safe function which can be called safely from a signal handler. And this function can provide a precise timestamp for your signals.


text:
Q: Change select element options according to its identifiers react New react developer i'm learning by coding,
Here i have 'country' and 'city'.
There could be many more country or city boxes, each those 'country' has its own identifier and each city has its own city_id.
I need advice/help on this:
if user is changing one of those country boxes (from its select dropdown), then it should only affect those city boxes which is connected to it (these two has same value so they are connected identifier: "0-0-0-4" and city_id:"0-0-0-4"), others should stay to default. (one country box can be connected to many city boxes so there could be for example two city boxes with same city_id:"0-0-0-4")
In my code 'country' are in different component and cities in another
my code:
try it here codesandbox: https://codesandbox.io/s/react-cascading-select-forked-6lt4g0?file=/src/App.js

  const city = useSelector(
    (state: RootStateOrAny) => state.selection.city
  );

 const country = useSelector(
    (state: RootStateOrAny) => state.selection.country
  );

  that country contains : {identifier: "0-0-0-4",type:""}

  that city contains: {city_id:"0-0-0-4",mode:"hereShouldbeThatType"}

import React, { useState } from "react";
import "./styles.css";

const countriesData = [
  {
    name: "Germany",
    states: ["Duesseldorf", "Leinfelden-Echterdingen", "Eschborn"]
  },
  {
    name: "India",
    states: ["Delhi", "Kolkata", "Mumbai", "Bangalore"]
  },
  {
    name: "France",
    states: ["Auvergne", "Bretagne", "Corse", "Centre"]
  }
];

function Form() {
  const [{ country, state }, setData] = useState({
    country: "Germany",
    state: ""
  });

  const countries = countriesData.map((country) => (
    <option key={country.name} value={country.name}>
      {country.name}
    </option>
  ));

  const states = countriesData
    .find((item) => item.name === country)
    ?.states.map((state) => (
      <option key={state} value={state}>
        {state}
      </option>
    ));

  function handleCountryChange(event) {
    setData((data) => ({ state: "", country: event.target.value }));
  }

  function handleStateChange(event) {
    setData((data) => ({ ...data, state: event.target.value }));
  }

  return (
    <form onSubmit={() => console.log("Submitted")}>

Countries

            Box 1 type
            <select value={country} onChange={handleCountryChange}>
              {countries}
            </select>
            <input type="submit" />

            Box 2 type
            <select value={country} onChange={handleCountryChange}>
              {countries}
            </select>
            <input type="submit" />

cities

            Mode
            <select value={state} onChange={handleStateChange}>
              {states}
            </select>

            Mode
            <select value={state} onChange={handleStateChange}>
              {states}
            </select>

{" "}

            Mode
            <select value={state} onChange={handleStateChange}>
              {states}
            </select>

{" "}

            Mode
            <select value={state} onChange={handleStateChange}>
              {states}
            </select>

{" "}

{" "}

    </form>
  );
}

export default Form;

English is not my mother language so could be mistakes.


text:
Q: How to adjust the width of a pool \ Lane in visio Shape using c# Hi i was able to adjust all the shapes width and height of visio shapes programatically, but i was not able to adjust the width of the Pool \ Lane shape from visio BPMN Shapes.Why doesnt the width is not getting adjusted.
   shape.get_CellsSRC((short)Microsoft.Office.Interop.Visio.VisSectionIndices.
                       visSectionObject, (short)Microsoft.Office.Interop.Visio.VisRowIndices.
                       visRowXFormIn, (short)Microsoft.Office.Interop.Visio.VisCellIndices.visXFormWidth).ResultIU = 15;

whatever i tried it only takes the default size 7.25 but the height can be adjusted using the same code as below
shape.get_CellsSRC((short)Microsoft.Office.Interop.Visio.VisSectionIndices.
                       visSectionObject, (short)Microsoft.Office.Interop.Visio.VisRowIndices.
                       visRowXFormIn, (short)Microsoft.Office.Interop.Visio.VisCellIndices.visXFormHeight).ResultIU = 10;

How to adjust the width of the **Pool and Lane ** shape in visio 2013 using c#...??

A: I had the same problem when I was working with the "Pool / Lane" stencil.  I switched to the "CFF Container" instead and the C# code (same as in the question) allowed me to resize the width of the pool.


text:
Q: newbie error on installing python on OS X Lion via brew I get this error when running on OX Lion:
brew install python

Error: MD5 mismatch
Expected: c8cfcfd42ec9ab900fb3960a3308eef2
Got: f783444754861f9b33e9f4083bd97b60
Archive: /Users/jt/Library/Caches/Homebrew/distribute-0.6.21.tar.gz
(To retry an incomplete download, remove the file above.)

I remove file but same issue comes up with same hash value
The specific issue is mentioned here https://github.com/mxcl/homebrew/issues/7768
I guess I'm not understanding what the workaround is. Can someone explain to me what to do?
I'm using this method to get MySQLdb installed via mysql-python installation problems (on mac os x lion) ; the bottom part. If better ideas for getting python / mysql working - let me know
thx for any help

A: They simply replaced the MD5 value in Python formula. Try 'brew update' command and see if it works after that.
If all else fails you can edit the file yourself locally.
vi /usr/local/Library/Formula/python.rb

Just make the same change as outlined in diff:
https://github.com/martinploeger/homebrew/commit/0bf86f684fa97a15d6863c3bfe4a75d87c73b7d8