text:
Q: How to set style of some parts of text in DataGrid by condition in C# I need to combine more than one text and I want to show new text partially different style by condition.
For instance,
I have a datatable with columns (code,opt1,std1,opt2,std2,opt3,std3,opt4,std4). I want to combine code,opt1,opt2,opt3 and opt4 row values in configuration column of datagrid.
But also I want to show opt1 value (in configuration) bold, italic and underline if std1 is true; I want to show opt2 value (in configuration) bold, italic and underline if std2 is true; I want to show opt3 value (in configuration) bold, italic and underline if std3 is true; I want to show opt4 value (in configuration) bold, italic and underline if std4 is true.
my xaml code like that:
<Grid>
    <DataGrid x:Name="grid1" ItemsSource="{Binding Items}" HorizontalAlignment="Left"  Margin="10,10,0,0" VerticalAlignment="Top"  CanUserSortColumns="True"  CanUserAddRows="False"  AutoGenerateColumns="False" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding code}"  Header="code" />
            <DataGridTemplateColumn   Header="configuration" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Path=code}"/>
                            <TextBlock Text=" - "/>
                            <TextBlock Text="{Binding Path=opt1}">
                                //How to use Style and Trigger here?
                            </TextBlock>
                            <TextBlock Text=" - "/>
                            <TextBlock Text="{Binding Path=opt2}">
                                //How to use Style and Trigger here?
                            </TextBlock>
                            <TextBlock Text=" - "/>
                            <TextBlock Text="{Binding Path=opt3}">
                                //How to use Style and Trigger here?
                            </TextBlock>
                            <TextBlock Text=" - "/>
                            <TextBlock Text="{Binding Path=opt4}">
                                //How to use Style and Trigger here?
                            </TextBlock>
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Binding="{Binding opt1}"  Header="opt1" />
            <DataGridCheckBoxColumn Binding="{Binding std1}"  Header="std1" />
            <DataGridTextColumn Binding="{Binding opt2}"  Header="opt2" />
            <DataGridCheckBoxColumn Binding="{Binding std2}"  Header="std2" />
            <DataGridTextColumn Binding="{Binding opt3}"  Header="opt3" />
            <DataGridCheckBoxColumn Binding="{Binding std3}"  Header="std3" />
            <DataGridTextColumn Binding="{Binding opt4}"  Header="opt4" />
            <DataGridCheckBoxColumn Binding="{Binding std4}"  Header="std4" />
        </DataGrid.Columns>
    </DataGrid>

</Grid>

and C# codes like that:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataTable optionalPro = new DataTable();

        optionalPro.Columns.Add("code", typeof(string));
        optionalPro.Columns.Add("opt1", typeof(string));
        optionalPro.Columns.Add("std1", typeof(byte));
        optionalPro.Columns.Add("opt2", typeof(string));
        optionalPro.Columns.Add("std2", typeof(byte));
        optionalPro.Columns.Add("opt3", typeof(string));
        optionalPro.Columns.Add("std3", typeof(byte));
        optionalPro.Columns.Add("opt4", typeof(string));
        optionalPro.Columns.Add("std4", typeof(byte));

        optionalPro.Rows.Add("A01", "Option_ABC",false, "Option_ADB", true, "Option_CAF", true, "Option_ASD", false);
        optionalPro.Rows.Add("A02", "Option_AXC",true, "Option_ADB", true, "Option_CAD", false, "Option_AWD", false);
        optionalPro.Rows.Add("A03", "Option_AXC",true, "Option_SWD", false, "Option_ZAS", true, "Option_YHL", true);
        optionalPro.Rows.Add("A04", "Option_AAZ",false, "Option_MNK", true, "Option_DHG", true, "Option_AFL", false);
        optionalPro.Rows.Add("A05", "Option_CDE",true, "Option_KLM", true, "Option_SLH", false, "Option_AXD", true);
        optionalPro.Rows.Add("A06", "Option_HGF",false, "Option_SSD", false, "Option_CQL", false, "Option_KHG", true);

        grid1.ItemsSource = optionalPro.DefaultView;
    }
}

As a result, I see that screen:

but I want to show configuration column like that:

A: you need a regular Style for TextBlock with setter for FontWeight, FontStyle and TextDecorations.
apply it in CellTemplate using StaticResource
DataTrigger binds to Tag property in order to reuse it, since each TextBlock uses different std property. In CellTemplate each TextBlock has additional Tag binding.
DataTrigger Value is 1 because std columns are defined with byte type: true gets conveted to 1, false - to 0
<DataGrid>
 <DataGrid.Resources>
  <Style TargetType="TextBlock" x:Key="cfgText">
   <Style.Triggers>
    <DataTrigger Binding="{Binding Tag, RelativeSource={RelativeSource Self}}" Value="1">
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="FontStyle" Value="Italic"/>
        <Setter Property="TextDecorations" Value="Underline"/>
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </DataGrid.Resources>
 <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding code}"  Header="code" />
    <DataGridTemplateColumn   Header="configuration" >
     <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
       <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=code}"/>
        <TextBlock Text=" - "/>
        <TextBlock Text="{Binding Path=opt1}" Tag="{Binding Path=std1}" Style="{StaticResource cfgText}"/>
        <TextBlock Text=" - "/>
        <TextBlock Text="{Binding Path=opt2}" Tag="{Binding Path=std2}" Style="{StaticResource cfgText}"/>
        <TextBlock Text=" - "/>
        <TextBlock Text="{Binding Path=opt3}" Tag="{Binding Path=std3}" Style="{StaticResource cfgText}"/>
        <TextBlock Text=" - "/>
        <TextBlock Text="{Binding Path=opt4}" Tag="{Binding Path=std4}" Style="{StaticResource cfgText}"/>
       </StackPanel>
      </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTextColumn Binding="{Binding opt1}"  Header="opt1" />
    <DataGridCheckBoxColumn Binding="{Binding std1}"  Header="std1" />
    <DataGridTextColumn Binding="{Binding opt2}"  Header="opt2" />
    <DataGridCheckBoxColumn Binding="{Binding std2}"  Header="std2" />
    <DataGridTextColumn Binding="{Binding opt3}"  Header="opt3" />
    <DataGridCheckBoxColumn Binding="{Binding std3}"  Header="std3" />
    <DataGridTextColumn Binding="{Binding opt4}"  Header="opt4" />
    <DataGridCheckBoxColumn Binding="{Binding std4}"  Header="std4" />
 </DataGrid.Columns>
</DataGrid>


text:
Q: Google Calendar api permissions - Service account I have a script which modifies my work supplied GCal. For authentication I use an access/refresh token (like this: https://developers.google.com/people/quickstart/python).
I want to run the script in Docker now. For authentication I have decided to use a service account.
I have created the service account, shared my calendar with it and accepted the calendar. In the Google Console where you create the service account, I set the permission to "owner".
When I try to run the script using the service account (not in Docker yet) it returns only a subset of attributes for each calendar event. I can see that accessRole = freeBusyReader.
How do I grant write access to this service account? I have tried:
rule = service.acl().get(calendarId="myId", ruleId='user:service@myApp-351310.iam.gserviceaccount.com').execute()  # Get this from acl_items
rule["role"] = "owner"
service.acl().update(calendarId="myId", ruleId="user:service@myApp-351310.iam.gserviceaccount.com", body=rule).execute()

I have read about firmwide delegation and impersonation of users. I'm not sure if this is requred or not. Does anyone know how to do this?

A: The code to authenticate a service account is slightly different then the sample you were using for an installed application it is as follows.
credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)
credentials = credentials.create_delegated(user_email)

This video shows How to create Google Oauth2 Service account credentials. just make sure to enable the google calendar api.
Remember service accounts are only supported via domain wide delegation to users on your google workspace domain. You cant use a standard google gmail user.
I recommend following the Delegate domain-wide authority to your service account sample it shows how to set up the delegation to a service account from your workspace domain.  Just change out the section about admin sdk to that of google calendar as this is the api you are trying to connect to.
You add the user_Email being the user on your domain you want the service account to impersonate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XNA DrawableGameComponent mouse input problem I'm developing a simple board game, where my game board is represented as a DrawableGameComponent. In the update method of board I'm checking mouse input to determine which field on the board was clicked. The problem I'm encountering is that mouse click gets registered only once every 5-6 clicks.
Mouse click code is basic:
public override void Update(GameTime gameTime)
    {
        MouseState mouseState = Mouse.GetState();
        Point mouseCell = new Point(-1, -1);

        if (mouseState.LeftButton == ButtonState.Pressed && previousMouseState.LeftButton == ButtonState.Released)
        {
            mouseCell = new Point(mouseState.X, mouseState.Y);
        }

        // cell calc ...

        previousMouseState = mouseState;

        base.Update(gameTime);
    }

In the Game.cs, I'm just adding my board to Components collection.
Has anyone idea what I might be missing here?
EDIT: Actually, it's not just the mouse, keyboard input doesn't work properly either, so I've probably messed up DrawableGameComponent implementation altrough I have no idea how.
EDIT2: Found some folks here: http://forums.create.msdn.com/forums/p/23752/128804.aspx and here: http://forums.create.msdn.com/forums/t/71524.aspx having very similar problems.
After unsuccessful debugging I ditched the DrawableGameComponent and implemented manual LoadContent/Update/Draw calls and put all input collecting into game.cs. Works like a charm.
However, if someone has any explanation what could have went wrong (looks like DrawableGameComponent somehow clodges input) I'd really like to know.

A: The problem is, that if the mouse changes state between MouseState mouseState = Mouse.GetState(); and previousMouseState = mouseState;, then previousMouseState and mouseState will have the same value.
This can be maked almost imposible by moving those to lines as close to each other as posible.
public override void Update(GameTime gameTime)
{
    Point mouseCell = new Point(-1, -1); //moved this up, so that the mouseState and previousMouseState are as close to each other as possible.
    MouseState mouseState = Mouse.GetState();

    if (mouseState.LeftButton == ButtonState.Pressed && previousMouseState.LeftButton == ButtonState.Released)
    {
        mouseCell = new Point(mouseState.X, mouseState.Y);
    }
    //It is almost imposible, that the mouse has changed state before this point
    previousMouseState = mouseState; //The earliest place you can possibly place this line...

    // cell calc ...

    base.Update(gameTime);
}


text:
Q: In install4j, what does the variable sys.adminRights do? it appears automatically in the response var file When a user runs our installation/upgrade and gets a response var file for the next silent install, we get questions about the properties in that var file.
On of the properties is sys.adminRights (boolean property)
What does sys.adminRights do? I can't find any reference for it in the internet / install4j manual. I've also scanned the XML for this attribute, but it's not there.

A: This property is set by the "Request privileges" action and indicates if admin privileges were actually obtained.
It is used by the "Require installer privileges" which is added to the uninstaller and possibly to custom installer applications.


text:
Q: Delphi - DB Refresh alternative I am using Delphi with Firebird DB in a software that display many calculations and according to requirement I need to store and display the total whenever other dependent tables gets updated.
I am currently using the refresh method for several TIBTable components to display the result of these calculations to the user. considering this a multi user app and the fact that refresh make posting slow, is there any alternative to refresh or more optimized way ?

A: For a multi-user application, where clients need to receive notifications, one option is to use Firebird events to send a 'broadcast' message for every data change (SQL INSERT, UPDATE or DELETE).
Clients can 'register' (listen) for a specific message type, and whenever the Firebird server sends a message with this type, they will receive it, and run client application code, which in your case would refresh a user interface object to display the total.
While this can be a sufficient solution in many simple use cases, there are also some restrictions. I recently blogged about this topic here:

*

*Firebird Database Events and Message-oriented Middleware
(I am author of middleware libraries for Delphi and Free Pascal)

A: There's really no way around refreshing to get new data.  But if you were using IBObjects for your database access, you could use the TIBOTable.InvalidateBookmark method to have it only refresh specific rows.  This is a lot faster than calling Refresh, which refreshes the entire dataset.
Looking at the documentation, it doesn't appear that TIBTable has anything comparable, unfortunately.


text:
Q: Issue with unmarashalling a collection in JAXB using Jersey MOXy implementation I have an Object which has a collection element. I am certain that it has values in the collection. When the object values are unmarshalled, I do not get any single values in the XML output. Do you think the way I have named my wrapper object is incorrect?
Here is my code:
@XmlRootElement(namespace = "http://www.myself.com/schema/me/v16", name = "history")
@XmlAccessorType(XmlAccessType.NONE)
public class History extends SuperRecord {
    private List<PatientHistoryFinding> medicalHistory;

    @XmlElement(name = "medicalHistory")
    @XmlElementWrapper(name = "medicalHistoryList")
    public List<PatientHistoryFinding> getMedicalHistory() {
        return medicalHistory;
    }
    public void setMedicalHistory(List<PatientHistoryFinding> medicalHistory) {
        this.medicalHistory = medicalHistory;
    }
}

@XmlRootElement(namespace = "http://www.myself.com/schema/me/v16", name = "patientHistoryFinding")
@XmlAccessorType(XmlAccessType.NONE)
public class PatientHistoryFinding extends HistoryFinding {

    private String question;

    @XmlElement
    public String getQuestion() {
        return question;
    }
    public void setQuestion(String question) {
        this.question = question;
    }
}

@XmlAccessorType(XmlAccessType.NONE)
public abstract class SuperRecord{
    protected int id;

    @XmlElement
    public int getId() {
        return id;
    }

    @Override
    public void setId(int id) {
        this.id = id;
    }
}

A: Based on your mapping the expected XML is the following, chances are your XML does not have the appropriate namespace qualification:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:history xmlns:ns0="http://www.myself.com/schema/me/v16">
   <id>0</id>
   <medicalHistoryList>
      <medicalHistory/>
      <medicalHistory/>
   </medicalHistoryList>
</ns0:history>

Note that expected namespace on the root element is due to the namespace specified on the @XmlRootElement annotation on the History class:
@XmlRootElement(namespace = "http://www.myself.com/schema/me/v16", name = "history")
@XmlAccessorType(XmlAccessType.NONE)
public class History extends SuperRecord {


text:
Q: Find sphere intersection point I have a sphere which is originated at:
$$
    \begin{matrix}
    0 & 0 & 0
    \end{matrix}
$$
Its radius r is 150. I have a line which goes from: $$
    \begin{matrix}
    0 & 0 & 0
    \end{matrix}
$$
and passes through the point inside a sphere [x y z]. Knowing that line starts from origin and crosses [x y z], how to find out at what coordinates line will intersect with the sphere?

A: The line consists of the points $[\lambda x,\lambda y,\lambda z]$ with $\lambda\in\Bbb{R}$. The sphere consists of the points $[u,v,w]$ with
$$u^2+v^2+w^2=150^2.$$
So the points of intersection are the points $[\lambda x,\lambda y,\lambda z]$ with $\lambda\in\Bbb{R}$ such that
$$(\lambda x)^2+(\lambda y)^2+(\lambda z)^2=150^2.$$
It is not hard to see that the appropriate values for $\lambda$ are
$$\lambda=\pm\sqrt{\frac{150^2}{x^2+y^2+z^2}}=\pm\frac{150}{\sqrt{x^2+y^2+z^2}}.$$


text:
Q: Removing first n characters from folder names I'm fairly new to batch, my problem is the following:
I have a long list of folders and need to delete the first 3 characters from each of their names. Think 01_Folder1, 02_Folder2, 03_Folder3 and so on. I've tried patching together pieces of CMD commands I've found on the web but could not come up with a script that does what I want it to do. I've even tried using VBScript as I'm more familiar with VB in general but failed to find a solution as well.
Is there an easy way to solve this?
Edit:
Here's my attempt; it's giving me a syntax error but as I am not versed enough in CMD, I cannot really see why:
setlocal enableextensions enabledelayedexpansion
for /d %%i in ("%~dp0*") do (set name=%%i && ren "!name!" "!name:~3!")
endlocal

A: The FOR command line does not work because of assigned to loop variable i is the name of a directory with full path and so removing the first three characters results in removing drive letter, colon and backslash from path of the directory and not the first three characters from directory name. Further the full qualified directory name is assigned with an additional space to environment variable name because of the space between %%i and operator &&.
One solution would be:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /d %%i in ("%~dp0*") do set "name=%%~nxi" && ren "%%i" "!name:~3!"
endlocal

The disadvantage of this solution is that directory names with one or more exclamation marks in name or path are not processed correct because of enabled delayed expansion resulting in interpreting ! in full directory name as begin/end of a delayed expanded environment variable reference.
Another solution is quite simple with using just the command line:
@for /D %%i in ("%~dp0*_*") do for /F "tokens=1* delims=_" %%j in ("%%~nxi") do @ren "%%i" "%%k"

The outer FOR searches in directory of the batch file for non-hidden subdirectories matching the pattern *_*.
For each directory name assigned with full path to loop variable i one more FOR command is used which processes just the string after last backlash (directory name without path) and splits the string up into substrings (tokens).
The string delimiter is an underscore as defined with option delims=_. The option tokens=1* tells FOR to assign first underscore delimited string to specified loop variable j and everything after one or more underscores after first underscore delimited string to next but one loop variable k according to ASCII table.
The inner FOR would ignore a directory name on which first substring starts with a semicolon as being the default end of line character. But in this case no directory has ; at beginning of its name.
There is one problem remaining with this command line. It does not work on drives with FAT32 or exFAT as file system, just by chance on drives with NTFS file system. The reason is that the list of non-hidden directories changes in file system while the outer FOR iterates over the directory entries matching the pattern.
A better solution loads first the list of directories to rename into memory of Windows command process which is processing the batch file before starting with renaming the directories.
@for /F "delims=" %%i in ('dir "%~dp0*_*" /AD-H /B 2^>nul') do for /F "tokens=1* delims=_" %%j in ("%%i") do @ren "%~dp0%%i" "%%k"

FOR executes in this case in background one more command process with %ComSpec% /c and the command line within ' appended as additional arguments. So executed in background is with Windows installed to C:\Windows:
C:\Windows\System32\cmd.exe /c dir "C:\Batch\File\Path\*_*" /AD-H /B 2>nul

DIR searches in directory of the batch file for

*

*non-hidden directories because of option /AD-H (attribute directory and not hidden)

*matching the wildcard pattern *_*

*and outputs just the directory names in bare format because of option /B without path to handle STDOUT (standard output) of background command process.

Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
FOR respectively the Windows command process processing the batch file captures everything written to standard output handle of background command process and starts processing it as described above after started cmd.exe terminated itself. So there is in memory already a list of directory names and so the executed REN command does not result anymore in a changed list of directory names on processing one after the other.
Please note that a directory with name 01__Underscore_at_beginning is renamed to Underscore_at_beginning and not to _Underscore_at_beginning by both single line solutions.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*echo /?

*endlocal /?

*for /?

*ren /?

*set /?

*setlocal /?


text:
Q: Is there a way or a browser extension to bring the focus to the highlighted search result in a browser (Chrome)? So that if there is a link, for example, you could press the key and then [ENTER] to follow it.
The emphasis is on "highlighted", not just tabbing around a page. Probably not a real technical feasibility unless said item is actually "focusable".

A: The TAB key is something you might want to look into. You can use it to navigate UIs in the entire system (Windows at least, don't know about other operating systems).
In Google search, once you get to the results page, hitting TAB will make a little window saying "Skip to main content". You can press ENTER, and it will bring you to the first result. After that, you can continue navigating by continuing to press TAB. This will bring you to a couple of thinks related to the result, and will then move on to the next result.
Image of "Skip to main content" in Google (cannot embed posts :( )

A: In Windows after highlighting the text, press Shift+F10 to open the context menu, then press:

*

*S: to search the highlighted text.

*T: to open the highlighted link in a new tab.

*W: to open the highlighted link in a new window.

*G: to open the highlighted link in an incognito window.


text:
Q: Gradle 6 migration settings.gradle.kts I've got the following code in the settings.gradle.kts, which is works fine in gradle 5
rootProject.name = "server"

val pluginsRepoUrl: String by settings
val repoUsername: String by settings
val repoPassword: String by settings

pluginManagement {
    repositories {
        maven {
            url = uri(pluginsRepoUrl)
            credentials {
                username = repoUsername
                password = repoPassword
            }
        }
    }
}

I want to upgrade to gradle 6 but this code is not works and gives me a following error:
e: .../settings.gradle.kts:10:23: Unresolved reference: pluginsRepoUrl

The values comes from the gradle.properties file.

A: In Gradle 6, the behavior of the pluginManagement {} block was changed:

Previously, any pluginManagement {} blocks inside a settings script were executed during the normal execution of the script.
Now, they are executed earlier in a similar manner to buildscript {} or plugins {}. This means that code inside such a block cannot reference anything declared elsewhere in the script.

(emphasis mine)
This means that you cannot reference the variables declared outside of that block. To fix this, move those declarations inside the pluginManagement {} block:
pluginManagement {
    val pluginsRepoUrl: String by settings
    val repoUsername: String by settings
    val repoPassword: String by settings
    repositories {
        ...


text:
Q: Android Wear resource directory I'd like an existing smartphone app to look good a smartwatch.
What is the correct  resource directory name for Wear layouts?
I tried res/layout-wear, but the console says that this resource directory name is invalid.

A: you need an additional wearable module, which looks like a normal android projects, but it is only for wearable. You'll have res/ too, where you will have only the layout of your wearable application. Here you can find more info


text:
Q: Python: looking for a string within a string and then returning the strings around it import time
with open('txt.txt', 'r') as myfile:
    data=myfile.read().replace('\n', '')
pdf_content = data.split(" ")`
vocab = input('Vocab word to search for: ')

if vocab not in pdf_content:
    print('word not found....')
if vocab in pdf_content:
    for vocab in pdf_content:
        print((" ".join(pdf_content[1])))
time.sleep(200)

I want to basically search a body of text for a certain word and return a group of words around that 1 word.
ex. your paragraph is the quick brown fox jumped over the lazy dog
and we wanted to search for brown, it would return quick brown fox since those are the surrounding words. I'm not sure how to do this but help would be greatly appreciated

A: You could use a regular expression:
import re

text = 'the quick brown fox jumped over the lazy dog'

word = "brown"
for match in re.finditer(r"\w+\W+{}\W+\w+".format(word), text):
    print(match.group())

Output
quick brown fox

Regex

*

*\w+ matches a word

*\W+ followed by one or more characters that are not words

*followed by the chosen word, in this case 'brown'

A: Or a one-liner:
print(' '.join(s.split()[s.split().index(s2)-1:s.split().index(s2)+2]))

Demo:
s = 'the quick brown fox jumped over the lazy dog'
s2 = "brown"
print(' '.join(s.split()[s.split().index(s2)-1:s.split().index(s2)+2]))

Explanation:

*

*join the strings of the index-1 to index+1 (+2 in this case)

*index meaning the index of s2 in the split list from s

A: Try splitting the words and use indices:
pdf_content = "the quick brown fox jumps over the lazy dog"
word = "brown"

words = pdf_content.split()
pos = words.index(word)
found = word
if pos > 0:
    found = words[pos - 1] + " " + found
if pos < len(words) - 1:
    found = found + " " + words[pos + 1]

print(found)


text:
Q: Does wifi need to be on for AirDrop, even if using ethernet connection? My iMac is connected to my network with an ethernet cable - as such I have turned wifi off, to ensure that I am using the wired network, rather than the much slower wifi network.
AirDrop never seems to work on that iMac, whereas I can AirDrop easily between my iOS devices and MacBook (which is on wifi).
I have only just clicked that these two points may be related. For AirDrop to work do I need:

*

*All devices to be connected to the same wifi network?

*Wifi to be switched on, but not connected, on the iMac?

*Something else?

If I need wifi to be enabled on the iMac, can I "forget" my home wireless network without iCloud forgetting it on my other devices?

A: Please turn on wifi on the iMac, but no need to connect to any network. Since you are connected via Ethernet your syncing iMac with iCloud will happen without any interruption. Now you will be able to use Airdrop and iCloud syncing simultaneously. Hopes this will help.


text:
Q: Python - I can only save one thing with append? Here is my code. I can't save more than 1 thing in the list, I don't know why.
The point of the program is to save words (like "banana") and then add a description to it ("yellow"). I'm using Python 2.7
word = []
desc = []

def main_list():

    print "\nMenu for list \n"
    print "1: Insert"
    print "2: Lookup"
    print "3: Exit program"

    choice = input()
    print "Choose alternative: ", choice

    if choice == 1:
        insert()
    elif choice == 2:
        look()
    elif choice == 3:
        return
    else:
        print "Error: not a valid choice"

def insert():
    word.append(raw_input("Word to insert: "))
    desc.append(raw_input ("Description of word: "))
    main_list()

def look():
    up = raw_input("Word to lookup: ")
    i = 0
    while up != word[i]:
        i+1
    print "Description of word: ", desc[i]
    main_list()

A: You're not updating the value of i. You're calling i+1 which doesn't really do anything (it simply evaluates i + 1 and discards the result). Do instead i += 1 which seems to work.
Furthermore that's a rather strange approach to creating a dictionary, when you have a built-in data structure for that - the dictionary ({}).

A: In general, you should not use two list to save the words and their respective descriptions.
This is a classic case for using a dictionary, which will also help you once you have a lot of words, as you do not need to loop over all entries to find the corresponding description.
words = {}

def main_list():

    print "\nMenu for list \n"
    print "1: Insert"
    print "2: Lookup"
    print "3: Exit program"

    choice = input()
    print "Choose alternative: ", choice

    if choice == 1:
        insert()
    elif choice == 2:
        look()
    elif choice == 3:
        return
    else:
        print "Error: not a valid choice"

def insert():
    word = raw_input("Word to insert: ")
    desc = raw_input ("Description of word: ")
    words[word] = desc
    main_list()

def look():
    up = raw_input("Word to lookup: ")
    print "Description of word: ", words.get(up, "Error: Word not found")
    main_list()


text:
Q: Is it possible to get the Standard Field "Name" increased form 80 characters lenght to a greater legth by Salesforce Support? Is it possible to get the Standard Field "Name" increased form 80 characters lenght to a greater length by Salesforce Support via a case?
I know, it's not possible changing this as an Admin. But I never tried to open a case and ask Salesforce for that. I ask because opening and babysitting a case is not a quick journey, and I'm sure that someone has already asked the support.
I know also that there is an idea for this. But it has aged for years already and this is no help now.
Reason is: this field is very special and plays a major role for lookup relationships and search. 80 characters is way too short. Before we start to go with other quirks, a want to make sure, that there is really NO way to get it adjusted, even not with super-powers....

A: No - it is not possible to increase the Name field from 80 chars. I raised a case with Salesforce Support regarding this, as I was curious. The response is below:

Currently, this is not yet possible as it is a limitation of the
  coding. But our Research and Development Team is welcome to future
  changes and additional capabilities to our Standard Features.
The most possible thing that we can do as of this moment is to vote on
  this in the community board. I strongly suggest that you and users
  from your Organization vote on this idea. Here's a link where you can
  vote and promote this functionality already requested by other users
  as well:
Increase Name field length from 80 to 255
  https://success.salesforce.com/ideaView?id=08730000000kowTAAQ
Having said that, we'll now temporarily close your case for now to
  avoid sending you additional requests for updates. However, please be
  assured that you can re-open the case anytime if you still require
  assistance. You may also create a new case and we'll be happy to
  assist you.

A: There is nothing really special about a name. That is why I use auto-naming whenever I can.
If you want to have a special name, create a new field called "My Special Name". You can have any length you want, up to 255 characters. If you want to make this field an index key, aka searchable via universal search, make it an external id. Then it is automatically indexed and searchable. Make it a required field if you want, and you can require that it be unique. If you don't want to use up one of external Ids's, you can make a service request to salesforce.com that a custom field on an object be indexed.
Hide the auto name field whenever you can. Users cannot edit it, so why show it to them


text:
Q: I want to filter the NSFW url on discord.js This is the code
const body = await fetch(`https://shot.screenshotapi.net/screenshot?&url=${encodeURIComponent(args.join(" "))}&fresh=true&output=json&file_type=png&wait_for_event=load`)
           .then(res => res.json().catch(() => { }));

            if (args.length === 0) return message.channel.send({
               embed: {
                    color: config.embedcolor,
                    title: "Please provide a valid URL!"
               }
            })
            if (!body) return message.channel.send({
                embed: {
                    color: config.embedcolor,
                    title: "❌ Error"
                }
            })
            if (body.error) return message.channel.send({
                embed: {
                    color: config.embedcolor,
                    title: "❌ Error URL not found"
                }
            });

            const embed = new MessageEmbed()
                .setTitle(` ${body.url} `)
                .setColor(config.embedcolor)
                .setTimestamp()
                .setFooter("https://cdn.discordapp.com/attachments/725019921159028808/739770316754256012/Screenshot_20200803-1459592.png")
                .setImage(`${body.screenshot}`)
            message.channel.send(embed);
        }
    }

I don't know how to filter the NSFW url like
const link = ["pornhub.com","nhentai.net", and more...]

If someone send that link, bots sends an error/smth.
sry, my English bad

A: Assuming you have an exhaustive list of hostnames to block, you can check something like this:

const blocked = ['pornhub.com', 'nhentai.net']

const Result = {
    Ok: 'Ok',
    Blocked: 'Blocked',
    Invalid: 'Invalid',
}

const checkUrl = urlStr => {
    try {
        const url = new URL(urlStr)

        return blocked.some(b => url.hostname === b)
            ? Result.Blocked
            : Result.Ok
    } catch {
        return Result.Invalid
    }
}

for (const url of [
    'https://google.com',
    'https://pornhub.com',
    'https;//invalid.com',
]) {
    console.log({ url, result: checkUrl(url) })
}


text:
Q: How do I extract a string of text that lies between two (brackets) or n Bracklets I need a regular expression or scripting code to select all the text between two outer brackets.
Example of message Body : some text(text here(possible text)text(possible text(more text)))end text
the result that i want Result: (text here(possible text)text(possible text(more text)))
the second example:

(Jack Tomy)(Smith)(ti,ab(((Abbott near/10 (assay* OR test* OR analy*
  OR array)) OR (Abbott p/1 Point P/1 Care) OR ARCHITECT OR (CELL p/0
  DYN)) OR ((Alere near/10 (assay* OR test* OR analy* OR array)) OR
  (Alere NEAR/5 (Triage P/1 System)) OR INRatio OR Afinion) OR
  ((Beckman* p/1 Coulter near/10 (assay* OR test* OR analy* OR array))
  OR ((Beckman* p/0 Coulter) near/2 AU????) OR (UniCel* P/1 DxC) OR
  (UniCel* p/1 DxI) OR ( Beckman* near/5 Access) OR (Access* p/1
  Systeme) OR (CytoFLEX OR (cyto p/0 flex)) OR (UniCel* p/1 DxH) OR
  ((Coulter* p/1 LH) OR CoulterLH)) OR ((Ortho p/0 Clinical P/1
  Diagnostics) OR VITROS OR (vitros p/1 System*) OR (VITROS* p/1 ECiQ)
  OR ORTHOTM OR (orthotm p/1 VISION) OR (ORTHO p/1 AutoVue*)) OR
  ((Instrumentation p/0 Laboratories) OR HemosIL OR ACLTOP OR (ACL p/0
  ELITE) OR (GEM* P/1 Premier) OR GEMOPL) OR ((Radiometer near/10
  (assay OR test* OR analy* OR array)) OR (AQT?? p/0 FLEX) OR (ABL??
  p/0 FLEX) OR HemoCue*) OR ((Nova p/0 Biomedical) OR StatStrip OR (STAT
  p/0 PROFILE*) OR ((Nova p/0 Biomedical) near/1 Prime) OR STATPROFILE*)
  OR (((Siemens p/0 Healthcare) near/10 (assay* OR test* OR analy* OR
  array)) OR (ADVIA p/0 Centaur) OR (Dimension p/0 Vista) OR RAPIDPOINT))) and (ud(>20170101)) (see attachment)

the same thing I want to extract the text from "()" (Jack Tomy)(Smith)(ti,ab(((... my output jack Tomy Smith ti,ab(........)
.)
var messageBody = message.getPlainBody();
var ssFile = DriveApp.getFileById(id);

DriveApp.getFolderById(folder.getId()).addFile(ssFile);
    var ss = SpreadsheetApp.open(ssFile);
    var sheet = ss.getSheets()[0];
    sheet.insertColumnAfter(sheet.getLastColumn());
    SpreadsheetApp.flush();
    var sheet = ss.getSheets()[0];
    var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn() + 1)
    var values = range.getValues();
    values[0][sheet.getLastColumn()] = "Search Strategy";
    for (var i = 1; i < values.length; i++) {

    var y = messageBody.match(/\(.*\)/ig); //my regexp to extract the the text between ()
    if (y)
    values[i][values[i].length - 1] = y.toString();
    }

I've been trying for hours, I tired a lot of examples but failed.
any help will be gratefully received.
Thanks a lot.

A: Simply match everything between the two brackets:

const str = 'some text(text here(possible text)text(possible text(more text)))end text';
const match = str.match(/\((.*)\)/);
console.log(match[0])

A:

var string = "some text(text here(possible text)text(possible text(more text)))end text";
console.log(string.match(/.*?(\(.*\))[^\)]*/)[1]);


text:
Q: The server committed a protocol violation Error even after using useUnsafeHeaderParsing Im trying to get XML reposnce from External URL in MVC.
This is my Code :
        Uri uri = new Uri("http://101.10.3.111:8600/out");
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";

        request.ServicePoint.Expect100Continue = false;
        request.KeepAlive = false;

        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                // as an xml: deserialise into your own object or parse as you wish
                var responseXml = XDocument.Load(response.GetResponseStream());
                Console.WriteLine(responseXml.ToString());
            }
        }
        catch (Exception ex)
        {

        }

and it gives this error :
{"The server committed a protocol violation. Section=ResponseStatusLine"}

if i add this to web.config  :
  <system.net>
    <settings>
      <httpWebRequest useUnsafeHeaderParsing="true"/>
    </settings>
  </system.net>

errors changed to this :
{"The underlying connection was closed: The connection was closed unexpectedly."}

Also if i call (copy\paste) the url into Browser it gives me output file.


text:
Q: Custom Keyboard: ASCII Codes vs KEYCODE I am working on a Gamer's Keyboard for Android. The idea is to emulate several different layouts that are more centric to gamers.
I've come across something that I would like advice on. The current android:codes use ASCII values (http://www.asciitable.com/). There are several keys that do not have an ASCII value assigned to them. I do see that there are KEYCODES for many keys though (https://developer.android.com/reference/android/view/KeyEvent). Can these be used in place of ASCII values in android:codes? How could I use this in the following example:
QWERTY.XML
<Row>
    <Key android:codes="49,33" android:keyLabel="1" android:popupCharacters="1!"
        android:popupKeyboard="@xml/keypopup"
        android:keyEdgeFlags="left"/>
    <Key android:codes="50,64" android:keyLabel="2"  android:popupCharacters="2@"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="51,35" android:keyLabel="3"  android:popupCharacters="3#"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="52,36" android:keyLabel="4"  android:popupCharacters="4$"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="53,37" android:keyLabel="5"  android:popupCharacters="5%"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="54,94" android:keyLabel="6"  android:popupCharacters="6^"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="55,38" android:keyLabel="7"  android:popupCharacters="7&"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="56,42" android:keyLabel="8"  android:popupCharacters="8*"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="57,40" android:keyLabel="9"  android:popupCharacters="9("
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="48,41" android:keyLabel="0"  android:popupCharacters="0)"
        android:popupKeyboard="@xml/keypopup"/>
    <Key android:codes="-5" android:keyIcon="@drawable/sym_keyboard_delete"
        android:keyWidth="20%p"
        android:isRepeatable="true"
        android:keyEdgeFlags="right"/>
</Row>

Will I need to add anything to the Java file?
I do have to admit, that this is my first time working on an Android app. I am using Android Studio 3. For the most part, I have it working, there are some things I need to work out, etc. The above would help out though. :D
Thanks everyone!


text:
Q: Operation along third dimension of two 3-D arrays in R I have two 3D arrays, the dimensions are specifically [Longitudes][Latitudes][Time] and the two array are temperature and precipitation observations in space and time.
I would like to obtain a 2D matrix [Longitudes][Latitudes] of the correlation (along the [Time] dimension) between the temperature and precipitation array for each specific Longitude-Latitude point.
The function apply() only work with one array at the time and the only solution I came out with is a basic loop, being Ts and Ps respectively the Temperature and Precipitation 3D arrays this is what I wrote:
corr.matix <- array(dim = dim(Ts)[c(1,2)])
  for (i in seq(dim(Ts)[1])){
    for (j in seq(dim(Ts)[2])){
      corr.matix[i,j] <- cor(Ts[i,j,],Ps[i,j,])
    }
  }

It works, however it is slow.
My question is, is there a faster (vectorised?) way to solve this simple problem in R?

A: It would help to have some sample working code to test, but could map2() from package purrrhelp?
See https://purrr.tidyverse.org/reference/map2.html


text:
Q: wpf toolkit datagrid column sorting Hi I have a column called Temperature in my datagrid which displays the temperature values. I want to sort this column on click, so I set the CanUserSort and SortMemberPath to the respective values in viewmodel. But the sorting is not taking into consideration the negative values, it is treating them positive. How to resolve this issue.?

A: Please check the Datatype of the items you sort.


text:
Q: Setting up simple communication between a PostgreSL local database and a cloud database We set up a local PostgreSQL DB to capture data from our chemical process. Now, we would like to send that data up to a cloud DB. We would like the cloud to hold all the data the local has ever received and for the local DB to only keep the last 2 weeks of data it has received.
Specifics:

*

*Our DB is pretty simple. Only a table that is updated with a new row every 3 seconds from the unit.

*We are a scientific company so I was thinking about using Flask (bc python) to do this, but TBH I don't really know if that is the right direction or overkill

*We don't know which hosting service would be best to use for this kind of simplistic need.

*Local computer: Windows 7
Others:

*

*I can connect to it on our local network, cannot find a way to connect to the DB remotely.

Thank you for the help!

A: It seems that you want to centralize data in order to run some data analytics, right? You are probably looking for a data warehouse solution such as Redshift: https://aws.amazon.com/redshift/


text:
Q: mongoose: when timestamps: true auto deletes document after 1 minute? With the following scheme below, documents get deleted after approx 1 minute. The intention is to have the createdAt and updatedAt fields for each document.
let userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50,
    },
    email: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 255,
        unique: true,
    },
    password: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 1024,
    },
}, {
    timestamps: true
});


text:
Q: groupby and count values when column contains list of values with pandas My DataFrame looks like:
title     type      country    release_year
 a        movie      USA       2018
 b        movie      USA,UK    2018
 c        movie      USA       2018
 d        movie      UK        2018
 e        movie      USA       2019
 f        movie      UK        2019

I want to count per country how many movies were released by year. Therefore I'm applying the following:
result = df.groupby(['release_year', 'country'])['country'].count().reset_index(name='counts')

and this is what I´m getting:
release_year     country       counts
2018              USA           2
2018              USA,UK        1
2018              UK            1
2019              USA           1
2019              UK            1

However, I would like to get something where USA,UK is counted once under USA and UK and not separate like:
release_year     country       counts
2018              USA           3
2018              UK            2
2019              USA           1
2019              UK            1

I've tried before grouping as well:
pd.Series(df.country.str.split(', ').sum()).value_counts()

which gives me the result per country, but not grouped by release_year. I couldn't match both conditions.

A: You can use pandas.DataFrame.explode(...) for your purpose:
df["country"]=df["country"].str.split(",")
df=df.explode("country")

Outputs:
  title   type country release_year
0     a  movie     USA         2018
1     b  movie     USA         2018
1     b  movie      UK         2018
2     c  movie     USA         2018
3     d  movie      UK         2018
4     e  movie     USA         2019
5     f  movie      UK         2019

A: You can do str.split and explode then groupby:
(df.assign(country=df.country.str.split(',\s*'))
   .explode('country')
   .groupby(['release_year','country']).size()
   .reset_index(name='counts')
)

Output:
   release_year country  counts
0          2018      UK       2
1          2018     USA       3
2          2019      UK       1
3          2019     USA       1


text:
Q: Use asp.net membership via LDAP We have an intranet system that uses asp.net with the sql membership provider.  We have about 400 users setup in the intranet.  These can include employees, contractors, etc.
I'm trying to find out if there is a way to expose our existing asp.net sql membership database so it can be used by other systems via LDAP.  For example, we have 2 multi-function copy machines that are used heavily for scanning to email.  Currently we manually maintain the email address book saved on the copiers, but we'd like to configure the copier to use LDAP and pull the names and email addresses automatically from the intranet membership database.
Can the asp.net membership be exposed to be used via LDAP?  The systems would only be consuming the user information (read-only); no need to write changes back to the membership database.
Thanks in advance.

A: For me the best way is to install an ADAM (Active-Directory Application Mode) on W2K3 (R2) or an LDS (Lightweigth Directory Server) on W2K8 (R2) if you prefer Microsoft solutions or OpenLDAP, OpenDS for open source solution. And then, synchronize your SQL Database with this 'tiny' LDAP server. And why not replace the SQL membership with an LDAP server, it's a bit more standard for authentication.


text:
Q: duplicate mysql comment entries with ajax powered social network? trying to solve a bug! I have an ajax powered social network (with like and comments etc). I have a working comment script but when i have tested it I am getting a duplication of the original post and comment. Instead of adding a comment to just the post it is adding the comments and duplicating the post and comments each time when the data is output.
I have used jquery for ajax which works fine and PHP, probably something obvious as i new to jquery and php I was hoping for some help? Sorry for the armount of code I can reduce if required
Thanks
jquery
       $(".editable").live('click', function(){

        $(this).empty();

        $(this).mouseout(function() {

            var comment = $(this).html();
            var postid = $(this).attr("pid");
            var commentuserid = $("#loggedin").attr("uid");

            if(comment == ""){

                return false;

            }else{

                    //alert(comment);
                    //alert(postid);
                    //alert(commentuserid);

                    var datastring = 'comment=' + comment + '&postid=' + postid + '&commentuserid=' + commentuserid;

                    //save with ajax clear box and then load back in
                    $.ajax({
                    type: "POST",
                    url: "uploadcomment.php",
                    data: datastring,
                    success: function(data){

                    $(".usermsg").html(data);

                    }

                    });

            }
});

});

php giving double post when comment uploaded
     <?

    $sql = "SELECT post.post, post.posttime, post.pid_imageurl, post.likes, user.name,
    comments.comment, user.uid_imageurl, comments.comment_uid, post.pid
                FROM post
                INNER JOIN user
                ON post.uid=user.uid
                LEFT JOIN comments
                ON comments.comment_pid=post.pid
                ORDER BY pid DESC";

    $result = mysql_query($sql);

    while($row=mysql_fetch_assoc($result)){?>

    <?
    $pid = $row['pid'];
    $formattime = date("g:i:a",$row['posttime']);
    echo '
'.$row['post'].'
';
    echo '
Posted by '.$row['name'].' at '.$formattime. '
';
?>

    <div class="editable" pid="<? echo $row['pid'];?>" contentEditable="true">
             add comment...

    <?

    $sql_comments = "SELECT comments.comment, comments.comment_time, user.name, user.uid_imageurl FROM comments
                    INNER JOIN user
                    ON  comments.comment_uid = user.uid
                    WHERE comment_pid = '$pid' ORDER BY cid DESC";

    $result_comments = mysql_query($sql_comments);

      $numrows_comments=mysql_num_rows($result_comments);//num of rows

              if($numrows_comments==0) //no comments
            {
                 echo '
Comments

';
                 echo 'This post has no comments yet, be the first!';
                 echo '

';

            }else{
                  echo '
Comments

';
                  while($row=mysql_fetch_assoc($result_comments)){
                  $formattime_comment = date("g:i:a",$row['comment_time']);
                   echo '
'.$row['comment'].'
';
                   echo '
posted by '.$row['name']. ' at ' .$formattime_comment. '
';

            }//$sql_comments

            echo '

';

      }//else end

    }//$sql

    ?>

        -->

A: I believe you're looking for the ON DUPLICATE... UPDATE syntax. Combined with a unique index (comment_pid, post.pid or comment_pid, user.uid?), that will prevent dupes from happening and merely update a row (vs. inserting a new one) when one already exists with the same key.

A: I would first be inclined to believe
$(".usermsg").html(data);

should be altering the html of another element. It is possible your ajax is returning the whole html and adding that to just an inner element and not the container. If this is the case, alter your php to return only the comment that was posted, or change this
$(".usermsg").html(data);

to the container element. In this case, it is not duplicating, it is just adding extra html to the loaded page.
as a side note, it is definitely better to replace the whole comment block - depending on how you handle the page - than to just place in the comment that was added. This way your html will update if another user happened to be commenting as well. It will keep your comments as up to date as possible.
Little different if you are paginating, happen to be on some inner page and enough other comments were added to push the user to another page of comments. That's another story though.

A: Have you checked where the duplication is occuring? The server-side script that inserts/retreives the posts+comments could be working perfectly, and your client-side javascript is causing the duplication to occur by extracting too much from the page before doing the ajax call.


text:
Q: Re-assigning (specifically, incrementing) a variable in a bash script
Possible Duplicate:
How can I do command line integer & float calculations, in bash, or any language available?

I would like to simply re-assign a variable (to be specific, increment it by 0.050) in a bash script.  In the following script that I wrote, i is an (integer) index, and mytime is a decimal/double/float number.  "ps" (picosecond) is the unit of time that I am using in my calculations.
#!/bin/bash
mytime = 0.000
for i in {1..3}
do
echo "$i: $mytime ps"
mytime = mytime + 0.050
done

But, when I run this script using bash test.sh, I get these error messages:
test.sh: line 2: mytime: command not found
1:  ps
test.sh: line 6: mytime: command not found
2:  ps
test.sh: line 6: mytime: command not found
3:  ps
test.sh: line 6: mytime: command not found

Why does it seem to be interpreting mytime as a command or a function, instead of as a variable?  Can you please help me to correct this?

A: for i in $(seq 1 0.05 3); do
  # loop body
  echo i equals $i
done

A: Two problems:

*

*Don't use white space. An assignment is VAR=value, not VAR = value, VAR =value or VAR= value. It has to be one shell white space-delimited token, not two or three).

*The shell doesn't do arithmetic like that. For integer math, you can say VAR=$(($VAR+1)), or you can read this excellent question for a gazillion other ways (integer, floating point, infix, postfix, possibly even prefix, arbitrary precision, and the kitchen sink): how can I do command line integer & float calculations, in bash, or any language available?


text:
Q: Minimum of $f(x)=\sqrt{9x^{2}+1}-3x-2 $ Let
$$f(x)=\sqrt{9x^{2}+1}-3x-2 $$

*

*Show that $f$ is bounded from below by $-2$
$$\forall x\in \mathbb{R}\quad f(x)>-2 $$

*Is $-2$ the minimum value of $f$ ?

Indeed,
let $x\in \mathbb{R}$
\begin{align}
f(x)>-2 &\iff \sqrt{9x^{2}+1}-3x-2>-2\\
&\iff \sqrt{9x^{2}+1}>3x \\
&\implies 9x^{2}+1>9x^2 \\
&\implies 1>0
\end{align}
then $$\forall x\in \mathbb{R}\quad f(x)>-2 $$ which means $f$ is bounded from below by $-2$

*

*Is $-2$ the minimum value of $f$ ?

I can't show that $-2$ is not a value of f(x) to say that $-2$ isn't minimum value of $f$
Beware: No differentiability

A: Your $f(x)>-2$ argument is problematic because, as it is writtten, you can't go from $1>0$ in the bottom back to $f(x)>-2$. An easy fix is by replacing the last two $\Rightarrow$ by $\Leftarrow$'s.
Alternatively, you can also rephrase the argument as follows: because $9x^2+1>9x^2$, we have
$$
f(x)>\sqrt{9x^2}-3x-2=3|x|-3x-2=3(|x|-x)-2\geq -2.
$$
And because the leftmost inequality is strict, $2$ is not the minimum value of $f$.

A: Note that
$$
\sqrt{9x^2+1}>3x
$$
if and only if one of the two conditions :
$$
x<0 \quad \mbox{or} \quad \begin{cases}
x\ge 0\\
9x^2+1>9x^2
\end{cases}
$$
is true. And, since $9x^2+1>9x^2$ is true $\forall x \in \mathbb{R}$, we can conclude that the function is $f(x)> -2 \quad \forall x \in \mathbb{R}$.
The same calculations shows that the equation $f(x)=-2$ has no solutions, so $-2$ is not a minimum for the function.

A: We have :
$$f(x)=\sqrt{9x^{2}+1}-3x-2 $$
So
$$ f'(x) = \frac{9x}{\sqrt{9x^2+1}} - 3$$
It is obvious that $f'(x)\lt0$ :
$f'(x) \lt  0  \iff \frac{9x}{\sqrt{9x^2+1}} \lt  3 \iff \frac{81x^2}{9x^2+1} \lt 9   \iff 0\lt9$ .
Now we know that $f(x)$ is strictly decreasing . Now we calculate limit using L'Hôpital :
$$ \lim_{x\to \infty}\sqrt{9x^{2}+1}-3x-2 = -2$$
Also we know $f(x) \neq -2$ as you calculate in your question Therefore we can conclude that $f(x)\gt -2$


text:
Q: Array-declaration issue in Python I have trouble declaring a two-dimensional list in Python. Below are two different matrices; A and R. When changing the content of a single cell I am successful in the R-matrix, but not so much in the A-matrix, as the value-input affect the entire column and not only the single cell.
Why does this happen? I would prefer the A-style of declaring the matrix.
n=6

A = [[0]*n]*n
R=[[0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0]]

R[1][1]=5
A[1][1]=5

print(R)
print(A)

The output from the two operations is:
[[0, 0, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
[[0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0], [0, 5, 0, 0, 0, 0]]

A: A = [[0]*n]*n creates multiple copies of the same list. This is why changing one affects every other one


text:
Q: Access denied (SA doesn't have storage.objects.create access) when trying to upload using a preSigned url to google cloud storage Background:
Have a cloud function deployed to GCP that is responsible for only creating a pre-signed URL for the cloud function invoker to use to upload to Cloud Storage. The front end is the invoker of the cloud function. The front-end then makes the XML request to put the object using the pre-signed URL. I have manually created the service account with the required roles and manually changed the default service account for the cloud function in the gcp console. I am successful in creating the service account, I only encounter my error when trying to use the pre-signed URL.
Problem:
Having issues trying to allow a client to upload a file via a pre-signed URL.
Error received
<?xml version='1.0' encoding='UTF-8'?>
<Error>
AccessDenied
<Message>Access denied.</Message>

urlsigner@<project>.iam.gserviceaccount.com does not have storage.objects.create access to <bucket-name>/<filename>.pdf.

</Error>

Code executes as a gcp cloud function and is used for generating.
Cloud function is the default service account function was updated to urlSigner
async createSignedUrl({
    contentType,
    fileName,
    userId,
  }: SignedUrlRequest): Promise<string> {
    const bucket = await this.cloudStorage.bucket(BUCKET_NAME);
    console.log(
      moment.utc().add('minutes', 15).toDate(),
      Date.now() + 15 * 60 * 1000
    );
    const options: any = {
      version: 'v4',
      action: 'write',
      expires: Date.now() + 15 * 60 * 1000,
      contentType,
    };
    const [signedUrl] = await bucket
      .file(`${userId}-${fileName}`)
      .getSignedUrl(options);

    return signedUrl;
  }

CORS temp json file
[
  {
    "maxAgeSeconds": 3600,
    "method": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    "origin": ["*"],
    "responseHeader": [
      "Content-Type",
      "Authorization",
      "Content-Length",
      "User-Agent",
      "x-goog-resumable"
    ]
  }
]

Steps used to create gcp resources
gcloud iam service-accounts create urlsigner --display-name="GCS URL Signer" --project=<project-id>
gcloud iam service-accounts keys create service_account.json --iam-account=urlsigner@<project-id>.iam.gserviceaccount.com
gsutil mb gs://<bucket-name>
gsutil iam ch serviceAccount:urlsigner@<project-id>.iam.gserviceaccount.com:roles/storage.admin gs://<bucket-name>
gsutil cors set cors-json-file.json gs://<bucket-name>
The upload code
export async function uploadDoc(preSignedUrl: string, file: File) {
  return await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', preSignedUrl, true);
    xhr.onload = () => {
      const status = xhr.status;
      if (status === 200) {
        console.log('uploaded');
        resolve('good to go');
      } else {
        console.log('failed to upload');
        reject('not good to go');
      }
    };

    xhr.onabort = () => {
      reject('aborted for idk');
    };

    xhr.onerror = () => {
      reject('Failed for idk');
    };

    xhr.setRequestHeader('Content-Type', file.type);
    const formData = new FormData();
    formData.append('verify-doc', file);
    xhr.send(formData);
  });
}

Lastly, verified that the cloud function has the Service-Token-Creator role necessary for signing the blob that gets sent back to the front-end and that under the bucket permissions the service account is listed with the storage admin role too. So at this point just scratching my head as to why I'm getting the error of access denied for lack of permissions by the service account.
Thanks in advance for whoever can assist.
PS.
I referenced this article as well https://medium.com/google-cloud/upload-download-files-from-a-browser-with-gcs-signed-urls-and-signed-policy-documents-f66fff8e425

A: From the error message I understand that you miss the storage.objects.create permission from the service account.
I would suggest you to make sure you have assigned all the necessary permissions according to this doc. You may use one of the Predefined Roles that include the aforementioned permission or create a Custom Role.
I would also suggest to make check if "Uniform bucket-level access" is activated. According to documentation:

If you enable uniform bucket-level access, you revoke access from
users who gain their access solely through object ACLs and prevent
users from administrating permissions using bucket ACLs.


text:
Q: How to store datas from a text file in c with variable number of lines and columns I have a text file containing datas that I want to read and store in a C structure. But this file can be different with a variable number of columns and rows, depending on the case being treated.
For example in one case we have this file (3 columns, 4 rows) :
56.3 1.8 25.9

-8.0 3.2 156.7

-9.4 -12.36 -11.8

-0.27 -0.04 0.1004

And in an other case we could have (2 columns, 5 rows) :
2.3 65.7

-8.2 3.4

9.4 -12.76

-0.27 -0.04

 0.56  45.8

I can't use fscanf because I don't know at each cases the number of datas I will read. With fgets I can't access to each datas separately. For example I would like to store datas like this :
datas[0][0] = line[0];
Do you have any idea to perform a such reading in C ?


text:
Q: Voltage drops keeping the current same as source/supply curent My question is "How to reduce the DC-voltages without changing current ". In my case I've 3.7 V Li-ion cell of 2 Amp i want to convert into 2 V and 2 A.

A: Try one of these switching regulators: -

This should just give you the general idea what you should be looking for although the part above is highly suited to your requirements and will work down to 2.7 volts from the Li ion battery. The resistor values shown can be any range within reason i.e. 140.9 kohm and 60.4 kohm. These are precise theoretical values so a 150 k and 62 k resistor would produce a nominal output of 2.05 volts.
You can of course use a linear regulator but it will be burning energy that you may want to conserve given it's a battery powered application. For instance, a linear regulator with 4.2 volts at the input and 2 volts at the output will be dissipating 4.4 watts of power (yuk) and probably need a fair sized heatsink.
A switching regulator on the other hand will be 90%+ efficient so, if the output power is 4 watts (2 volts, 2 amps) then the input power will be 2.22 watts thus the switcher only burns 220 mW.
As with all these things read the data sheet.
Texas Instruments are another source and, if you are prepared to have an external transistor supplementing the switcher then there are many more options.


text:
Q: Appending monad With just putChar I can do stuff like this:
f =
  do
    putChar 'a'
    putChar 'b'
    g
    putChar 'f'
    putChar 'g'

g =
  do
    putChar 'c'
    putChar 'd'
    putChar 'e'

And what I will find when I "run" this (by saying main = f) it'll just print the characters out in order.
What I'm looking for is a non-IO version. Something that works a bit like this:
f =
  do
    append 'a'
    append 'b'
    g
    append 'f'
    append 'g'

g =
  do
    append 'c'
    append 'd'
    append 'e'

And a function, say runAppend :: t a -> [a]
Such that runAppend f = ['a','b','c','d','e','f','g']
Naturally I'd want this to run in linear time (i.e. not suffer issues like ++ does when you do the concatenations in a bad order).
This seems like a fairly common use case so I'm guessing it exists, if someone could point me to it that would be good, I didn't want to reinvent the wheel.

A: The Writer monad does this:
> let g = tell "b" >> tell "c" >> tell "d"
> runWriter (tell "a" >> g >> tell "e")
((),"abcde")

A: You can use a Writer monad for this:
import Control.Monad.Writer
import Data.DList (DList)
import qualified Data.DList as DList

type Append c = Writer (DList c)

append :: c -> Append c ()
append = tell . pure

runAppend :: Append c () -> [c]
runAppend = DList.toList . execWriter

f, g :: Append Char ()

This is a bit more complicated than necessary because it uses a DList Char instead of a String. DList gives you an efficient Monoid instance for this case where you keep appending to the end.


text:
Q: Why delay in response is not working without an html tag? Below given is a sample node server code.
//Lets require/import the HTTP module
var http = require('http');

//Lets define a port we want to listen to
const PORT=8080;

//We need a function which handles requests and send response
function handleRequest(request, response){
     response.write("
hello
");       //version 1
     response.write("hello");              //version 2
     setTimeout(function(){
         response.write("
world
");   //version 1
         response.write("world");          //version 2
         response.end();
     }, 2000);

}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function(){
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

There are two versions of the same code. Try to run each one by one.
My confusion is with version 1 there is a delay in response as expected. And it prints
Hello
(delay)
world

But with version 2 the output is like
helloworld (without delay)

A: That's some browser-dependent behavior. You can try running curl -N localhost:8080 (-N is to use non-buffered stream) and you will see that the server sends response in two parts with the delay for both versions (as you expected it to behave).
When I request the server with Chrome, it behaves as you mentioned. When I do the same in Firefox, it waits the response to fully complete before rendering the result in both cases.


text:
Q: bash- conditional triangle error my task was to print whether the numbers given signify ISOSCELES,EQUILATERAL, or SCALENE triangle.
My code prints only ISOSCELES: Where's the error ?
#!/bin/bash
read a b c
if [ "$a" == "$b" ] && { [ "$b" = "$c" ] && [ "$c" = "$a" ]; }
then
    echo "EQUILATERAL"
exit 1
elif [ "$a" == "$b" ] && { [ "$b" = "$c" ] || [ "$c" = "$a" ]; }
then
    echo "ISOSCELES"
elif ([[ "$a" != "$b" ]] && [[ "$b" != "$c" ]] && [[ "$c" != "$a" ]])
then
    echo "SCALENE"
fi

A: There's a strange mixture of [, [[, = and == in your script. If you are using bash, I would suggest that you instead use (( )) for all of your numerical comparisons. This creates an arithmetic context, so it also means that you don't need to use $ to refer to your variables:
if (( a == b )) && (( b == c )) && (( c == a )); then echo "equilateral"
elif (( a != b )) && (( b != c )) && (( c != a )); then echo "scalene"
else echo "isoceles"
fi

The separate test for isosceles is unnecessary.

A: You can just count the number of different numbers to get the answer.
#!/bin/bash
read a b c
different=$(printf '%s\n' $a $b $c |
            sort -n                |
            uniq -c                |
            wc -l
         )

case $different in
    (1) echo EQUILITERAL ;;
    (2) echo ISOSCELES   ;;
    (3) echo SCALENE     ;;
esac

You should also verify the triangle inequality at the beginning:
#!/bin/bash
read a b c
sorted=$( printf '%s\n' $a $b $c | sort -n )
ineq=${sorted/$'\n'/+}
ineq=${ineq/$'\n'/>}
(( $ineq )) || exit 1

different=$( uniq -c <<< "$sorted" | wc -l )

case $different in
    (1) echo EQUILITERAL ;;
    (2) echo ISOSCELES   ;;
    (3) echo SCALENE     ;;
esac

A: *

*you mix == and = in your tests

*change the order, first test for EQUILATERAL, then for SCALENE, then you don't need to test for ISOSCELES (quartum non datur;-)

A: Try (use == or -eq for numbers):
   #!/bin/bash

   read a b c
   if [ "$a" == "$b" ] && { [ "$b" == "$c" ] && [ "$c" == "$a" ]; }
   then
      echo "EQUILATERAL"
  elif ([[ "$a" != "$b" ]] && [[ "$b" != "$c" ]] && [[ "$c" != "$a" ]])
  then
      echo "SCALENE"
  else
     echo "ISOSCELES"
  fi

A: That a bit simplified:
#!/bin/bash
read a b c
if [ "$a" -eq "$b" ] && [ "$b" -eq "$c" ] && [ "$c" -eq "$a" ];
then
    echo "EQUILATERAL"
    exit 1
elif [ "$a" -ne "$b" ] && [ "$b" -ne "$c" ] && [ "$c" -ne "$a" ];
then
    echo "SCALENE"
else
    echo "ISOSCELES"
fi

I think thats the purposed output:
$ echo "6 6 6" | ./script
EQUILATERAL
$ echo "6 6 5" | ./script
ISOSCELES
$ echo "4 5 6" | ./script
SCALENE

A: Take the sides of traingles as input using read command.
read a
read b
read c
if (( a == b )) && (( b == c )) && (( c == a ));
then
    echo "EQUILATERAL"
elif (( a != b )) && (( b != c )) && (( c != a ));
then
    echo "SCALENE"
else
    echo "ISOSCELES"
fi


text:
Q: $K$ is the fraction field of $R$, but $R$ is not an order in $K$.
*

*Give an example of non-trivial number field $K$ (so $K \not= \mathbb{Q}$) and a proper subring $R$ of $K$ such that $K$ is the fraction field of $R$, but $R$ is not an
order in $K$.

*Given that there exist solutions where $K$, $L_1$, $L_2$ are quadratic, give an example of two number fields $L_1$ and $L_2$ contained in a bigger number field $M$ such that $\mathcal{O}_{L_1L_2}\neq \mathcal{O}_{L_1}\mathcal{O}_{L_2}$.


text:
Q: Using regex to break string into a dictionary with key and values I am attempting to turn this list into a list full of dictionaries. Below I included a snippet of the full list Im using.
With row 4.1 as an example, I want:

*

*the key to be the row number, ('4.1')

*the values to include the title ('Properties occupied by  the company
(less $  43,332,898 \nencumbrances')

*and the four numbers after it as a list ['68,122,291',  '0',
'68,122,291', '64,237,046'].

I got the general loop for how I'd put together each separate dictionary. Where I am struggling is coming up with regex patterns to get the row title and row values. Its difficult since some of the row titles also include numbers. Another issue is that not all of the rows have four numbers at the end. For these instances, I just want the available numbers.  Any help figure out the regex to grab these would be appreciated.
    clean = ['4.1 Properties occupied by  the company (less $  43,332,898 \nencumbrances)  68,122,291  0  68,122,291  64,237,046 \n',
         '4.2 Properties held for  the production of income (less \n $    encumbrances)  0  0   0  0 \n',
         '4.3 Properties held for sale (less $  \nencumbrances)      0  0 \n',]

    clean_list = []

    for n in clean:
        row_num = re.findall(r'\d+\.',n)
        row_title =
        row_values =
        new_dict = {row_num: row_title, row_values}
        clean_list.append(new_dict)

A: Following the examples shared by you

*

*"4.1 Properties occupied by  the company (less $  43,332,898 \nencumbrances)  68,122,291  0  68,122,291  64,237,046"

*"4.2 Properties held for  the production of income (less \n $    encumbrances)  0  0   0  0"

*"4.3 Properties held for sale (less $  \nencumbrances)      0  0 "

for n in clean:
    row_num = re.search(r'$\d+\.\d+',n).group()
    row_title = re.search(r'(?<=\d+\.\d+).*?(?=((\d+,?)+ ?)+$)', n}.group()
    row_values = re.search(r'((\d+,?)+ ?)+$', n).group()
    new_dict = {row_num: row_title, row_values}
        clean_list.append(new_dict)

I would seriously recommend going through https://regexr.com/ and trying these patterns and messing with them to learn. The solution is not important. It's how you end up at it.

A: Not sure why you want a separate dictionary for each line, each with just one key. I would think it more useful to end up with one dictionary with several keys.
d = {}
for line in clean:
    parts = re.match(r"^([\d.]+)\s+(.*?)\s+(\d[\d,.]*)\s*(?:(\d[\d,.]*)\s*)?(?:(\d[\d,.]*)\s*)?(?:(\d[\d,.]*)\s*)?$",
            line, re.DOTALL)
    code, title, *values = parts.group(1,2,3,4,5,6)
    d[code] = (title, list(filter(None, values)))

For the sample data, the value of d would be:
{
  '4.1': (
    'Properties occupied by  the company (less $  43,332,898 \nencumbrances)',
    ['68,122,291', '0', '68,122,291', '64,237,046']
  ),
  '4.2': (
    'Properties held for  the production of income (less \n $    encumbrances)',
    ['0', '0', '0', '0']
  ),
  '4.3': (
    'Properties held for sale (less $  \nencumbrances)',
    ['0', '0']
  )
}

A: you can use split() to accommodate variable number of the last values into a list.  if your data always has the parenthesis you can use those as part of the pattern:
for n in clean:
    row_num, row_title, row_values = re.findall(
        r'^(\d+\.\d+)\s+(.*\))\s+(.*)$', n, re.DOTALL)[0]
    new_dict = {row_num: (row_title, row_values.split())}
    clean_list.append(new_dict)

keeping your use of re.findall().  output looks like:
[{'4.1': ('Properties occupied by  the company (less $  43,332,898 \n'
          'encumbrances)',
          ['68,122,291', '0', '68,122,291', '64,237,046'])},
 {'4.2': ('Properties held for  the production of income (less \n'
          ' $    encumbrances)',
          ['0', '0', '0', '0'])},
 {'4.3': ('Properties held for sale (less $  \nencumbrances)', ['0', '0'])}]

this retains the newlines, if you want those.


text:
Q: How to select first n items of list in netlogo I have a list and i want to do an operation on first 3 items of list if they are not 0.i can do my operation on each item by code below,but dont know how to do it for first 3 items.
foreach list2
[
 if (item ? list2 != 0)
  [
   set candidatelist lput (item ? list3) candidatelist
 ]
]

A: Here's a helper for getting the first n elements:
to-report take [n xs]
  report sublist xs 0 min list n (length xs)
end

Now we can write:
filter [x -> x != 0] take 3 ...

sample run:
observer> show filter [x -> x != 0] take 3 [1 0 3 4 5]
observer: [1 3]

(That's NetLogo 6 syntax. In NetLogo 5, write [? != 0] instead of [x -> x != 0].)

A: i wrote code below to solve it:
let m 0
 foreach list2
  [
   if (m < 3)
    [
     if (item ? list2 != 0)
      [
       set candidatelist lput (item ? list3) candidatelist
        ]
     set m m + 1
       ]
     ]


text:
Q: Faraday not working on Rails I'm trying to use Faraday with Rails 4 for Google API Oauth in below code:
class GoogleApisController < ApplicationController

    def oauth2callback
        require 'faraday'
        render layout: false

        conn = Faraday.new(:url => 'https://accounts.google.com',:ssl => {:verify => false}) do |faraday|
            faraday.request  :url_encoded
            faraday.response :logger
            faraday.adapter  Faraday.default_adapter
        end

        @result = conn.post '/o/oauth2/token', {'code' => params[:code],
            'client_id' => "some_id",
            'client_secret' => "some_secret",
            'redirect_uri' => "some_redirect_uri",
            'grant_type' => 'authorization_code'}

    end
end

But when I do @result.body.inspect it doesn't return anything.
So @result return nil and doesn't seem to process at all.
However when I try the above codes in liveshell it seems to work.
Is there a reason why this is happening?

A: If you try to render before you instantiate the object you are trying to render, the template won't actually have anything in it.  Moving the render statement to the bottom of the method will take care of the issue.


text:
Q: Prolog - Find the depth of an element in a binary tree I would like to know how I can find the depth of a given element E in a binary tree.
For simplicity, the tree has no repeated elements.
I tried:
ElemDepth(E,t(E,T1,T2), D).
ElemDepth(E,t(M,T1,T2), D):- D1 is D+1, ElemDepth(E,T1, D1).
ElemDepth(E,t(M,T1,T2), D):- D1 is D+1, ElemDepth(E,T2, D1).

but it does not seem to work.

A: Given a binary tree where

*

*The empty tree is denoted by the atom nil, and

*A non-empty tree is represented as a t/3 structure:
t( Data, Left_Subtree, Right_Subtree)

We can walk it easily:
visit( t(_,L,_) , P ) :- visit(L,P). % visit the left subtree, then
visit( t(P,_,_) , P ) .              % visit the current tree node, then
visit( t(_,_,R) , P ) :- visit(R,P). % visit the right subtree

And visiting each node whilst computing the depth of the nodes is similarly easy. We just move the actual traversal logic into a helper predicate that carries with it the extra bit of state to count depth as it goes.
visit(T,P,D) :- visit(T,0,P,D) .

visit( t(_,L,_) , N, P, D ) :- N1 is N+1, visit(L,N1,P,D) .
visit( t(P,_,_) , D, P, D ) .
visit( t(_,_,R) , N, P, D ) :- N1 is N+1, visit(R,N1,P,D) .


text:
Q: Copy files which do not exist in log file to folder Essentially I need to be able to copy new files from the source folder which were not present the last time the script ran to a destination folder.
Here is what I am thinking:
-Script to run every 1 min
-Source Folder
-Destination Folder
-Log file records file which was copied
Process:
-Run through directory file by file and check against log file to determine if file needs to be copied.
-If file exists in log file DO NOT COPY
-If file DOES NOT EXIST in log file, Copy to Destination Folder, Write filepath/filename to logfile
-Continue to next file in directory
This is what I have but am experiencing issues with findstr and not entirely sure this is the best way to go about it.
@echo off
:start

for /r "C:\Source" %%i in (*) do (

    echo --------------------------------------
    echo Searching for: %%i
    type log.txt | findstr /L "%%i"

    if %ERRORLEVEL% EQU 1 (
    echo NOT FOUND
    goto copyfile
    )
    if %ERRORLEVEL% EQU 0 (
        echo FOUND
    )
echo ------------------------------------------

:copyfile
echo ------------------------------------------------------------------
echo Copy %%i
copy "%%i" C:\Destination
echo Writing to log file: %%i
echo -------------------------------------------------------------------
echo %%i >> log.txt

)

I would greatly appreciate the insight. Thank you all for your time.

A: As MC ND pointed out RoboCopy is the answer and certainly worked for me.
robocopy source-path destination-path /r:30 /w:20 /mon:1 /mot:1 /log+: path-to-log

/r:30 - Retries to copy 30 times if copy error occurs
/w:20 - Waits 20 seconds before retrying copy
/mon:1 - Monitors source directory for a change of 1 file
/mot:1 - Waits 1 minute before checking for changes
/log+: - Appends to log file
To see more info on Robocopy in cmd type robocopy /?


text:
Q: Can't access files on network drive using FS npm module nodejs I have a network drive mapped to X:\ and for some reason I cannot access the files in it using the FS module. I tried using fs.existsSync(file) and it returns that no files can be found but when I type out the path fs.existsSync('X:\path\to\file') it works fine. Both file and the string I hardcoded are exactly the same, so why is fs returning different results for both? I have to use the "file" variable because I am looping through an array of file paths to create them in my network drive if they do not exist. I have also accounted for the backslashes, and replaced them all with double backslashes so the string is not being escaped.
    //This does not work
    let modifiedfilePathToSiger = path.join('X:\\', filePathToSiger.slice(17));
    let mps = JSON.stringify(modifiedfilePathToSiger)
    //Remove double quotes from mps
    let file = mps.replace(/['"]+/g, '')   //Ex: file here = X:\\Data\\Aerial Photo.docx

    let found = fs.existsSync(file);
    console.log(found) //Returns false

    //This does work
    let found = fs.existsSync('X:\\Data\\Aerial Photo.docx');
    console.log(found) //Returns true

One other thing to note, if I type out the whole hardcoded path into fs.existsSync() it works fine and returns true, but if I copy and paste the path that is logged from the console, it returns false, albeit the exact same path... not 1 character is different.

A:
Looks like when I log file variable it returns X:\Data\Aerial Photo.docx but when I log the hardcoded string X:\Data\Aerial Photo.docx it returns X:\Data\Aerial Photo.docx

Make use of .split and path.win32 then path.join
From Node REPL
> path = require('path').win32
<ref *1> {
  resolve: [Function: resolve],
  normalize: [Function: normalize],
  isAbsolute: [Function: isAbsolute],
  join: [Function: join],
  relative: [Function: relative],
  toNamespacedPath: [Function: toNamespacedPath],
  dirname: [Function: dirname],
  basename: [Function: basename],
  extname: [Function: extname],
  format: [Function: bound _format],
  parse: [Function: parse],
  sep: '\\',
  delimiter: ';',
  win32: [Circular *1],
  posix: <ref *2> {
    resolve: [Function: resolve],
    normalize: [Function: normalize],
    isAbsolute: [Function: isAbsolute],
    join: [Function: join],
    relative: [Function: relative],
    toNamespacedPath: [Function: toNamespacedPath],
    dirname: [Function: dirname],
    basename: [Function: basename],
    extname: [Function: extname],
    format: [Function: bound _format],
    parse: [Function: parse],
    sep: '/',
    delimiter: ':',
    win32: [Circular *1],
    posix: [Circular *2],
    _makeLong: [Function: toNamespacedPath]
  },
  _makeLong: [Function: toNamespacedPath]
}
> strArr = file.split('\\')
[ 'X:', 'Data', 'Aerial Photo.docx' ]
> path.join(strArr[0],strArr[1],strArr[2])
'X:\\Data\\Aerial Photo.docx'
>

it will take care of the slashes respective to environment


text:
Q: The indefinite integral of an $L^1$ function has a convergent series of Fourier coefficients Let $f\in L^1([0,2\pi])$ be a $2\pi$-periodic function with $\hat f(0)=0$ and $\hat f(\vert n\vert)=-\hat f(-\vert n\vert)\geq 0$. Define $F(t)=\int_0^t f(x)dx$. I know that F iscontinuous, $2\pi$-periodic function and $\hat F(n)=\frac{\hat f(n)}{in}$ if $n\neq 0$.
I want to prove that $\sum_{n\geq 1} \frac{\hat f(n)}{n}<\infty$.
How to prove that?

A: The function $F$ is continuous and of bounded variation because
$$
                       V_{a}^{b}(F) = \int_{a}^{b}|f(t)|dt.
$$
Therefore the Fourier series for $F$ converges pointwise everywhere to $F$ (in fact it must converge uniformly.) In particular,
$$
              F(0) = \lim_N\sum_{n=-N}^{N}\hat{F}(n)=2\lim_N\sum_{n=1}^{N}\frac{\hat{f}(n)}{in}.
$$


text:
Q: Hdiutil files case sensitivity changing in ISO Running this command to create an iso on macOS:
hdiutil makehybrid -o ~/Desktop/test.iso ~/Documents/files/ -iso

When mounting the iso all files in the directory are in upper case.
How can I stop case-sensitivity from changing with this command?

A: As suggested by Mark Setchell: the addition of -joliet:
hdiutil makehybrid -o ~/Desktop/test.iso ~/Documents/files/ -joliet -iso

Maintains case sensitivity when creating the iso.


text:
Q: How to boot FreeBSD from GNU GRUB 2 bootloader command mode I've been following an installation guide for FreeBSD and this part seems to be skipped. When I reboot my system after the initial installation it loads to grub boot loader, but in command mode as no options have been setup yet. I have windows10 installed on another drive.
How do I load FreeBSD from this command mode?

A: Run ls to list the partitions and replace hd0,X with your root partition:
set root=(hd0,X)
kfreebsd /boot/kernel/kernel
boot

A: I'd suggest to install GRUB2WIN.
I have a similar setup; FreeBSD multi-booted with GNU/Linux.
For EFI hardware:
set root=(hdX,Y)
chainloader /boot/loader.efi
boot

For non-EFI hardware:
set root=(hdX,Y)
kfreebsd /boot/loader
boot

For EFI hardware + ZFS:
set root=(hdX,Y)
chainloader /@/boot/loader.efi
boot

For non-EFI hardware + ZFS:
set root=(hdX,Y)
kfreebsd /@/boot/loader
boot

All of these methods work for me, and I hope they do for you, too.


text:
Q: Hertz used in AVR I'm very new to AVR and got confused about a question from one of our tutorials. It says:
"To toggle an output compare pin 8 times per second (4Hz period), what clock prescale and output output compare values do we need?"
My confusion is:
why it says "4Hz period"? isn't Hertz a measurement for frequency? why is it describing time period?

A: You are correct Hz is the unit for frequency. Frequency is changes per second so if you toggle a pin 4 times per second its frequency is 4Hz. The author was problably lazy and did not want to calculate the period time to 1/4 s

A: Hertz represents >> cycles per seconds in Metrical System SI system.
As mentioned above it tells you how many times a process, event anything else takes place. Mostly everything is measured in Hz because its convenient and has direct relation to time. So one can easily jump back and forth in units.
For the AVR has a system clock which is then prescaled to lower rates for use in different system peripherals. The event loop speed is also measured in Hertz. Currently on mine the loop execution time is 2.7 MHz so very fast loop.


text:
Q: File permissions for mounted volumes in docker Currently using WSL2 ubuntu with docker-desktop for windows with WSL integration.
docker-compose.yml file
version: '3.9'
services:

  wordpress:
    # default port 9000 (FastCGI)
    image: wordpress:6.1.1-fpm
    container_name: wp-wordpress
    env_file:
      - .env
    restart: unless-stopped
    networks:
      - wordpress
    depends_on:
      - database
    volumes:
      - ${WORDPRESS_LOCAL_HOME}:/var/www/html
      - ${WORDPRESS_UPLOADS_CONFIG}:/usr/local/etc/php/conf.d/uploads.ini
      # - /path/to/repo/myTheme/:/var/www/html/wp-content/themes/myTheme
    environment:
      - WORDPRESS_DB_HOST=${WORDPRESS_DB_HOST}
      - WORDPRESS_DB_NAME=${WORDPRESS_DB_NAME}
      - WORDPRESS_DB_USER=${WORDPRESS_DB_USER}
      - WORDPRESS_DB_PASSWORD=${WORDPRESS_DB_PASSWORD}

  database:
    # default port 3306
    image: mysql:latest
    container_name: wp-database
    env_file:
      - .env
    restart: unless-stopped
    networks:
      - wordpress
    environment:
      - MYSQL_DATABASE=${MYSQL_DATABASE}
      - MYSQL_USER=${MYSQL_USER}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
    volumes:
      - ${MYSQL_LOCAL_HOME}:/var/lib/mysql
    command:
      - '--default-authentication-plugin=mysql_native_password'

  nginx:
    # default ports 80, 443 - expose mapping as needed to host
    image: nginx:latest
    container_name: wp-nginx
    env_file:
      - .env
    restart: unless-stopped
    networks:
      - wordpress
    depends_on:
      - wordpress
    ports:
      - 8080:80    # http
      - 8443:443   # https
    volumes:
      - ${WORDPRESS_LOCAL_HOME}:/var/www/html
      - ${NGINX_CONF}:/etc/nginx/conf.d/default.conf
      - ${NGINX_SSL_CERTS}:/etc/nginx/certs
      - ${NGINX_LOGS}:/var/log/nginx

  adminer:
    # default port 8080
    image: adminer:latest
    container_name: wp-adminer
    restart: unless-stopped
    networks:
      - wordpress
    depends_on:
      - database
    ports:
      - "9000:8080"
networks:
  wordpress:
    name: wp-wordpress
    driver: bridge

I'm just starting out with development using docker. The file on the local storage(in the Linux file system) was initially owned by www-data so I changed it to my linux username using sudo chown -R username:username wordpress/ because it wasn't writeable. But doing this doesn't allow me to upload files(from wordpress interface) or write to files inside the nginx container unless the ownership is changed back to www-data:www-data.
Things I've tried:

*

*Starting a bash session inside the nginx container with docker exec -it <cname> bash and changing the ownership of the uploads directory and writing files to my username.(after adding user with adduser username)

*Changing the nginx user within the bash session to my username using user username username
I don't know what else to try except sudo chmod -R a+rwx in the main directory.
default.conf:
# default.conf
# redirect to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name wordpress-docker.test;
    location / {
        # update port as needed for host mapped https
        rewrite ^ https://wordpress-docker.test:8443$request_uri? permanent;
    }
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name wordpress-docker.test;
    index index.php index.html index.htm;
    root /var/www/html;
    server_tokens off;
    client_max_body_size 75M;

    # update ssl files as required by your deployment
    ssl_certificate     /etc/nginx/certs/localhost+2.pem;
    ssl_certificate_key /etc/nginx/certs/localhost+2-key.pem;

    # logging
    access_log /var/log/nginx/wordpress.access.log;
    error_log  /var/log/nginx/wordpress.error.log;

    # some security headers ( optional )
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        try_files $uri = 404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass wordpress:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }

    location ~ /\.ht {
        deny all;
    }

    location = /favicon.ico {
        log_not_found off; access_log off;
    }

    location = /favicon.svg {
        log_not_found off; access_log off;
    }

    location = /robots.txt {
        log_not_found off; access_log off; allow all;
    }

    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
        expires max;
        log_not_found off;
    }
}

Folder struct:
    |-config
    |--uploads.ini
    |-dbdata
    |-logs
    |-nginx
    |--certs
    |--default.conf
    |-wordpress
    |-.env
    |-docker-compose.yml

A: Refering to this answer, this is how I resolved my issue:

*

*Add your user to the www-data group
sudo usermod -a -G www-data username

*Give rw permissions to the www-data group(f flag applies the permissions only to files and leaves the directories)
sudo find wordpress -type f -exec chmod g+rw {} +


text:
Q: rails: how would you convert a multi-line output into html? suppose in your controller, you had something like this:
@out = `git log --name-status -n1 ${@hash}`

(which returns a multi-line output to the terminal)
And you wanted to show it in a view like so:
<%= content_tag(:div, @out.html_safe, class: "well") %>

How do you get that output with preserved whitespace?

A: Either use the good old <pre> tag or, in your CSS, apply white-space: pre; or white-space: pre-wrap; to the surrounding element. Personally I think <pre> is preferable, since it's semantic.
P.S. I would avoid using html_safe in this instance, as the unescaped output from your shell command could easily break your markup.

A: Typically a <pre> tag is used to markup pre-formatted text:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre


text:
Q: Extract years from string in Excel I have a list of coverage dates without a recurring pattern. For example, I have the following strings:
Available from 1951 until 1984;

Available from 1964 volume: 2 issue: 1 until 2002 volume: 20 issue: 4;

Available from 1958 volume: 1 issue: 1;

Available from 1970 issue: 24 until 1989 issue: 110;  Available from 1990 volume: 1 issue: 1 until 2001 volume: 12 issue: 4;

I am trying to extract only the years value into a different columns in Excel, for example:
Available from 1951 until 1984; -> 1951 | 1984
Available from 1964 volume: 2 issue: 1 until 2002 volume: 20 issue: 4; -> 1964 | 2002
Available from 1970 issue: 24 until 1989 issue: 110;  Available from 1990 volume: 1 issue: 1 until 2001 volume: 12 issue: 4; -> 1970 | 1989 | 1990 | 2001

(if possible, each year should appear in a different column)
Is there a way for me to extract the years? I thought of writing a VB code but I am honestly not fluent in VB.
Thank you.

A: Use this array formula:
=IFERROR(INDEX(MODE.MULT(IF((TRIM(MID(SUBSTITUTE($A1," ",REPT(" ",999)),(ROW($1:$50)-1)*999+1,999))="from")+(TRIM(MID(SUBSTITUTE($A1," ",REPT(" ",999)),(ROW($1:$50)-1)*999+1,999))="until"),SUBSTITUTE(TRIM(MID(SUBSTITUTE($A1," ",REPT(" ",999)),(ROW($1:$50))*999+1,999)),";","")*{1,1})),COLUMN(A:A)),"")

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.
Put in B1, Hit Ctrl-Shift-Enter.  Then copy/drag over and down.
This formula looks for from and until and pulls the next "word" as the return.  If that rule is not consistent then this will not work.


text:
Q: Switching between Fragment classes in Kotlin I have a Navigation drawer and have a problem in switching between fragments in android with kotlin. No error messages appear, but I guess the problem in this peace of code:
private fun selectItemDrawer(menuItem: MenuItem){
    var fragment:Fragment? = null
    var fragmentClass:Class<*> = when(menuItem.itemId)
    {
        R.id.first-> FirstFragment::class.java
        R.id.second-> SecondFragment::class.java
        R.id.third-> ThirdFragment::class.java
        R.id.fourth-> FourthFragment::class.java
        else -> FirstFragment::class.java
    }
    try {
       fragment = fragmentClass.newInstance() as Fragment
    }catch (e:Exception){
        e.printStackTrace()
    }

    var fragmentManager = supportFragmentManager
    fragmentManager.beginTransaction()
            .replace(R.id.frame,fragment)
            .commit()
    menuItem.isChecked = true
    menuItem.title
    drawer_layout.closeDrawers()
}

Could anyone help in this please!

A: You have never modified var fragment value after declaration, so, when you try a fragment transaction, fragment variable value is still null and it will not work.
In your code example, you should do something like below:
try {
    fragment = fragmentClass.newInstance() as Fragment //set fragment var with selected case
}catch (e:Exception){
    e.printStackTrace()
}

Edit: Because question code update.
Just set your fragment value directly from your switch statement:
private fun selectItemDrawer(menuItem: MenuItem) {
    var fragment: Fragment = when (menuItem.itemId) {
        R.id.first -> FirstFragment()
        R.id.second -> SecondFragment()
        R.id.third -> ThirdFragment()
        R.id.fourth -> FourthFragment()
        else -> FirstFragment()
    }
    var fragmentManager = supportFragmentManager
    fragmentManager
            .beginTransaction()
            .replace(R.id.frame, fragment)
            .commit()
    menuItem.isChecked = true
    menuItem.title
    drawer_layout.closeDrawers()
}

A: You can download the full source code from here(Navigation Drawer In Android Kotlin)
    class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        init()
    }

    private fun init() {
        tv_home.setText("Home Tab")
        tv_title.setText("Home")
        ll_about.setOnClickListener(this)
        ll_home.setOnClickListener(this)
        ll_bookmark.setOnClickListener(this)
        ll_help.setOnClickListener(this)
        rl_menu.setOnClickListener(this)
        rl_header.setOnClickListener(this)

        tv_link.setLinkTextColor(Color.parseColor("#000000"));
        Linkify.addLinks(tv_link, Linkify.ALL)

    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {

            R.id.ll_home -> {
                drawer_layout.closeDrawer(GravityCompat.START)
                tv_home.setText("Home Tab")
                tv_title.setText("Home")

            }
            R.id.ll_about -> {

                val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://deepshikhapuri.blogspot.in/"))
                startActivity(browserIntent)

            }

            R.id.ll_help -> {
                drawer_layout.closeDrawer(GravityCompat.START)
                tv_home.setText("Help Tab")
                tv_title.setText("Help")

            }

            R.id.ll_bookmark -> {
                drawer_layout.closeDrawer(GravityCompat.START)
                tv_home.setText("Bookmark Tab")
                tv_title.setText("Bookmark")

            }

            R.id.rl_header -> {
            }

            R.id.rl_menu -> {
                if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
                    drawer_layout.closeDrawer(GravityCompat.START)
                } else {
                    drawer_layout.openDrawer(GravityCompat.START)
                }
            }

        }

    }

}

Thanks!