text:
Q: XSLT management - attaching metadata to a stylesheet for output and parameters I am using about a dozen XSLT files to provide a large number of output formats. At the moment the user has to know the extension of the file format being exported to e.g. RTF, HTML, TXT.
I would also like to use parameters to allow more options.  If I can embed the metadata in the XSL file itself then I can pick up the details by scanning through the files.
Here is what I am thinking about. In this example the program would have to parse the comments for the required information.
<?xml version="1.0" encoding="UTF-8"?>
<!-- Title: Export to Rich Text Format -->
<!-- Description: This Stylesheet converts to a Rich Text Format format which may be used in a word processor such as Word -->
<!-- FileFormat: RTF -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:param name="CompanyName"/> <!-- Format:String, Description: Company name to be inserted in the footer -->
<xsl:param name="DateDue"/> <!-- Format:Date-yyyy-mm-dd, Description: Date Due -->
<xsl:param name="IncludePicture">true</xsl:param><!-- Format:Boolean, Description: Do you want to include a graphical representation? -->
  <xsl:template match="/">
  <!-- Stuff -->
  </xsl:template>
</xsl:stylesheet>

Are there any standards out there? Do I need to butcher more than one (Dublin Core with a smattering of XML Schema)?
P.S. the project this is being applied to is Argumentative.

A:
Here is what I am thinking about. In
  this example the program would have to
  parse the comments for the required
  information.

You don't need to code the metadata within comments.
Metadata can be specified as part of the XSLT stylesheet using ordinary XML markup -- as rich in structure and meaning as we need.
Here is an example how to do that:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:meta="my:meta">
 <xsl:output method="text"/>

 <meta:metadata>
   <title>Title: Export to Rich Text Format </title>
   <description>
    This Stylesheet converts to a Rich Text
    Format format which may be used in a word processor
    such as Word
   </description>
   <fileFormat>RTF</fileFormat>
   <parameters>
     <parameter name="CompanyName" format="xs:string"
      Description="Company name to be inserted in the footer"/>

     <parameter name="DateDue" format="xs:date"
      Description="Date Due"/>

     <parameter name="IncludePicture" format="xs:boolean"
      Description="Do you want to include a graphical representation?"/>
   </parameters>
 </meta:metadata>

 <xsl:param name="CompanyName"/>
 <xsl:param name="DateDue"/>
 <xsl:param name="IncludePicture" select="true"/>

 <xsl:variable name="vMetadata" select=
      "document('')/*/meta:metadata"/>

 <xsl:template match="/">
  This is a demo how we can access and use the metadats.

  Metadata --> Description:

  "<xsl:copy-of select="$vMetadata/description"/>"
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the result is:
  This is a demo how we can access and use the metadats.

  Metadata --> Description:

  "
    This Stylesheet converts to a Rich Text
    Format format which may be used in a word processor
    such as Word
   "

Do note:

*

*Any element that is in a namespace (of course not the no-namespace and not the xsl namespace) can be specified at the global level of any xslt stylesheet.

*Such elements can be accessed using the xslt function document().


text:
Q: How would I implement a 1-bit slt operation in an ALU? (MIPS) This is a homework assignment, so I'm not looking for an answer, but guidance. The instructions say, "How would you implement a 1-bit slt operation in an ALU? Describe your solution using only AND, OR, and NOT. No need to diagram the logic gates, just clearly describe the process with all possible inputs, expected outputs, and the logical expression that represents SLT."
So far...
I'm thinking of having A and B as 32-bit inputs into the ALU. I was also thinking of taking the two's complement of B. Then, I would add A and B together. If the output is anything other than a negative, return 0. In my thinking, that sounds like I have implemented a 1-bit slt operation. But, how do I show "if result is negative return 1" using only AND, OR, and NOT?

A: In your case assume the high bit is the sign bit. Mask the result by AND'ing with 1 << 31 to check sign bit. If you want to return either 1 or 0 then you can use another NOT operation on the result of masking and then AND with 1 and return that.
Example:
If the result is negative you get (in bits) 1....... then NOT of this will give you 0111111..... and finally the last AND will give you 000....1 which is the result you want.

A: Guidance: Draw a truth table for slt instruction.

Answer:
Truth table for 1 bit slt ALU instruction.
A  B  Q
0  0  0  //A=B no!
0  1  1  //A<B yes!
1  0  0  //A>B no!
1  1  0  //A=B no!

Q(output) is set high only if A< B.
Therefore, Q=A'B. (or Q=~A&B in verilog)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Writing to xlsm is not working in c# I was trying to write some data's to a macro enabled excel which is create with Microsoft Excel 2010.
The problem is my code is not writing any datas, also there is no error. can anyone  tell me what's wrong with my code?
 private void button2_Click_1(object sender, EventArgs e)
        {
            string excelFilename;
            excelFilename = "D:\\TestPivot1.xlsm";
            Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
            Workbook ObjWorkBook;
            Worksheet ObjWorkSheet;

            ObjWorkBook = ObjExcel.Workbooks.Open(excelFilename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[2];
            int i;
            for(i=1;i<10;i++){
                ObjWorkSheet.Cells[i, 1] = "ID";
                ObjWorkSheet.Cells[i, 2] = "NAME";
                ObjWorkSheet.Cells[i, 3] = "GENDER";
                ObjWorkSheet.Cells[i, 4] = "DEPT";
                ObjWorkSheet.Cells[i, 5] = "SALARY";
                ObjWorkSheet.Cells[i, 6] = "DOH";
                ObjWorkSheet.Cells[i, 7] = "LOCATION";
            }
            ObjWorkBook.SaveAs("D:\\TestPivot2.xlsm", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
       Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
       Missing.Value, Missing.Value, Missing.Value,
       Missing.Value, Missing.Value);
        }

A: You are passing whole .xlsm file to the interop object, first crate Filestream object then use that object to open excel and then create workbook object with exactly the same name on that you want to modify.
errors: 1) No fileStream object to open .xlsm file
        2) You are passing filepath where you should pass FileStream
        3) when you are done with your required operation then ObjWorkBook.Write(fs); and then close all the objects


text:
Q: Does github contribution graph remove the contributions specifically made to that organization when I leave the organization? I got hired by a company and I was told to use my personal account for Github and I was wondering if the contribution graph will get reset as if I never joined the company once I leave the company, because I only wanted my personal account contain green blobs for my personal projects and not my work in a private organization. Is there a way to remove the contributions.
Also, will people who will join the company in the future see that I contributed to the projects in the company and see a link to my Github account?

A: By default, GitHub contribution graphs contain contributions from all commits made with your email address that end up in the default branch of a public repo.  You can also choose to enable or disable the ability to show contributions from a private repo; if you do, then users will see that your contributions were in a private repo, but not which one.
If you use a corporate email address for your work contributions, then when you leave the company, you can remove the email address, and the contributions will no longer be associated with your account.  They will still be listed with your name and the Gravatar associated with your email address, but not related to your account.


text:
Q: The distance covered when 22 MeV gamma rays travel through air Both alpha and beta radiations can only travel short distances through air as they're not as penetrating as gamma radiations. How long gamma radiations with 22 MeV energy can travel in air? Is it meters, kilometers, miles, etc.
Is there a difference between a lower energy gamma ray (for example a 2 MeV gamma ray) and a higher energy gamma ray (22 MeV gamma ray) when it comes to the maximum distance covered in air?

A: In a beam of 22 MeV gamma rays passing through dry air at sea level, half will be absorbed in about 350 meters.  Photons at lower energies are absorbed in a shorter distance (for 2 MeV, it's about 130 meters).

Calculation details: NIST gives the mass attenuation coefficient $\mu/\rho$ for 20 MeV photons as $1.705 \times 10^{-2} \mathrm{\ {cm}^2/g}$ (it's a little bit lower at higher energies).  The density of air at sea level, $\rho$, is about 1.225 kg/m$^3$.  Therefore, for 20 MeV photons, half will be absorbed in a distance
$$\frac{\ln 2}{(1.705 \mathrm{\ {cm}^2/g})(1.225 \mathrm{\ {kg}/m^3})} \approx 330 \mathrm{\ m}$$
and the distance is a little higher at 22 MeV.


text:
Q: Adding buttons to static table view/calling methods from tableview cells Quite simply, I'm trying to add multiple buttons to the bottom of the static table view, much like in the address book app (below the contact's details for Send Message, Share Contact and Add to Favourites). However it just simply won't let me add three button in Storyboards unless I use a subview but then I can't quite get the colour to be the same as that of the iOS 6 background (and I've used the colour picker). What happens is that it'll simply add the button below the table view section and it takes up the entire width of the iPad's screen.
My other (and original) thought was to use the static table view cells to simply call methods. What I want to do here is add the building's details (like address, name etc) to the user's contacts app when they press the tableview/button - but I can't link it to any IBActions.
Using a button would be no problem, so if the first issue could be solved that'd be excellent.

A: If you use the solution with the subview, you can set the views backgroundcolor to [UIColor clearColor]


text:
Q: Where are the apps..really? I'm a brand new user of Linux/Ubuntu (14.04)
I am looking for BASH.
I clicked the UbuntuSoftwareCenter at the left and then the "All Software" icon at the top.  I enter "Bash" into the search field at the top right, and at the top of the results is "GNU Bourne Again SHell" and it's flagged as "Installed" (green check, etc.) But I cannot "do" anything with it from there - I cannot open the program, drag it to the left menu bar, etc. Nothing.
So, still in Ubuntu Software Center, I instead click "Installed" at the top , but now the program "GNU Bourne Again SHell" is nowhere to be found.
So, I closed the window then clicked "Dash" and entered "BASH" or "Bourne" or "SHell" (in varying capitalizations), and I also opened up the "Applications" section to show all... there's no "BASH"
Can anyone explain what I was seeing and where I can find the supposedly installed BASH, and pin it to the left menu?

A: Many programs in Ubuntu need something or the other to run in. Graphical programs like the file manager (typically Nautilus) or the browser (Firefox, or Google Chrome, for example) need an instance of the X Window System (typically provided by X.Org's X server) to run.
Correspondingly, command-line programs like Bash, apt-get, lynx, etc., to be run interactively, need a terminal emulator to run. By default, Ubuntu has GNOME Terminal, XTerm and the TTYs (managed by getty, accessible by pressing CtrlAltF1-F6 - back to GUI by CtrlAltF7) via which you can interact with command line programs.
To run a command-line program, then, you need to run a terminal emulator (for example, GNOME Terminal) first.
The terminal emulator programs typically run bash by default (since that is the default login shell for users in Ubuntu). Therefore, to run bash, usually all you need to do is run Terminal.
Without a terminal to run in, when you started Bash or Dash, they probably quit immediately. Nothing to see here, folks.
See:

*

*What is the difference between Terminal, Console, Shell, and Command Line?

*What is the exact difference between a 'terminal', a 'shell', a 'tty' and a 'console'?

*What is the best way to learn how to use Ubuntu with terminal?

Making a launcher icon for a command line program is a different issue. For that, see How can I edit/create new launcher items in Unity by hand?, and use Terminal=true instead of Terminal=false.

A: bash is a shell; basically a program that reads commands and executes them. It is one of the interfaces between the kernel and the user.
I do not know what do you call "apps", but if I understand correctly, bash is under the level of what you call "an app". But it's a fundamental part of the system...
Have a good read here: http://www.tutorialspoint.com/unix/unix-getting-started.htm --- the diagram below is a graphic example of a Unix system architecture from that site (it's a link, not a copy...)

You can run bash in a terminal, in a virtual console, in a background program. Your system is probably running several instance of bash right now.
As far as any Unix system is designed, the graphical interface and the graphical applications are just another kind of application programs --- this is one of the reason that Ubuntu (and all other Unixes) can use several different graphic interfaces.

A: The terminal is NOT BASH. Make sure you remember that :)
Bash is a shell - "a program that reads commands and executes them. It is one of the interfaces between the kernel and the user." Credit - rmano


text:
Q: android the bottom of the scrollview disappear I am making an android app with scrollview and inside the scrollview there is a relativelayout and both of them have a background and it works fine but when I try to make space between the scrollview and the relativelayout by using marginTop and Bottom, the bottom of the scrollview disappear.
<?xml version="1.0" encoding="utf-8"?>

 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="400dp"
    android:layout_height="fill_parent"
    android:background="@drawable/bg"

    >

 <RelativeLayout
        android:layout_width="330dp"
        android:layout_height="730dp"
        android:layout_marginLeft="26dp"
        android:layout_marginRight="26dp"
        android:layout_marginTop="26dp"
        android:layout_marginBottom="26dp"
        android:background="@drawable/bg2"

        >

<Button
    android:id="@+id/button1"
    android:layout_width="100dp"
    android:layout_height="30dp" />

<Button
    android:id="@+id/button2"
    android:layout_width="100dp"
    android:layout_height="30dp" />

<Button
    android:id="@+id/button3"
    android:layout_width="100dp"
    android:layout_height="30dp" />

  </RelativeLayout>

   </ScrollView>

when I run the app I want this:

but I am getting this, I cant view the bottom:

A: Use this in your Scroll View:
android:fillViewport="true"

and in RelativeLayout:
android:adjustViewBounds="true"

A: Please add this line into your <ScrollView></ScrollView> Tag in view's XML File.
android:padding="15dp"

It will solve your problem.

A:  <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#15375e"

    >

 <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="30dp"
        android:background="#000000"

        >

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_margin="10dp"
    android:text="1" />

<Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_below="@+id/button1"
    android:layout_height="40dp"
    android:layout_margin="10dp"
    android:text="2" />

<Button
    android:id="@+id/button3"
    android:layout_width="match_parent"
    android:layout_below="@+id/button2"
    android:layout_height="40dp"
    android:layout_margin="10dp"
    android:text="3"/>

<Button
    android:id="@+id/button4"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_margin="10dp"
    android:layout_below="@+id/button3"
    android:text="4" />

<Button
    android:id="@+id/button5"
    android:layout_width="match_parent"
    android:layout_below="@+id/button4"
    android:layout_height="40dp"
    android:layout_margin="10dp"
    android:text="5" />

<Button
    android:id="@+id/button6"
    android:layout_width="match_parent"
    android:layout_below="@+id/button5"
    android:layout_height="40dp"
    android:layout_margin="10dp"
    android:text="6"/>

  </RelativeLayout>

   </ScrollView>

If you use this above code, you will get output like . Hope this helps you.

A: I've just stumbled upon this issue and found a solution.
It seems that if you set the bottom margin for the layout inside the scrollview it doesn't behave as expected. As a solution, you can set the padding for that element instead of the margin. If you want a background that takes the whole screen you can set that on the scrollview itself.
Example:
<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:orientation="vertical">

            <!--Your elements go here-->

    </LinearLayout>

</ScrollView>

Hope this helps someone!


text:
Q: Report Generation in Git Can anyone tell me, is there any option for generating report in git, Like unmerged branches in a repository, fetching branch name that's created during particular time period.
If there is any separate tools for git report generation, kindly refer it.

A: This http://gitstats.sourceforge.net/ looks very interesting. Might help you.

A: A report about what has changed on the various branches, which branches were merged, which were not, etc. probably depends too much on your actual workflow.
Junio C Hamano, the Git maintainer, uses such scripts to automatize the generation of its "what's cooking" emails.   These scripts are on the todo branch of the git repository, but I don't know if their use is documented somewhere...


text:
Q: wait_for() multiple user discord.py I need my bot to wait for multiple user inputs. for example
if I called a command ('!invite @user1 @user2 @user3') in discord server!
It should wait until all the mentioned user says "@mentionme accept"
Now the problem is, I Can Do it for one mention ('!invite @user1') but I can't do for multiple users.
here is my code:
@client.command()
async def invite(ctx,*,message):
    mentioned_users = [member for member in message.mentions]#get all mentioned users
    def check(message: discord.Message):
        return message.channel == ctx.channel and message.author.id in mentioned_users and message.content == f"{ctx.author.mention} accept"
    msg = await client.wait_for('message', check=check,timeout=40.0)#wait_for
    await ctx.channel.send(f'{member.mention} accepted the invitation!')

It works for only one mention! Is there anyother ways to use the wait_for function for multiple users?

A: You can make a list with all the mentions and remove from it
@bot.command()
async def invite(ctx, *mentions: discord.Member):
    await ctx.send('Waiting for everyone to accept the invitation...')
    # Converting the tuple to list so we can remove from it
    mentions = list(mentions)
    def check(message):
        if message.channel == ctx.channel and message.author in mentions and message.content.lower() == f'{ctx.author.mention} accept':
            # Removing the member from the mentions list
            mentions.remove(message.author)
            # If the length of the mentions list is 0 means that everyone accepted the invite
            if len(mentions) == 0:
                return True
        return False

    await bot.wait_for('message', check=check)
    await ctx.send('Everyone accepted the invitation!')


text:
Q: Create sorted array from unsorted ArrayList I have an ArrayList filled with objects of the class result, each result has an attribute named value. I now want to create an Array which is filled with references to the same memory location as in the ArrayList but now in order where to object with the highest value is in the first location, the second highest in the second location and so forth.
I have searched here but haven't found any other post like it.

A: There are multiple ways to solve it using Gauava or lambda expressions.
Hope this implementation solve your problem.
package com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestDemo {

 public static void main(String[] args) {

  List < HockeyPlayer > players = new ArrayList < HockeyPlayer > ();
  HockeyPlayer obj1 = new HockeyPlayer();
  obj1.goalsScored = 22;
  players.add(obj1);
  HockeyPlayer obj2 = new HockeyPlayer();
  obj2.goalsScored = 11;
  players.add(obj2);
  HockeyPlayer obj3 = new HockeyPlayer();
  obj3.goalsScored = 111;
  players.add(obj3);
  HockeyPlayer obj4 = new HockeyPlayer();
  obj4.goalsScored = 3;
  players.add(obj4);

  Collections.sort(players, new Comparator < HockeyPlayer > () {
   @Override public int compare(HockeyPlayer player1, HockeyPlayer player2) {
    return player1.goalsScored - player2.goalsScored;
   }

  });

  for (int i = 0; i < players.size(); i++) {
   System.out.println(players.get(i).goalsScored);
  }

  HockeyPlayer array[] = new HockeyPlayer[players.size()];

  players.toArray(array); // contains reference

  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i].goalsScored);
  }

 }

}

class HockeyPlayer {
 public int goalsScored;

}


text:
Q: How is that possible that simple arithmetic mean works well even for strongly skewed distribution? I was taught, that the arithmetic mean is sensitive to outliers and skewness. This was natural to me - the observations lying far from the "central point" of the distribution "pull" the measure towards them. Then I was advised to use the arithmetic mean only for symmetric distributions, ideally normal, but symmetry was found as "good enough". When it came to asymmetric distributions, left or right, I was told to use the median. In case of log-normal distributed data, which - as I was told - have multiplicative nature (whatever it means), I was advised to use the geometric mean, as better measure of the central tendency. But then I was told, that the arithmetic means is "valid for any distribution", as it is the BLUE (best linear unbiased) estimator of the population expected value (still - the arithmetic mean).
Now I'm lost. If the arithmetic mean is so good measure even for so strongly skewed distributions as the log-normal, then why telling about "robust measures", like geometric mean, winsorized mean, trimmed mean, mid-mean? According to what I was told, only the arithmetic mean is the BEST estimator. Moreover, the geometric mean is not an estimator of the population expected value, so why even bother with? Is this because the expected value, the first raw moment, not always is the best measure characterizing the central tendency? And that is because, even if the arithmetic mean is best estimator, we instead propose the geometric mean as the best measure of the central tendency instead (not expectance) instead?
In other words: is it that however every distribution (for which the first raw moment is deifned) has the expected value, which is the arithmetic mean, but the expected value is "useful" only for the normal (or symmetric) distribution, and for any other skewed ones we may prefer different measure of central tendency instead of the expectance (which plays important role in theoretical considerations anyway)?

A: Whether the arithmetic mean is a good measure for a strongly skewed distribution depends on what you are using it for -- what does "good" mean?
One variable that is usually very right skew is income and, usually, you see median income rather than mean income. But why?
Because, usually, when we look at some measure of central tendency, we are looking for something like a "typical" value. So if we wanted to compare incomes in different countries, it would be natural to compare medians (or maybe other quantiles) rather than arithmetic means, because it is closer to what we are interested in. On the other hand, if we were interested in the total capital available in different countries, the arithmetic mean would be better.
Sometimes, though, the arithmetic mean makes very little sense. If we are trying to average numbers on different scales then the arithmetic mean is still BLUE, but it's a BLUE of a number that isn't useful. For instance, suppose you are averaging students' SAT scores (0 to 1600) and their high school grades (0 to 4). Then you won't want the arithmetic mean. Here you want the geometric mean.
Or, if you are averaging rates that have different denominators, the arithmetic mean will again be BLUE, but of a number that isn't useful.  For instance, if you make a trip of 300 km at 100 kph and return at 150 kph, then the arithmetic mean is 125 kph, but this is not very useful because you took 5 hours to go 600 km, which is 120 kph. Here you probably want the harmonic mean.
For more details on this, see my blog post the geometric and harmonic means.


text:
Q: Using variables in TSQL and keep formatting in SQL Server Management Studio I'm creating some views with a lot of references to tables in another database.
At some point the other database needs to change.
I want to make it easy for the next developer to change the scripts to use another database.
This obviously work like it should:
CREATE VIEW ViewName
AS
    SELECT *
    FROM AnotherDatabase.SchemaName.TableName;

But when I do:
DECLARE @DB CHAR(100)
SET @DB = 'AnotherDatabase'
GO

CREATE VIEW ViewName
AS
    SELECT *
    FROM @DB.SchemaName.TableName;

I get the error:

Msg 137, Level 15, State 2, Procedure ViewName, Line 3
  Must declare the scalar variable "@DB".

I could do something like:
DECLARE @SQL ...
SET @SQL = ' ... FROM ' + @DB + ' ... '
EXEC (@SQL)

But that goes against the purpose of making it easier for the next developer - because this dynamic SQL approach removed the formatting in SSMS.
So my question is: how do I make it easy for the next developer to maintain T-SQL code where he needs to swap out the database reference?
Notes:

*

*I'm using SQL Server 2008 R2

*The other database is on the same server.

A: Consider using SQLCMD variables.  This will allow you to specify the actual database name at deployment time.  SQL Server tools (SSMS, SQLCMD, SSDT) will replace the SQLCMD variable names with the assigned string values when the script is run.  SQLCMD mode can be turned on for the current query windows from the menu option Query-->SQLCMD mode option.
:SETVAR OtherDatabaseName "AnotherDatabaseName"

CREATE VIEW ViewName AS
SELECT *
  FROM $(OtherDatabaseName).SchemaName.TableName;
GO

This approach works best when SQL objects are kept under source control.

A: When you declare variables, they only live during the execution of the statement. You can not have a variable as part of your DDL. You could create a bunch of synonyms, but I consider that over doing it a bit.
The idea that your database names are going to change over time seems a bit out of the ordinary and conceivably one-time events. However, if you do still require to have the ability to quickly change over to point to a new database, you could consider creating a light utility directly in SQL to automatically generate the views to point to the new database.
An implementation may look something like this.
Assumptions

*

*Assuming we have the below databases.

*Assuming that you prefer to have the utility in SQL instead of building an application to manage it.

Code:
create database This;
create database That;
go

Configuration
Here I'm setting up some configuration tables. They will do two simple things:

*

*Allow you to indicate the target database name for a particular configuration.

*Allow you to define the DDL of the view. The idea is similar to Dan Guzman's idea, where the DDL is dynamically resolved using variables. However, this approach does not use the native SQLCMD mode and instead relies on dynamic SQL.

Here are the configuration tables.
use This;

create table dbo.SomeToolConfig (
    ConfigId int identity(1, 1) primary key clustered,
    TargetDatabaseName varchar(128) not null);

create table dbo.SomeToolConfigView (
    ConfigId int not null
        references SomeToolConfig(ConfigId),
    ViewName varchar(128) not null,
    Sql varchar(max) not null,
    unique(ConfigId, ViewName));

Setting the Configuration
Next you set the configuration. In this case I'm setting the TargetDatabaseName to be That. The SQL that is being inserted into SomeToolConfigView is the DDL for the view. I'm using two variables, one {{ViewName}} and {{TargetDatabaseName}}. These variables are replaced with the configuration values.
insert SomeToolConfig (TargetDatabaseName)
    values ('That');

insert SomeToolConfigView (ConfigId, ViewName, Sql)
    values
        (scope_identity(), 'dbo.my_objects', '
create view {{ViewName}}
as
    select *
    from {{TargetDatabaseName}}.sys.objects;'),
        (scope_identity(), 'dbo.my_columns', '
create view {{ViewName}}
as
    select *
    from {{TargetDatabaseName}}.sys.columns;');
go

The tool
The tool is a stored procedure that takes a configuration identifier. Then based on that identifier if drops and recreates the views in the configuration.
The signature for the stored procedure may look something like this:
exec SomeTool @ConfigId;

Sorry -- I left out the implementation, because I have to scoot, but figured I would respond sooner than later.
Hope this helps.


text:
Q: how to find the maximum occurence of a string in Oracle SQL developer i have 2 columns in a table. Data looks like this
Folio_no | Flag
1145       R

201        S

1145       FR

300        E

1145       R

201        E

201        S

Expected Output:

Folio_No | Flag

1145        R

201         S

300         E

The output should give the folio_no along with the flag which occured maximum number of times for that particular folio number.
i tried doing the below but it throws an error
select folio_no, max(count(flag)) from table group by folio_no;

A: We can use an aggregation:
WITH cte AS (
    SELECT Folio_No, Flag, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY Folio_No, Flag
),
cte2 AS (
    SELECT t.*, RANK() OVER (PARTITION BY Folio_No ORDER BY cnt DESC, Flag) rnk
    FROM cte t
)

SELECT Folio_No, Flag
FROM cte2
WHERE rnk = 1;

Note that I assume should two flags within a given folio number be tied for the max frequency, that you want to report the earlier flag.
Here is a working demo.

A: If you want the flag(s) that have the maximum occurrence for each folio then you can use:
SELECT Folio_No, Flag
FROM   (
  SELECT Folio_No,
         Flag,
         RANK() OVER (PARTITION BY Folio_No ORDER BY COUNT(*) DESC) AS rnk
  FROM   table_name
  GROUP BY Folio_No, Flag
)
WHERE  rnk = 1;

Which, for the sample data:
CREATE TABLE table_name (folio_no, flag) AS
  SELECT 1145, 'R'  FROM DUAL UNION ALL
  SELECT 201,  'S'  FROM DUAL UNION ALL
  SELECT 1145, 'FR' FROM DUAL UNION ALL
  SELECT 300,  'E'  FROM DUAL UNION ALL
  SELECT 1145, 'R'  FROM DUAL UNION ALL
  SELECT 201,  'E'  FROM DUAL UNION ALL
  SELECT 201,  'S'  FROM DUAL UNION ALL
  SELECT 201,  'S'  FROM DUAL UNION ALL
  SELECT   1,  'A'  FROM DUAL UNION ALL
  SELECT   1,  'A'  FROM DUAL UNION ALL
  SELECT   1,  'B'  FROM DUAL UNION ALL
  SELECT   1,  'B'  FROM DUAL UNION ALL
  SELECT   1,  'C'  FROM DUAL UNION ALL
  SELECT   1,  'D'  FROM DUAL;

Outputs:

FOLIO_NO
FLAG

1
A

1
B

201
S

300
E

1145
R

If you want only a single flag with the maximum occurrence for each folio, and if there are ties then the first folio alphabetically in each folio, then:
SELECT Folio_No, Flag
FROM   (
  SELECT Folio_No,
         Flag,
         ROW_NUMBER() OVER (PARTITION BY Folio_No ORDER BY COUNT(*) DESC, flag) AS rn
  FROM   table_name
  GROUP BY Folio_No, Flag
)
WHERE  rn = 1;

Which, for the sample data outputs:

FOLIO_NO
FLAG

1
A

201
S

300
E

1145
R

db<>fiddle here


text:
Q: Python - TypeError: __init__() takes exactly 2 arguments (3 given) but I gave 2 I'm new with Python so I tried some lines of code:
class loesung02(object):
    html = ""
    file1 = ""
    def __init__(self, html, file1):
        self.html = html
        self.file1 = file1
        print html + file1

i call it like that:
loesung02("aaaaaaaaaaaa", "bbbbbbbbbbb")

using the Python Shell
but I always get the ErrorMessage, so whats wrong?

A: What error message did you get? Your code run perfectly ok in my computer. I'm using python 2.7.1. Did you write that in a file and then run it or you write that in interpreter? If it is the latter, reinitialize or re-run your interpreter as there might be other variables that interfere with your code.


text:
Q: Datagridview Cell Length When I populate my Datagridview using the following code:
Private Sub FormatGridView()
    Dim ILNumColumn As New DataGridViewTextBoxColumn
    Dim ArtNumColumn As New DataGridViewTextBoxColumn
    Dim DescColumn As New DataGridViewTextBoxColumn

    'Header text
    ILNumColumn.HeaderText = "# IL"
    ArtNumColumn.HeaderText = "# Articles"
    DescColumn.HeaderText = "Description"

    'Wrap
    DescColumn.DefaultCellStyle.WrapMode = DataGridViewTriState.True

    'Widths
    ILNumColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
    ArtNumColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
    DescColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

    'Add columns
    dgvArticles.Columns.Add(ILNumColumn)
    dgvArticles.Columns.Add(ArtNumColumn)
    dgvArticles.Columns.Add(DescColumn)
End Sub

I want the ILNumColumn to accept no more than 3 numbers in its cell.
I have tried the following code:
ILNumColumn.MaxInputLength = 3

It doesn't work, I can still write "9999" ... Shouldn't that code stop me from typing once I get to "999" ? I know it is possible to do it using various datagridview events but I'm wondering if it is possible to do that upon adding the column to the datagridview.
Thank you

A: Well, I wasn't able to find an alternative to MaxInputLength so I used a CellValidating event.
Private Sub dgvArticles_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvArticles.CellValidating
    'Ensures only numeric values are entered in these fields
    If e.ColumnIndex = 0 Then
        If e.FormattedValue <> "" And (e.FormattedValue < 0 Or e.FormattedValue >= 1000) Then
            MsgBox("IL # must be greater than 0 and less than 1000")
            e.Cancel = True
        End If
    End If
End Sub


text:
Q: react js push to page from another localhost I have a project developed with nodejs and react js and a button that redirects me to http://localhost:3000/openProblemSetter  with the following code :
codeProblem =() => {

  localStorage.setItem('token', null);
  this.props.history.push('/openProblemSetter');
}

       <Button
         className="button_style"
            variant="contained"
            color="default"
            size="small"
            onClick={this.codeProblem}
          >
            ADD
          </Button>

I have another server running that opens http://localhost:8000/OpenProblemSetter
what can I do so the button redirects me to localhost:8000 and not localhost:3000 if that's possible

A: Method 1 : You can use location.assign('url') to navigate to a new page.
Method 2 : Or you also can use Redirect from React Router routing library. <Redirect to='url'/>


text:
Q: .NET Framework issue which I can't fix without formatting the PC I'm having an issue which I know I can fix by formatting the computer. Though, yesterday I was all afternoon installing it and installing all my programs, and I didn't want to go over it again...
This seems to happen when there's a bad problem and I have to run SFC (cause of that would be modifications in the system to change its aspect). And the error (on Winaero Tweaker) is the following, which only appears after what I described, and never happens if no problem appears on the computer:
System.IO.IOException: The parameter is incorrect.

   em Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str)
   em Microsoft.Win32.RegistryKey.CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, Object registrySecurityObj, RegistryOptions registryOptions)
   em Microsoft.Win32.RegistryKey.CreateSubKey(String subkey)
   em WinaeroTweaker.Classes.TweakerFavorites.PopulateFavorites()
   em WinaeroTweaker.MainForm.PopulateFavoritesToNode(String RootNodeName)
   em WinaeroTweaker.MainForm.AddNodes()
   em WinaeroTweaker.MainForm.MainForm_Load(Object sender, EventArgs e)
   em System.Windows.Forms.Form.OnLoad(EventArgs e)
   em System.Windows.Forms.Form.OnCreateControl()
   em System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   em System.Windows.Forms.Control.CreateControl()
   em System.Windows.Forms.Control.WmShowWindow(Message& m)
   em System.Windows.Forms.Control.WndProc(Message& m)
   em System.Windows.Forms.Form.WmShowWindow(Message& m)
   em System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

************** Loaded assemblies **************
mscorlib
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.4341.0 built by: NET48REL1LAST_C
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/mscorlib.dll
----------------------------------------
WinaeroTweaker
    Versão da assemblagem: 0.19.1.0
    Versão Win32: 0.19.1.0
    CodeBase: file:///C:/Program%20Files/Winaero%20Tweaker/WinaeroTweaker.exe
----------------------------------------
System
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.4300.0 built by: NET48REL1LAST_C
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Windows.Forms
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.4341.0 built by: NET48REL1LAST_C
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.3761.0 built by: NET48REL1
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
WinaeroControls
    Versão da assemblagem: 2.0.2.7
    Versão Win32: 2.0.2.7
    CodeBase: file:///C:/Program%20Files/Winaero%20Tweaker/WinaeroControls.DLL
----------------------------------------
System.Configuration
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.4190.0 built by: NET48REL1LAST_B
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Core
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.4341.0 built by: NET48REL1LAST_C
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Xml
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.3761.0 built by: NET48REL1
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Windows.Forms.resources
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.7.3190.0 built by: NET472REL1LAST_C
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms.resources/v4.0_4.0.0.0_pt_b77a5c561934e089/System.Windows.Forms.resources.dll
----------------------------------------
System.Data
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.4270.0 built by: NET48REL1LAST_C
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_64/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
System.Numerics
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.8.3761.0 built by: NET48REL1
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Numerics/v4.0_4.0.0.0__b77a5c561934e089/System.Numerics.dll
----------------------------------------
mscorlib.resources
    Versão da assemblagem: 4.0.0.0
    Versão Win32: 4.7.3190.0 built by: NET472REL1LAST_C
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/mscorlib.resources/v4.0_4.0.0.0_pt_b77a5c561934e089/mscorlib.resources.dll
----------------------------------------

Note: this is in Portuguese. If more translation is necessary please tell me and I'll translate any words (though, I think the main parts are translated).
Would anyone know if this is a system problem or a problem of the program itself? If it from the system, how can I fix it? (If it's from the program, I'll have to ask the developer and see if he can fix it - or just format this thing again...)
Thanks in advance for any help!

A:
I know I can fix by formatting the computer. ....   ... And the error
(on Winaero Tweaker)

Possibly reinstalling Windows may be the way.
Consider a Repair Install. Uninstall Winaero Tweaker first.  Note the 3 methods and try the first after uninstalling Winaero Tweaker and other third party apps that are not mainstream. See if the normal repair fixes things. Nothing lost.  The third option may be necessary in the event of (a) very severe damage or (b) User Profile damage.
Go to the Media Creation Link:
https://www.microsoft.com/en-us/software-download/windows10
Windows 10 is running, so click on the Download button (not Upgrade Button) and select Run.
If the Repair will not run as per above, use the Download button to create a USB Windows Installation key,
then run Setup on the USB Key.
This will launch the Repair and proceed normally.  There are 3 ways to proceed, according to the severity of the error.

(1) Keep Everything: Best if it works and your computer comes back
just the way you had set it up except repaired.  Always have a backup,
but generally nothing will be lost.
(2) Keep Data: Necessary if the operating system damage is extensive.
Keeps the User Profile and makes software install quite easy. Always
have a backup, but data is not usually lost.
(3) Keep Nothing: Deletes the User Profile and all else and is
essentially a fresh install.  Be certain you have backed up all your
data. "Keep Nothing" is necessary if the User Profile is damaged,
because broken User Profiles cannot be repaired and it is generally
easier to back up and start over if the User Profile is damaged. It
depends on the precise situation.


text:
Q: Spring cloud @HystrixCommand doesn't proxy the method which is invoked in CompletableFuture.supplyAsync I have one spring component bean which contains a method methodA defined by @HystrixCommand with fallbackMethod. The bean has another method methodB invokes methodA by CompletableFuture.supplyAsync(...). I expect Hystrix javanica will weave the aspect on methodA, but when I debug it, I didn't see hystrix aspect is weaved.
Here are some of the main sudo code,
TestApplication:
package com.my.own.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.my.own.test")
public class TestApplication {
    public static void main(final String[] args) throws Exception {
        SpringApplication.run(TestApplication.class, args);
    }
}

ApplicationConfiguration:
package com.my.own.test;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy(exposeProxy = true)
@EnableConfigurationProperties
@EnableCircuitBreaker
public class ApplicationConfig {

}

AsyncConfig:
package com.my.own.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

   @Value("${spring.threadpool.executor.core:10}")
   private int corePoolSize;

   @Value("${spring.threadpool.executor.max:20}")
   private int maxPoolSize;

   @Value("${spring.threadpool.executor.queue:1000}")
   private int queueCapacity;

   @Value("${spring.threadpool.executor.timeout:true}")
   private boolean coreThreadTimeOut;

   @Value("${spring.threadpool.executor.keepalive:30000}")
   private int keepAlive;

   @Value("${spring.threadpool.executor.prefix:ThreadPoolTaskExecutor}")
   private String threadNamePrefix;

   @Bean("taskExecutor")
   public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
       final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
       executor.setCorePoolSize(corePoolSize);
       executor.setMaxPoolSize(maxPoolSize);
       executor.setQueueCapacity(queueCapacity);
       executor.setAllowCoreThreadTimeOut(coreThreadTimeOut);
       executor.setKeepAliveSeconds(keepAlive);
       executor.setThreadNamePrefix(threadNamePrefix + "-");
       executor.initialize();

       return executor;
   }
}

TestController:
package com.my.own.test.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.my.own.test.core.TestProcessor;

@RestController
public class TestController {

    private static Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    TestProcessor tester;

    @RequestMapping(value = "/test", method = { RequestMethod.POST })
    public void test() {
        tester.methodB();
    }
}

TestProcessor:
package com.my.own.test.core;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Component
public class TestProcessor {

    @Autowired
    private ThreadPoolTaskExecutor executor;

    public void methodB() {
        final List<CompletableFuture<String>> a = new ArrayList<>();
        a.add(CompletableFuture.supplyAsync(() -> methodA(), executor));
        CompletableFuture.allOf(a.toArray(new CompletableFuture[a.size()])).join();
    }

    @HystrixCommand(fallbackMethod = "deferPushdown")
    public String methodA() {
        if (true) {
            throw new RuntimeException();
        } else {
            return "methodA";
        }
    }

    public String deferMethodA() {
        return "deferMethodA";
    }
}

Run output
Jan 03, 2018 2:55:55 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.concurrent.CompletionException: java.lang.RuntimeException] with root cause
java.lang.RuntimeException
    at com.my.own.test.core.TestProcessor.methodA(TestProcessor.java:40)
    at com.my.own.test.core.TestProcessor.lambda$0(TestProcessor.java:33)
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

P.S.
From the output, methodA is not invoked from hystrix aspect, but by lambda directly. Is this an issue on Hystrix or javanica? Please share if you know a solution. I appreciate it.

A: Unless you're using aspectj weaving (which requires special handling of compile steps, I think), spring defaults to using interface/cglib weaving, which only applies to the first method called from outside the class, as described in https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-understanding-aop-proxies.
In summary, if you call methodB, no aspect applies and the call from methodB to methodA is not eligible for aspect interception.
To activate the aspect you have to call methodB directly from outside the TestProcessor class.


text:
Q: SQL Report Server URL growing out of control (ExecId & PingId) I have a report that allows users to drill into sub reports and then come back to the main report and enter new criteria.  I'm noticing that with each drill down and then back to the main report that the following information is added to my URL with each link clicked:
&ExecId=xq4pydfqqc3eqkygktfx0uah&PingId=f3kthzre4mbyg0mfjsfe0qmu

That is what I get after my first link followed, each additional link produces another:
&PingId=f3kthzre4mbyg0mfjsfe0qmu

After a user has been doing this for a while, the link starts to look like this:
&PingId=hbtv1gyagv4tsx55cdfc1on5&PingId=ghdx5b45fn4qk045zggkpi45&PingId=ykb5ku2jhy1d11iyaguann45&PingId=eryqw4eg3md2bsmsmxmqce45&PingId=3l4ppd45nl1t3355o0cbzij4&PingId=bxcp4l45cosufzba2o5cj355&PingId=oyqnea55wfkefv4552kj1045&PingId=nrhjfxjinnvmgl45rcqqbk55&PingId=44yavxb0rcldabuqzdeekl3a&PingId=3o4mtxy0e4hise454zfvp055&PingId=r1pjxf55o1yy0f55pfd1u345&PingId=m5j5xa550y4dmrqfrsfmczua

We're noticing not only performance issues, but eventually IE just craps out and I assume this is due to hitting the 2083 character URL max (roughly 20 links clicked).
I can find NO information about what the PingId is or what its purpose is.  I believe it's like a GUID that tracks what you've done allowing you to drill back out of a report.  Maybe that GUID is a representation of a variable being passed into the sub report, I don't know.  Is there a way to scrub the URL when you click on a sub report or to drop the tracking that RS is doing?  What I do know is that it's giving us a headache.
Thanks in advance.

A: I found a solution to my problem...  This DOES NOT explain what the PingId is and why it's growing.  Rather than setting the Action of a field to "jump to report" I changed it to "jump to url".  Then I created a formula (see below) that takes the user back to the original report passing the arguments needed.  This changes how the report is viewed (notice that it's ReportServer/Pages vs Reports/Pages).  I found this article to be helpful: http://dobrzanski.net/2008/08/11/reporting-services-problem-with-passing-parameters-directly-in-the-url/
http://rs/ReportServer/Pages/ReportViewer.aspx?%2fDepartment+Reports%2fOperations%2f.Receiving+Stuff%2fPaperless+Receiving&rs:Command=Render&po_number="&Fields!po_number.Value


text:
Q: Possible bug / numerical issues with HypergeometricU -- any suggestions for a fast workaround? I've encountered some problematic behaviour with HypergeometricU.  I have a probability distribution on the positive integers that takes the following form after integrating out a few degrees of freedom:
prob[α_, γ_, T_, k_] := ((T)^k Gamma[k + α] Gamma[α + γ]
    HypergeometricU[k + α, 1 + k - γ, T]) / (k! Gamma[α] Gamma[γ])

For many ranges of parameters, this works nicely, but if you plug in something like α = 0.145, γ = 1.71, and T = 53, you'll see that this (incorrectly) evaluates to zero for 14 <= k <= 128.  This is somewhat "annoying" (not my original choice of words), given that I would like to perform maximum likelihood / Bayesian analysis on a set of data, but keep running up against Indeterminate outputs whenever my log-likelihood function collides with these erroneous results.  (And as luck would have it, the maximum likelihood values for my data set look like they fall in the "broken" zone.)
Now, I can go back to the integral definition of HypergeometricU and attempt to perform that numerically, say with something naive like:
myU[a_?NumericQ, b_?NumericQ, z_?NumericQ] :=
    Re[1/Gamma[a] NIntegrate[Exp[-z t] t^(a - 1) (1 + t)^(b - a - 1), {t, 0, ∞}]]

but this makes my log-likelihood function run s...l...o...w, taking on the order of 30s per call.  In addition, the functional form of the integral can be problematic for numerical integration -- as a gets large, the function becomes a very tall, but very narrow spike.  (I've tried several different options in NIntegrate, but none quiet the error messages that abound whenever I try applying NMaximize to my log-likelihood.)
Any suggestions from the community?  Or are many fun hours reading Abramowitz and Stegun, looking up, checking, rederiving, and ultimately coding up appropriate asymptotic forms in my future?  (I can do this, but part of my reason for using Mathematica is so that I don't have to do this ...)

A: I think it is a working precision problem because you work with big numbers (for Factorial, Gamma and HypergeometricU these numbers are big).
Therefore, you can simply increase the precision
Nprob[α_, γ_, T_, k_] := prob @@ SetPrecision[{α, γ, T, k}, 100]

prob[0.145, 1.71, 53, 100]
Nprob[0.145, 1.71, 53, 100]

0.
0.00024978428152868438468357163500888181009355521204244571578248072896\
   52983233226993080280022314532640

However, it is a problem that the precision of HypergeometricU is poor with MachinePrecision.


text:
Q: All of my websites are using dark mode in Google Chrome but unclear why? I have Google Chrome installed with google-chrome-stable from apt on ubuntu 21.04
It says the version is Version 92.0.4515.107 (Official Build) (64-bit)
Currently all websites have a dark mode which I don't necessarily want.
Chromium and Firefox on the same computer do not have the same issue
For example this website (unix.stackexchange.com) looks like this
Note that interestingly, in devtools, running window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; is false so it might not be related to a website dark mode preference automatically getting turned on(?)
Happens in private browsing and normal also, so shouldnt be extension related

A: Turns out I had in the chrome experiments in chrome://flags
"Force Dark Mode for Web Contents" enabled
Disabling it fixed it


text:
Q: Why doesn't docker build copy the files over? I am trying to deploy a python Webapp which is basically an interface for an excel file. The application is based on python.
I've build and ran the container on my local machine and everything is smooth. But when I try to deploy on Azure Web Apps I face an issue which says that my file is missing.
The Dockerfile looks like this
FROM python:3.8-slim-buster AS base

WORKDIR /home/mydashboard

RUN python -m pip install --upgrade pip
RUN pip3 install pipenv
COPY Pipfile /home/mydashboard/Pipfile
COPY Pipfile.lock /home/mydashboard/Pipfile.lock
COPY dataset.csv /home/mydashboard/dataset.csv
COPY src/ /home/mydashboard/src
RUN pipenv install --system
WORKDIR /home/mydashboard/src

EXPOSE 8000

CMD gunicorn -b :8000 dashboard_app.main:server

Weirdly enough when this runs on the Azure App Service I receive a message which was that "dataset.csv" does not exist.
I printed the files inside of  /home/dashboard/ it seems that it was an empty folder!!
Who does this happen??
It runs perfectly on my personal computer but it seems that it just run on Azure.

A: Based on:

*

*Your error message is dataset.csv does not exist

*It works on your local machine

*Fails in Azure

Probably dataset.csv exists in the copy from location on your local machine, but is missing in Azure.


text:
Q: Facebook Scores in Android Studio I'm wondering on how to save and the get back the score in Facebook sdk (Android). They explained it in few words but I don't understand nothing from that :S. How to ask and then handle the result with score? This is my code for it:
Getting the score
Bundle param = new Bundle();
param.putInt("score", myScore);

accessToken = AccessToken.getCurrentAccessToken();
new GraphRequest(
        accessToken,
        "/me/scores",
        param,
        HttpMethod.POST,
        new GraphRequest.Callback() {
            public void onCompleted(GraphResponse response) {
            }
        }
).executeAsync();

Setting the score
accessToken = AccessToken.getCurrentAccessToken();
new GraphRequest(
        accessToken,
        "/me/scores",
        null,
        HttpMethod.GET,
        new GraphRequest.Callback() {
            public void onCompleted(GraphResponse response) {
                try {
                    fbTotalScore = response.getJSONObject().getInt("score");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                tvTotalPushUps.setText(String.valueOf(fbTotalScore));
            }
        }
).executeAsync();


text:
Q: Making a list of dict from a list of lists with the list[0] as keys and other lists as values could you tell me how can I get a list of dicts from that with the a[0] as keys for each dict and a[1:] as values accordingly.
a = [['PORT', 'NAME', 'STATUS', 'VLAN', 'DUPLEX', 'SPEED', 'TYPE', 'FC_MODE'], ['Gi1/0/1', 'S1-P1-01 Cisco_Roo', 'connected', '248', 'a-full', 'a-1000', '10/100/1000BaseTX', ''], ['Gi1/0/2', '', 'notconnect', '121', 'auto', 'auto', '10/100/1000BaseTX', ''], ['Gi1/0/3', '', 'notconnect', '121', 'auto', 'auto', '10/100/1000BaseTX', '']]

I wanna get
[{'PORT' : 'Gi1/0/1',
'NAME' : 'S1-P1-01 Cisco_Roo',
.
.
.
},
{'PORT' : 'Gi1/0/2',
'NAME' : '',
.
.
.
}]

A: Does this work?
a = [
    ['PORT', 'NAME', 'STATUS', 'VLAN', 'DUPLEX', 'SPEED', 'TYPE', 'FC_MODE'],
    ['Gi1/0/1', 'S1-P1-01 Cisco_Roo', 'connected', '248', 'a-full', 'a-1000', '10/100/1000BaseTX', ''],
    ['Gi1/0/2', '', 'notconnect', '121', 'auto', 'auto', '10/100/1000BaseTX', ''],
    ['Gi1/0/3', '', 'notconnect', '121', 'auto', 'auto', '10/100/1000BaseTX', '']
    ]

import pandas as pd

pd.DataFrame(a[1:],columns=a[0]).to_dict(orient="records")

Creates this output.
[{'PORT': 'Gi1/0/1',
  'NAME': 'S1-P1-01 Cisco_Roo',
  'STATUS': 'connected',
  'VLAN': '248',
  'DUPLEX': 'a-full',
  'SPEED': 'a-1000',
  'TYPE': '10/100/1000BaseTX',
  'FC_MODE': ''},
 {'PORT': 'Gi1/0/2',
  'NAME': '',
  'STATUS': 'notconnect',
  'VLAN': '121',
  'DUPLEX': 'auto',
  'SPEED': 'auto',
  'TYPE': '10/100/1000BaseTX',
  'FC_MODE': ''},
 {'PORT': 'Gi1/0/3',
  'NAME': '',
  'STATUS': 'notconnect',
  'VLAN': '121',
  'DUPLEX': 'auto',
  'SPEED': 'auto',
  'TYPE': '10/100/1000BaseTX',
  'FC_MODE': ''}]

A: The easiest is probably:
[dict(zip(a[0], x)) for x in a[1:]]

This walks through each element from 1 onwards, and combines it with the first element, converting to a dictionary.


text:
Q: How to append docx file in Golang I want to copy all the contents of a docx file (including its formatting like bold, underline, bullets, paragraphs, etc.) and append it to another docx file.
In this case I want to copy contents from Source/D1.docx and append it to temp.docx
package main

import (
    "io/ioutil"
    "log"
    "os"
)

func main() {
    data, err := ioutil.ReadFile("./Source/D1.docx")
    if err != nil {
        log.Println(err)
    }

    file, err := os.OpenFile("temp.docx", os.O_APPEND|os.O_WRONLY, 0644)
    if err != nil {
        log.Println(err)
    }
    file.Write(data)
}

A: Do this:
git clone --depth 1 git://github.com/unidoc/unioffice
New-Item -ItemType Directory unioffice/document/merge
Set-Location unioffice/document/merge
git pull origin pull/448/head

Then in the merge folder, make this file:
package main

import (
   "github.com/unidoc/unioffice/document"
   "os"
   "path/filepath"
)

func main() {
   s := "TestDocument.docx"
   doc0, e := document.Open(s)
   if e != nil {
      panic(e)
   }
   defer doc0.Close()
   doc1, e := document.Open(s)
   if e != nil {
      panic(e)
   }
   defer doc1.Close()
   doc0.AddParagraph().AddRun().AddPageBreak()
   if e := doc0.Append(doc1); e != nil {
      panic(e)
   }
   out := filepath.Join(os.TempDir(), "merged.docx")
   doc0.SaveToFile(out)
}

Note this is just for testing, for real code you will want to get a license.
https://github.com/unidoc/unioffice


text:
Q: Change URL structure from /blog-post.php?id_blog_post=852 to something like /unblur-course-hero How can I change
/blog-post.php?id_blog_post=852

to
/unblur-course-hero

which is the title of the page.
I need a proper URL structure without _?/ etc

A: You have to store this value: unblur-course-hero in your DB record as a slug with id of this post equal to 852, after that you can check in your controller if there is any record with slug value equal to requested, and return html if exist such record.
Example:
Request:
/blog-post.php?id_blog_post=852

URL you have to create:
/unblur-course-hero

Controller:
public function index($slug = false){
   if($slug){
       //we have slug here, we search for record, overwise skip
       //query to check DB where `slug` = $slug
       //DO NOT FORGET TO USE BEST PRACTICES TO BIND VALUES while you make any
       //searches using public requests.
   }
   //perform regular index page rendering.
}


text:
Q: Understanding a Proof Regarding the Infinitude of Even Abundant Numbers I was reading the following theorem.

Theorem. There are infinitely-many even abundant numbers.
Proof. For a positive integer $a$, let $n=2^a\cdot3$, and compute$$\sigma(2^a\cdot3)=\sigma(2^a)\sigma(3)=(2^{a+1}-1)(3+1)=2(2^a\cdot3)+2^{a+1}-4=2n+2^{a+1}-4,$$
  which is greater than $2n$ whenever $a\geq2$. This demonstrates
  infinitely-many even abundant numbers. $\square$

I know that this proof assumes knowledge of the fact that the smallest even abundant number is $12=2^2\cdot3$, and that any multiple of an abundant number is also abundant. However, It is not immediately clear to me that $2^{a+1}-4$ is a multiple of $2n$ for $n\geq2$. What am I missing?
Thanks in advance.

A: All that the proof is demonstarting is that each number of the form $2^a \cdot 3$ is abundant when $a \geq 2$.
Recall a number $n$ is abundant when $\sigma(n) > 2n$.  This follows by the above calculation since:
$$\begin{align}
\sigma(2^a \cdot 3) = 2(2^{a}\cdot 3) + 2^{a+1} - 4 > 2 (2^a \cdot 3) &\iff  2^{a+1} - 4 > 0
\\
&\iff 2^{a+1} > 2^2
\\
&\iff a > 1.
\end{align}$$
This argument does not rely on $12$ being the smallest abundant number, or that a multiple of an abundant number is again abundant.  It just states that every number of the form $n = 2^a \cdot 3$ is abundant when $a \geq 2$.  This set of integers forms in infinite set of even abundant numbers.


text:
Q: Powershell -like operator confusion Why does the following powershell code give false instead of true?
"ok" -like "??p*"

A: Because * is a wildcard/glob and not a regex metacharacter.
Your pattern ??p* isn't saying "any two characters followed by zero-or-more 'p' characters" it is saying "any two characters followed by a 'p' followed by anything".

A: Your wildcard expression expect at least 3 characters with the third character being a p. As this is not the case the expression will return false.
See http://ss64.com/ps/syntax-wildcards.html


text:
Q: How to list Google Merchant Center Feeds I am trying to read customers' feeds through Google API. I got an access token.
This is the documentation I followed: https://developers.google.com/shopping-content/developers-guide-python#authentication
Example here shows an ACCOUNT_ID to use, but I don't understand where to receive this info.
import gdata.contentforshopping.client
ACCOUNT_ID = '1234567'
shopping_client = gdata.contentforshopping.client.ContentForShoppingClient(account_id=ACCOUNT_ID)

Here is what i did so far:
import gdata.contentforshopping.client
import gdata.gauth

part = 2

auth_token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=SCOPE, user_agent=USER_AGENT)
shopping_client = gdata.contentforshopping.client.ContentForShoppingClient()
authorize_url = auth_token.generate_authorize_url(redirect_uri=APPLICATION_REDIRECT_URI)

if part == 1:
    print 'Please visit: %s' % authorize_url

elif part == 2:

    query = {'code': 'xxxx'} # received from result of part == 1
    auth_token.get_access_token(query)
    auth_token.authorize(shopping_client)
    accounts = shopping_client.GetClientAccounts()
    print(accounts)

A: It turned out there is no proper way to do this. You have to get an error from old API and parse it to find out your merchant id.
Source: https://groups.google.com/forum/#!topic/google-content-api-for-shopping/3iLEm9puJis


text:
Q: I want to make a button automatically clickable without a tap in flutter. I'm also using WebView flutter: I want to make the bottom portion (that includes an ad) of the WebView clickable without a touch/tap. My WebView contains a floating ad in its bottom portion. I want to make it auto clickable without tapping it again and again. I have used IgnorePointer class. Some portion of my code is commented, you can check it also.
(Note: I'm doing this just for learning)
here is my code:
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomeScreen extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    final _key = UniqueKey();
    final height=MediaQuery.of(context).size.height;
    // return CustomScrollView(
    //
    //   slivers: <Widget>[
    //     SliverAppBar(
    //       title: const Text("Software Testing Help"),
    //       floating: true,
    //     ),
    //     SliverFillRemaining(
    //       child: WebView(initialUrl: "https://www.softwaretestinghelp.com/digital-marketing-software/"),
    //     )
    //   ],
    // );
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: height*0.08,
        backgroundColor: Colors.black,
        title: Center(child: Text('Software Testing Help', style: TextStyle(
          color: Colors.white
        ),)),
      ),
      body:
         Stack(
           children: [
              Container(
                   height: height*0.90,
                   child: Expanded(
                     child: WebView(
                       initialUrl: 'https://www.softwaretestinghelp.com/digital-marketing-software/',
                       key: _key,
                       javascriptMode: JavascriptMode.unrestricted,
                     ),
                   )

             ),
             Positioned(
               bottom:0,
               left: 10,
               child: GestureDetector(
                 onTap: (){
                   Scaffold.of(context).showSnackBar(SnackBar(
                     content: Text('Ad is clicked'),
                   ));
                 },
                 child: IgnorePointer(
                     ignoring: true,
                     child: Container(
                       decoration: BoxDecoration(
                         border: Border.all(
                           color: Colors.blue
                         )
                       ),
                       height: 100,
                       width: 100,

                     ),

                 ),
               ),
             )
           ]
         )

    );
  }

}

A: you can do it automatically by a timer, after a period of time this timer will call your function.
something like this:
bool? isLoading;

adClickedRunner() {
    Timer(
      Duration(seconds: 5), //example: after 5sec will call your task
      () async {
        isLoading = true; //to show circularProgressIndicatior for your button
        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text('Ad is clicked'),));
        isLoading = false;
      },
    );
  }


text:
Q: What is the Ubuntu installation going to do to my Windows files...? I am installing Ubuntu 12.10 in Windows with Wubi and I want to know if it's going to COPY my Windows files and place them in Ubuntu, or MOVE them to Ubuntu, or leave the Windows files so I start with an empty Ubuntu (which I want). Can someone please tell me?

A: It will leave the Windows files alone and create a place for Ubuntu to run out of.  WUBI installs Ubuntu as an application inside of Windows.

A: That's up to you. Ubuntu can be installed besides Windows. So you have a multi-boot system and no files are touched. Of course, you need enough space for doing this.
The other option is to wipe all the data and install Ubuntu over your system, so every file on your system partition are lost.
My Advise: Backup all files you want to keep.


text:
Q: Declaring an Angular2 Service with ES5 I was having trouble injecting a service into a component using ES5. I was finally able to get it to work, but discovered a couple different ways a service can be declared. Are one of these the more "Angular" way to declare a service?
Here is the component
(function (app) {
app.employeeSearchComponent = ng.core
    .Component({
        selector: 'employee-search',
        templateUrl: rootUrl + 'Home/EmployeeSearch',
        providers: [app.Service]
    })
    .Class({
        constructor: [app.Service, function(service) {
                   console.log(service.greeting);
            }]
        });
})(window.app || (window.app = {}));

Here is the service (Option 1)
(function(app) {
    app.Service = ng.core.Class({
        constructor: function(){},
        greeting: function() {
            return 'hello';
        }
    });
})(window.app || (window.app = {}));

Here is the service (Option 2)
(function(app) {
    app.Service = function() {
        this.greeting = function() {
            return 'hello';
        }
    };
})(window.app || (window.app = {}));

A: I think you will be good with option 1. Find an example from Angular.io cheat sheet
var OtherService = ng.core.Class({constructor: function() { }});

A: Going with first option you could probably declare dependencies to other services, like ng.http, in second you cant do that easily.


text:
Q: Remove right border from the last row items I have a 3 rows list of items. I need to divide first and second row by a borders, so I add right border to the items but I do not need borders for the items from the third row.

.test-row {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-auto-flow: column;
}

.test-row-item {
  padding-bottom: 3.2rem;
  border-right-color: #2C327A;
  border-right-width: 1px;
  border-right-style: solid;
}

    1

    2

    3

    4

    5

    6

    7

    8

    9

A: In this particular case use a second CSS rule that removes the right-border starting from the 7th instance, using the selector .test-row-item:nth-child(n+7):

.test-row {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-auto-flow: column;
}

.test-row-item {
  padding-bottom: 3.2rem;
  border-right-color: #2C327A;
  border-right-width: 1px;
  border-right-style: solid;
}

.test-row-item:nth-child(n+7) {
  border-right: none;
}

    1

    2

    3

    4

    5

    6

    7

    8

    9

A:

.test-row {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-auto-flow: column;
}

.test-row-item:nth-child(n + 4) {
  padding-bottom: 3.2rem;
  border-left-color: #2C327A;
  border-left-width: 1px;
  border-left-style: solid;
}

    1

    2

    3

    4

    5

    6

    7

    8

    9


text:
Q: How can I disable existing FastReport export? I'm using C++ Builder XE7 & FastReport components. My form contains two reports (TfrxReport components) and two export components (TfrxRTFExport, TfrxPDFExport). If I preview any of those two reports I have the option to export to RTF and PDF. But, I would like to disable RTF export for the second report while still having that option for the first report. How to do it? Thanks.

A: Try this solution :

*

*Remove the TfrxRTFExport component from your DataModule.

*Declare your TfrxRTFExport variable.

*On frxReport1Preview event , create your TfrxRTFExport.

*On frxReport1ClosePreview event , Free your TfrxRTFExport.
Another solution :
If you have two button (Button 1 for the report2 , Button2 for the report1) then :
In Button 1 :

*

*Free your TfrxRTFExport then show the report

In Button 2 :

*

*Create your TfrxRTFExport , then show the report.


text:
Q: Geo-Location error objective C I'm trying to create an app that will gather and display my longitude and latitude values in the labels I have set in the storyboard. If i simply assign a simple text to my labels in my IBAction instance, it runs fine and the text is displayed. However, when I use the code in my IBAction instance below, nothing is displayed in my labels when I press my button.
  @interface ViewController ()

@end

@implementation ViewController {
     CLLocationManager *locationManager;
}

@synthesize longitude, latitude;

- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];

   }

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)getCurrentLocation:(id)sender {

  locationManager.delegate = self;
  locationManager.desiredAccuracy = kCLLocationAccuracyBest;
  [locationManager startUpdatingLocation];
  }

  - (void)locationManager:(CLLocationManager *)manager                        didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
                           initWithTitle:@"Error" message:@"Failed to    Get Your Location" delegate:nil cancelButtonTitle:@"OK"    otherButtonTitles:nil];
[errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {
    longitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    latitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
 }
@end


text:
Q: Windows 7 home: allow create and modify own files but not others? We have a shared family computer running Windows 7 Home Premium (x64). Is it possible to set the Public folders so that kids can create and modify their own files & folders within that tree, while everything else in the tree is read only?

A: The simplest configuration is to allow the Users group to { read, create files, create folders }:
icacls "Public" /remove INTERACTIVE
icacls "Public" /grant Users:(oi)(ci)(r,wd,ad)

Children will always automatically have full control on objects (files and folders) they own or create.

A: You can specifically set a file, or groups of files, to be read only to everyone but you, while the folder they're contained in is both read and write. That way, your files are able to be read, but not edited, and your kids can still add their own files.
Make your files/folders read only, as shown below, but the overall folder read/write.
EDIT
I didn't include my file permissions because it lists my full name, but when changing the permissions for a person on your computer, you should be able to choose 'Allow' or 'Deny' in each area below.
Right-click file -> Properties -> Security tab -> Advanced: From here you should be able to edit the access abilities of each member of your family, or you could create a group as grawity has suggested and put your kids into a group and then give that group certain permissions.


text:
Q: Flutter firestore stream denied exception In my flutter app I have an open stream that is listening to changes on a document on firestore. If I log the user out i receive the following exception:
[Firestore]: Listen for Query(THE_DOC_PATH) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
I/System.out( 6117): com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.

I have a few questions

*

*Does the close the stream for me automatically?

*Are there any downsides to this happening? e.g. using extra reads on the doc or firestore rules

*Should i manually be closing the stream before the user signs out?

Thanks

A:
Does the close the stream for me automatically?

Yes.  After an error like this, there will be no more items emitted from the stream.

Are there any downsides to this happening? e.g. using extra reads on the doc or firestore rules

There are no extra costs, if that's what you're implying.

Should i manually be closing the stream before the user signs out?

Typically, yes. But that's a matter of opinion, and it's up to you.


text:
Q: Splitting a string withisalnum and store into a vector of strings I'm working with a string and trying to break it up whenever it is non-alphanumeric (not a-z, A-Z, and 0-9). I found isalnum to be a useful function to use.
For example, if I have the string "bob-michael !#mi%@pa hi3llary-tru1mp"
The vector should contain: bob, michael, mi, pa, hi3llary, and tru1mp.
My current code is:
  vector<string> result;
  string something = "bob-michael !#mi%@pa hi3llary-tru1mp";
  stringstream pie(something);
  //not sure what to do after this point(I know, not a lot. See below for my current thinking)

My idea was using a loop and while isalnum results in 1 continue forward, if isalnum results in 0 then push whatever I have so far into the vector of strings. Perhaps I could use isalnum as a delim? I'm having a hard time taking my idea and writing this. Could anyone point me in the right direction? Thanks!
Edit: Thanks everyone for the help.

A: Something along these lines, perhaps:
std::vector<std::string> result;
std::string something = "bob-michael !#mi%@pa hi3llary-tru1mp";
std::regex token("[A-Za-z0-9]+");

std::copy(
    std::sregex_token_iterator(something.begin(), something.end(), token),
    std::sregex_token_iterator(),
    std::back_inserter(result));

Demo

A: You can also iterate through the string and then check if the current index is a letter or not, then if not break it then store to vector
std::string something = "bob-michael !#mi%@pa hi3llary-tru1mp";

std::vector<std::string> result;

std::string newResult = "";

for ( int a = 0; a < something.size(); a++ )
{
      if((something[a] >= 'a' && something[a] <= 'z')||(something[a] >= 'A' && something[a] <= 'Z')
          || (something[a] >= '0' && something[a] <= '9'))
      {
          newResult += something[a];
      }
      else
      {
         if(newResult.size() > 0)
         {
            result.push_back(newResult);
            newResult = "";
         }
      }
}
result.push_back(newResult);

A: The std::replace_if trick I commented on turned out to not be quite as trivial as I thought it was because std::isalnum doesn't return bool.
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <algorithm>
#include <sstream>
#include <iterator>

int main()
{
    std::vector<std::string> result;
    std::string something = "bob-michael !#mi%@pa hi3llary-tru1mp";
    // I expected replace_if(something.begin(), something.end(), &isalnum, " ");
    // would work, but then I did a bit of reading and found is alnum returned int,
    // not bool. resolving this by wrapping isalnum in a lambda
    std::replace_if(something.begin(),
                    something.end(),
                    [](char val)->bool {
                          return std::isalnum(val) == 0;
                     },
                     ' ');
    std::stringstream pie(something);

    // read stream into vector
    std::copy(std::istream_iterator<std::string>(pie),
              std::istream_iterator<std::string>(),
              std::back_inserter<std::vector<std::string>>(result));

    // prove it works
    for(const std::string & str: result)
    {
        std::cout << str << std::endl;
    }
}


text:
Q: What is the correct way to catch both Error and Exception following `effective dart`? this code sample
import 'package:flutter_test/flutter_test.dart';

void main() {
  const one = 1;
  String oneAsString() => one as String;

  test('Make sure it fails', () {
    var s;
    var _e;
    try {
      s = oneAsString();
    } on Error catch (e) {
      _e = e;
    }
    expect(s == null, true, reason: 'should fail');
    expect(_e == null, false, reason: 'error or exception should be returned');
  });

  test('Catchin Error', () {
    var _e;
    try {
      oneAsString();
    } on Error catch (e) {
      _e = e;
    }
    expect(_e is Error, true, reason: 'should be an error');
  });

  test('Catchin Exception', () {
    var _e;
    try {
      oneAsString();
    } on Exception catch (e) {
      _e = e;
    }

    expect(_e is Exception, true, reason: 'should be an exception');
  });

  test('Why not BOTH', () {
    var _e;
    try {
      oneAsString();
    } on Error catch (e) {
      _e = e;
    } on Exception catch (e) {
      _e = e;
    }

    expect(_e is Error, true, reason: 'should be an error');
    expect(_e is Exception, false, reason: 'should NOT be an exception');
  });
}

outputs this result
00:02 +2 -1: Catchin Exception [E]
  type 'int' is not a subtype of type 'String' in type cast
  test/widget_test.dart 5:31   main.oneAsString
  test/widget_test.dart 31:18  main.<fn>

00:02 +3 -1: Some tests failed.

the safest approach seems to be Why not BOTH, but following effective dart
(enforcing it with the package effective_dart)
the analysis complains about  avoid_catching_errors

DON'T explicitly catch Error or types that implement it.
Errors differ from Exceptions in that Errors can be analyzed and
prevented prior to runtime. It should almost never be necessary to
catch an error at runtime.
BAD:
try {   somethingRisky(); } on Error catch(e) {   doSomething(e); }
GOOD:
try {   somethingRisky(); } on Exception catch(e) {   doSomething(e);
}

and if I simple do
try {} catch (e) {}

the analyzer complains about avoid_catches_without_on_clauses

AVOID catches without on clauses.
Using catch clauses without on clauses make your code prone to
encountering unexpected errors that won't be thrown (and thus will go
unnoticed).
BAD:
try {  somethingRisky() } catch(e) {   doSomething(e); } GOOD:
try {  somethingRisky() } on Exception catch(e) {   doSomething(e); }

what is the correct approach to catch BOTH Error and Exception?

A: re-posting the answer from @Miyoyo on r/FlutterDev discord
Optimally? You do not catch error
Just, at all
Remember effective dart is Guidelines
Using them as gospel will make some things impossible
Catching error is deliberately made to be "not according to guidelines"

because you're not supposed to do that
for my use case I'll just add
// ignore_for_file: avoid_catching_errors


text:
Q: How to add HTML-tags to JS-file I use Expo (React Native) with the main App.js file.
It's connected to my base with data called data.js.
Example of data.js element:
{
  id: '70078463',
  price: '$49.99',
  name: 'PELLO',
  image:
    'https://www.ikea.com/us/en/images/products/pello-armchair__38296_PE130209_S5.JPG?f=xs'
},

I want to add a description tag with the information about the item:
description: 'This is the best one you can buy online. It is so cool! Why have not you bought it?',

In HTML I could use <p> tag to make each sentense on a new line. How can I do it here?

A: To add a description to your JS Object as a new key-value pair you have two options:
 let object = {
  id: '70078463',
  price: '$49.99',
  name: 'PELLO',
  image:
    'https://www.ikea.com/us/en/images/products/pello-armchair__38296_PE130209_S5.JPG?f=xs'
},

Using Dot Notation:
object.description = "value";

Or Square Bracket Notation:
object["description"] = "value";

If you know for sure it is always description you can use dot notation but if you want to dynamically add key-value pairs the square bracket notation lets you pass in a variable.


text:
Q: Lie algebra of the semiorthogonal group $O(p,q)$ How do I prove this: If $\mathcal{O}(p,q)$ is a Lie algebra of the semiorthogonal group $O(p,q)$ then $\mathcal O(p,q)$  consist of all matrices of the form:
$$X=
  \left( \begin{matrix}
        a & x^t\\
        x & b \\
   \end{matrix}
\right),$$
where $a\in \mathcal O(p)$ and $b\in \mathcal O(q)$, and $x$ is an arbitrary real matrix $q \times p$.

A: Well you just do the same thing we do every night, Pinky, try to take over the world! Hm, well, I mean, compute differentials of curves.
Suppose that $\gamma$ is a smooth curve in $O(p,q)$ such that $\gamma(0)=I$, the identity matrix. If $x$ and $y$ are two vectors and $\def\i#1{\langle#1\rangle}$ is the usual quadratic form of signature $(p,q)$ on $\mathbb R^{p+q}$ then $\i{\gamma(t)x,\gamma(t)y}$ does not depend on $t$, so differentiating with respect to $t$ we see that $$0=\frac{\mathrm d}{\mathrm dt}\i{\gamma(t)x,\gamma(t)y}=\i{\gamma'(t)x,\gamma(t)y}+\i{\gamma(t)x,\gamma(t)'y}$$ and evaluating at $t=0$, $$0=\i{\gamma'(0)x,y}+\i{x,\gamma(0)'y}.$$ If $x=e_i$ and $y=e_j$ are vectors in the standard basis, then this tells us that $$a_{i,j}\epsilon_j+a_{j,i}\epsilon_i=0.$$ Here $a_{i,j}$ is the $(i,j)$th entry in the matrix $\gamma'(0)$ and $\epsilon_i$ is $1$ if $1\leq i\leq p$, and $-1$ if $p+1\leq i\leq p+q$.
These equations imply that the matrix $\gamma'(0)$ is of the form you want.
This means that the tangent vector space at $I$ is contained in the vector space you wrote in your question. Now compare dimensions.

If you do not know already the dimension of the group, well, you need more work. Let now $A$ be a matrix in the space you wrote and consider the curve $\gamma:t\mapsto e^{At}$. More or less the same reasoning as above show that the function $t\mapsto\i{\gamma(t)x,\gamma(t)y}$ is constant, so that the curve is contained in your group. As its tangent vector at zero is the matrix $A$, this proves the other containment.


text:
Q: Error AttributeError: 'function' object has no attribute 'json' occures when importing functions from other files I'm writting an automated test which uses 3 files helpers.py where I store fucntion of registering, test_mails.py where the test is executed and it runs checking for registration for 5 mails in list, login_credentials.py where json dictionaries are stored. test_mails.py uses unittest library and import main sing_up function for trying to register 5 emails through api requests. The aim of test is to check if system doesn't let these mails to pass. However, when in test_mails.pyI try to use methods from libs json orrequesrts with sing_up function I get these types of errors. AttributeError: 'function' object has no attribute 'json'. This also applies to status_code method How to solve it?
Here are files:
helpers.py
import json
import requests

def sign_up(data):
    with requests.Session() as session:
        sign_up = session.post(
            f'https://siteexample/api/register',
            headers={
                'content-type': 'application/json',
            },
            data=json.dumps(data)
        )
        print(sign_up.content)
        print(sign_up.status_code)

test.mails.py
import unittest
import requests
import json
from login_credentials import data, emails_list
from helpers import *

class Mails(unittest.TestCase):

    def test_sign_up_public_emails(self):
        emails_dict_ls = {}
        for email in emails_list:
            data_copy = data.copy()
            data_copy["email"] = email
            emails_dict_ls.update(data_copy)
            sign_up(emails_dict_ls)

            if 'email' in sign_up.json() and "User with this Email already exists." in
sign_up.json()['email']:
                registering = False
            else:
                registering = True
                assert self.assertEqual(sign_up.status_code, 400)
                assert sign_up.json()['status_code'] == "NOT_CONFIRMED_EMAIL"
            return registering

login_credentials.py
data = {
    "company": "Company",
    "phone": "+1111111",
    "email": "",
    "password1": "defaultpassword",
    "password2": "defaultpassword",
    "terms_agree": True,
    "first_name": "TestUser",
    "last_name": "One"
}

emails_list = ['mailtest.unconfirm@yahoo.com',
               'mailtest.unconfirm@gmail.com',
               'mailtest.unconfirm@ukr.net',
               'mailtest.unconfirm@outlook.com',
               'mailtest.unconfirm@icloud.com'
               ]

A: In the sign_up function in helpers.py. You'll have to return the response so that .json() can be called.
Also, you can use json=data instead of data=json.dumps(data) since it's already a built-in function of python-requests.
def sign_up(data):
  with requests.Session() as session:
    response = session.post(
        f'https://siteexample/api/register',
        headers={
            'content-type': 'application/json',
        },
        json=data
    )
    return response

In test_mails.py, You're just calling the function and not storing the value in a variable.
def test_sign_up_public_emails(self):
    emails_dict_ls = {}
    for email in emails_list:
        data_copy = data.copy()
        data_copy["email"] = email
        emails_dict_ls.update(data_copy)
        sign_resp = sign_up(emails_dict_ls)

        if 'email' in sign_resp.json()


text:
Q: jQuery.active dont updated properly after js error in ajax callback For see thar error just

*

*Write in console:
$.get("/", function(){
throw "test"; //any error here, manually throwed or runtime error
});

*See error throwed
"Uncaught test"

*Check $.active == 1 forever

*$(document).on("ajaxStop"... callback now will not be called forever
jquery 1.10.
What can i do to prevent this issue?

A: You can use .ajaxError().
$( document ).ajaxError(function() {
  $( ".log" ).text( "Triggered ajaxError handler." );
});

more Details : http://api.jquery.com/ajaxError/

A: I solved this issue by using try - catch in success and fail callback function, I simply logged the error in catch block and then it works fine.


text: Q: Unexplained variables in linear model output Could anyone please shed a light on why instead of displaying Month^1, Month^2 and Month^3, my model summary showed Month.L, Month.Q, Month.C. Also, what month did the Intercept refer to: January or December (please find attached image)?


text:
Q: MySQL only run a select statement if a condition is met Can the following be done? Can't get it to work for me
SELECT * FROM DB_1593 WHERE DB_1593_field_0_3 = '--skills--' IF('--dateTime--' < NOW())

A: Try this :
SELECT  *
FROM    DB_1593
WHERE   DB_1593_field_0_3 = '--skills--'
AND     '--dateTime--' < NOW()

Or even this works:
SELECT  *
FROM    DB_1593
WHERE   DB_1593_field_0_3 = '--skills--'
AND     IF('--dateTime--' < NOW())

A: You can try this query:
SELECT * FROM DB_1593
WHERE DB_1593_field_0_3 = '--skills--' AND IF('--dateTime--' < NOW())

A: You can use the IF clause as
DECLARE @COLUMN_NAME = 2

IF (@COLUMN_NAME <= 3)
    Select * FROM DB_1593 WHERE DB_1593_field_0_3 = '--skills--'

Reference https://www.guru99.com/sql-server-if-else.html


text:
Q: Streamlining if statement conditions to include a <= statement Managed to use an answer from someone else's question 11 years ago (How can you detect the version of a browser?) to retrieve the browser name and version that is being used and tie it into an if statement for displaying an alert message for out of date browsers (my if statement copied below).
What I'm wondering is if there is a simpler way for notating version <= Safari 12 so that Safari 11, 10, 9, etc. would get detected instead of doing the string of or || conditionals one after another.
if (navigator.sayswho === 'Safari 12' || navigator.sayswho === 'Safari 11' || navigator.sayswho === 'Safari 10' || navigator.sayswho === 'Safari 9') {
   alert('Your browser ('+ navigator.sayswho +') is out of date, some features of our website may not work with your browser version.\r\n Please update your browser to ensure compatibility with our online product forms.\r\n\r\n');
  }

It works, but I'm trying to learn how to make it a bit more elegant and slimmed down code wise. Thanks for any input you can provide. Stackoverflow has made my journey into development and website management a lot more productive and enjoyable for the last year. Cheers all.

A: A regular expression test will do the trick.
if (/Safari (?:12|11|10|9)/.test(navigator.sayswho)) {

Another approach would be to match the trailing digits, then check if they're in the range.
const match = navigator.sayswho.match(/Safari (\d+)/);
const num = match ? Number(match[1]) : 0;
if (num <= 12 && num > 9) {

A: I would recommend changing the check to:
const browser_list = [
    'Safari 12',
    'Safari 11',
    'Safari 10',
    'Safari 9'
];
if (browser_list.includes(navigator.sayswho)) {
    // etc.
}

This is readable, maintainable, and can easily be changed in the future for new browsers and versions.


text:
Q: looping a SQL insert statement with updating dates What do I need to do is run insert the same thing into a database only changing the date.
i.e
INSERT INTO bs_events
(
    eventDate,
    eventTime,
    title,
    spaces,
    description,
    entryFee,
    payment_required,
    max_qty,
    allow_multiple
)
VALUES (
    '2011-03-02 00:00:00',
    '10:00',
    'Carpet Cleaner 3000',
    '4',
    'This is rad',
    '25.99',
    '1',
    '1',
    '2'
)

So I need to run this loop for a year or month or 2 years and have it add to the database but the date needs to change each day
I've got no idea how I go about making a script to do this so any help would be appreciated
Thanks

A: Instead of inserting the date directly maybe you could use now(), assuming that it is the current date you want to insert.

A: The following will insert the current date instead of a preset date.  This assumes you're using MySQL.
INSERT INTO bs_events
(
    eventDate,
    eventTime,
    title,
    spaces,
    description,
    entryFee,
    payment_required,
    max_qty,
    allow_multiple
)
VALUES (
    DATE_FORMAT(CURDATE(),'%Y-%m-%d %H:%i:%s'),
    '10:00',
    'Carpet Cleaner 3000',
    '4',
    'This is rad',
    '25.99',
    '1',
    '1',
    '2'
);

You can create a stored procedure to loop and insert as many as you want starting from today using this:
DELIMITER //
CREATE PROCEDURE loopInsert()

BEGIN
    DECLARE a INT DEFAULT 0;
    myloop: LOOP
        INSERT INTO bs_events
(
    eventDate,
    eventTime,
    title,
    spaces,
    description,
    entryFee,
    payment_required,
    max_qty,
    allow_multiple
)
VALUES (
    DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL a DAY),'%Y-%m-%d %H:%i:%s'),
    '10:00',
    'Carpet Cleaner 3000',
    '4',
    'This is rad',
    '25.99',
    '1',
    '1',
    '2'
);
        SET a = a + 1;
        IF a = 6 THEN
            LEAVE myloop;
        END IF;
    END LOOP myloop;
END//
DELIMITER ;

Then you can:
CALL loopInsert();

And it will insert a days starting from today.  The example would insert 6 days.

A: Here's an example. It does it all in one query.
$row = array(
    '2011-03-02 00:00:00',
    '10:00',
    'Carpet Cleaner 3000',
    '4',
    'This is rad',
    '25.99',
    '1',
    '1',
    '2'
);

$rows = array();
$end = new DateTime('2012-01-01');
for($date = new DateTime($row[0]); $date < $end; $date->modify('+1 day')) {
    $row[0] = $date->format('Y-m-d H:i:s');
    $rows[] = sprintf("('%s')", implode("','", $row));
}

$query = 'INSERT INTO bs_events
(
    eventDate,
    eventTime,
    title,
    spaces,
    description,
    entryFee,
    payment_required,
    max_qty,
    allow_multiple
) VALUES '.implode(',', $rows);

Note: This works because the row data is known... if you accepting user input, make sure you are checking for SQL injection.


text:
Q: How Can I Use Join In The Leftjoin With Laravel? I have a question on leftjoin & join in laravel
I want to rewrite following sample to laravel, how can I do this ?
LEFT JOIN(advertsolution_f SF
          JOIN function_d FD ON SF.fd_id = FD.fd_id
          JOIN function_m FM ON FD.fm_id = FM.fm_id)
ON SM.ads_id = SF.ads_id

i try to rewrite it like this,but i think it is not a good idea.
->leftJoin($SF,$SM.'.ads_id',$SF.'.ads_id')
->leftjoin($FD,$SF.'.fd_id',$FD.'.fd_id')
->leftjoin($FM,$FD.'.fm_id',$FM.'.fm_id')

because i have no idea how to join table to $SF privately.

A: For making such complex query you can use RAW EXPRESSIONS like:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->get();

Raw Expressions
Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression.
Reference

A: Map like this,
->leftJoin($SF,$SM.'.ads_id','=',$SF.'.ads_id')
->leftjoin($FD,$SF.'.fd_id','=',$FD.'.fd_id')
->leftjoin($FM,$FD.'.fm_id','=',$FM.'.fm_id')

You are missing = sign in query.
EDIT
EXAMPLE YOU GIVEN, I am writing query on behalf of it, you just need to map with your original fields and tables,
DB::table('a')
->leftJoin("b","b.a_id","=","a.id")
->leftJoin("c","c.b_id","=","b.id")
->leftJoin("d","d.bd_id","=","b.bdid")
->get();

Map this query, as per your requirement,
it should work.