text:
Q: Regex groups for dash delimited filename in URL I have a URL that is structured like so: <domain>/<subdirectory>/<filename>-<semantic_version>-<hash>.<filetype>
For example, it could look like: https://cdn.example.com/sample_files/some_file-1.2.3-56857cfc709d3996f057252c16ec4656f5292802.css
So far I have the following regex which gives me the entire filename. However, I'd like to individually get the filename, semantic_version, and hash as defined above. You can assume that the filename will not has dashes in the name.
([^/\\&\?]+)$(?<=(?:.js))

A: You could match the protocol and then until the last forward slash.
After that, capture 1+ word chars in group 1 for the file name, a repeating part in group 2 to capture digits divided by dots and in the third group a character class which would match all the characters in the hash.
^http\S+\/(\w+)-(\d+(?:\.\d+)+)-([0-9a-f]+)\.\w+$

Explanation

*

*^ Start of string

*http\S+\/ Match the protocol followed by 1+ non whitespace chars, then backtrack till the last /

*(\w+)- Capture group 1, match 1+ word chars followed by -

*(\d+(?:\.\d+)+)- Capture group 2, match digits divided by dots followed by -

*([0-9a-f]+)\.\w+ Capture group 3, match 1+ times the chars from the hash followed by . and 1+ word chars

*$ End of string

Regex demo
If the hash always has 40 characters, you could match [a-z0-9]{40} instead of [a-z]+ to be a bit more precise.

A: Use multiple capture groups that don't match - characters.
([^-/\\&\?]+)-([^-/\\&\?]+)-([^-/\\&\?]+)\.[a-z]+$(?<=(?:.js))


text:
Q: Change text size and color in one time? I create many activities and classes in my app. However I have a function to change font size and color in every activity. This function changes text in own activity. When I go to other activity I must change textSize and color again. How can I create a function to change TextView in many classes and activities in one shot?
My app Structure:
Main.java   main.xml/
Suad1.java  suad1.xml/
Suad2.java  suad2.xml/
Suad3.java  suad3.xml/
Suad4.java  suad4.xml/

I want to change these activity in one time. Here my code in Suad1.class.
public void ShowDialog() {
    final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
    final SeekBar seek = new SeekBar(this);
    seek.getProgress();
    seek.setMax(100);

    popDialog.setIcon(R.drawable.conp);
    popDialog.setTitle(R.string.menu_settings);
    popDialog.setView(seek);
    try {

        seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                 // TODO Auto-generated method stub
            }

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                subtitles.setTextSize(progress);
            }
        });
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    popDialog.setSingleChoiceItems(items , -1,
        new DialogInterface.OnClickListener() {
            int i;
            public void onClick(DialogInterface dialog, int item) {
                i = item;
                if(items[i] =="Blue") {
                    subtitles.setTextColor(getResources().getColor(R.color.font3));
                } else if(items[i] == "Yellow") {
                    subtitles.setTextColor(getResources().getColor(R.color.font1));
                } else if(items[i]== "Red") {
                    subtitles.setTextColor(getResources().getColor(R.color.font2));
                }
            }
        }
    );

    // Button
    popDialog.setPositiveButton("OK",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(Suad1.this, "Your setting is complete", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        }
    );
    popDialog.create();
    popDialog.show();
}

And two more questions:

*

*Can I update SeekBar when out dialog and back again?

*Can I have two Titles or more in one AlertDialog?

A: Create a separate class with method which you can use in multiple Activities for Changing TextView text,color :
public class ChangetextAttr {

public Activity context;

public ChangetextAttr(Activity context){

        this.context=context;
}

// Create an Method for Changing TextView Attributes

public void settextViewAttr(Activity activity, TextView txtView){

   txtView.setTextSize(15);
   txtView.setTextColor(activity.getResources().getColor(R.color.font1));
   //....
}

and from Any Activity you can settextViewAttr method for setting TextView Attributes :
   ChangetextAttr obj=new ChangetextAttr(Your_Activity.this);
   obj.settextViewAttr(this,any_textview_instance);

A: Hey create a(Customized textview) class which extends TextView and do whatever you want to do for the textview like changing text color and textstyle. now use this class in all your xml's . if your class name MyTextView. then your xml should be like the following...
   <urpackage.MyTextView
    android:id="@+id/text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

A: Android provides you with mechanisms already to change the appearance of widgets, via Styles and Themes.
Here is how you define a style that sets the text size and color of any view that holds text:
<style name="BigColoredText">
    <item name="android:textColor">#FF0000</item>
    <item name="android:textSize">25sp</item>
</style>

and here is how you apply it to a TextView:
<TextView style="@style/BigColoredText" .../>

Styles can only be supplied to Views at construction time, you cannot change it afterwards. However, you can programmatically change the textAppearance with is the subset of a style that refers to text attributes via:
TextView v = ...;
v.setTextAppearance(R.styles.BigColoredText);

Now, if you want all TextViews within your Activity or Application using that same style (or at least use it by default), then you need a Theme:
<style name="Theme.MyTheme" parent="@android:style/Theme">
    <item name="android:textViewStyle">@style/BigColoredText</item>
</style>

and then apply the theme to either the entire Application or one or more Activities in your manifest:
<application or activity android:theme="@style/Theme.MyTheme" .../>

Or you can change it programmatically at runtime via:
Activity activity = ...;
activity.setTheme(R.style.Theme_MyTheme);

A: To answer your questions:
1- What you need is two styles (Bold & normal) and change between the used style for Text using View.setTextAppearance. Check Android documentaion and this answer.
2- To update seekbar with a value that is unchanged from View to View, then you need to keep its progress in a shared preference for e.g. and set the progress in onResume.
3- Consider using a custom Dialog instead (you can define it in XML as you wish). Or you can include /n to have multi lines in the Title string

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 6 authorization If user is not logged in and tries to access any secure URL it should not allow him to access and must redirect to login page even if it's directly access via URL bar of browser.
I found one solution over here which resolved my problem, But only thing is whenever user tries to access authorize URL from URL bar of browser it renders index.html and nav bar components contents.

A: You should try canActivate. It will identify user loged-in and based on enable routes. Below is example. Create ts file for below.
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class UserAuthorised implements CanActivate {

   constructor(private router: Router) { }

   canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      if (your condition here of if login true) {
         return true;
      } else {
         //redirect to login page.
         this.router.navigate(['/login']);
         return false;
      }
   }
}

Add above entry into list of providers in app.module.ts file. Now this class reference you need to give in routes file.
{ path: 'dashboard', component: DashboardComponent, canActivate: [UserAuthorised] },

What above will do : If user tries to access url directly routes will return false and redirect user to login page.


text:
Q: Where to find a follower? I need a follower but can't find one anywhere.

A: Here's a list of all followers in the game.
The first follower you get access to will likely be either Sven or Faendal in Riverwood, talk to either of them to do a simple quest that will net you a starter follower.


text:
Q: Can't get an error in VB6 on Windows 7 while I can on Windows Xp I must correct some trouble on a program which is made in VB6.
When I try to print a file in XPS type and then I close the folder selection box the program give me a "Run time error 482".
So I decide to get the error with this :
On Error GoTo Error_Handler

It works on Windows XP, the run time error doesn't appear but under Windows 7 (64 bits) the program didn't respond.
I have no idea why it works on a side and not on the other
I have try to run, on Windows 7, the software in Windows XP compatibility but it doesn't work
Public Sub Print_All_Click()
Dim prntLePrinter As Printer
Dim iI As Integer

    For Each prntLePrinter In Printers
        iI = iI + 1
    Next

    On Error GoTo Error_Handler

    If (iI > 0) Then
        MousePointer = vbHourglass
        'CD Référence d'échelle pour l'imprimante
        Printer.ScaleHeight = 100
        Printer.ScaleWidth = 100
        'CD Configuration de la font
        Printer.FontName = "Arial"
        Printer.FontSize = 8
        Printer.FontBold = False
        Printer.FontItalic = False
        Printer.FontUnderline = False
        Printer.FontStrikethru = False
        Printer.FontTransparent = True
        Printer.Font.Charset = 0

        If g_nbSessions = 1 Then 'Mode NORMAL
            PrintHEADER
            PrintGeneral
            PrintExceedances
            PrintEpc
            PrintAlarms
            PrintMfdPages
            PrintEndReport

        Else 'Mode CUMUL
            PrintHEADERCumul
            PrintCUMUL
            PrintEndReportCumul
        End If

        Printer.EndDoc

        MousePointer = vbDefault

    Else
        MsgBox "No printer installed !", vbOKOnly, Frm_Main.Caption

    End If

Error_Handler:

    If MousePointer <> vbDefault Then
        MousePointer = vbDefault
    End If

End Sub

A: I find the solution.
I have to use "Clear" to explicitly clear the Err object after treatment of an error, and then when I want to close the "selection folder box" the program close it correctly on Windows XP and on Windows 7.
So if you use On Error GoTo Error_Handler
don't forget to use :
Error_Handler:

And :
Err.Clear

My code now :
Public Sub Print_All_Click()
Dim prntLePrinter As Printer
Dim iI As Integer

    For Each prntLePrinter In Printers
        iI = iI + 1
    Next

    On Error GoTo Error_Handler

    If (iI > 0) Then
        MousePointer = vbHourglass
        'CD Référence d'échelle pour l'imprimante
        Printer.ScaleHeight = 100
        Printer.ScaleWidth = 100
        'CD Configuration de la font
        Printer.FontName = "Arial"
        Printer.FontSize = 8
        Printer.FontBold = False
        Printer.FontItalic = False
        Printer.FontUnderline = False
        Printer.FontStrikethru = False
        Printer.FontTransparent = True
        Printer.Font.Charset = 0

        If g_nbSessions = 1 Then 'Mode NORMAL
            PrintHEADER
            PrintGeneral
            PrintExceedances
            PrintEpc
            PrintAlarms
            PrintMfdPages
            PrintEndReport

        Else 'Mode CUMUL
            PrintHEADERCumul
            PrintCUMUL
            PrintEndReportCumul
        End If

        Printer.EndDoc

        MousePointer = vbDefault

    Else
        MsgBox "No printer installed !", vbOKOnly, Frm_Main.Caption

    End If

Error_Handler:
Err.Clear

    If MousePointer <> vbDefault Then
        MousePointer = vbDefault
    End If

End Sub


text:
Q: Set WAS Process Definition Environment Entries using Jython? Is it possible to add custom Process Definition environment entry in a WebSphere Application Server using a jython script?
I see that the existing properties in the server.xml are assigned auto-generated IDs, is it possible to retrieve those prop without knowing their ID?
 <environment xmi:id="Property_1248356598212" name="<my_prop>" value="<my_value>" required="true"/>

WAS 6.1/i5

A: checkout this link for configuring process definition properties using jython
some snippets that might help you
server = AdminConfig.getid('/Cell:mycell/Node:mynode/Server:server1/')
processDef = AdminConfig.list('JavaProcessDef', srvid)
print AdminConfig.show(processDef, 'environment')
server = AdminConfig.getid('/Cell:mycell/Node:mynode/Server:server1/')
jvm = AdminConfig.list('JavaVirtualMachine', server)
AdminConfig.modify(ns, [['BOOTSTRAP_ADDRESS', [['host', 'myhost'],  ['port', 2810]]]])


text:
Q: Unix- Copying the same file from multiple directories into a new directory while renaming the files I have 36 subdirectories in the same directory named 10,11,12,....45 and a subdirectory logs
in each subdirectory (except for the directory logs) there is the same file called log.lammps
i was wondering if there was a way where i could copy each log.lammps file from each subdirectory 10-45 and put it in the sub directory logs while also adding the number of the directory that it originated from to the end of the filename
so i am looking for a code that copies the file log.lammps one by one from each subdirectory and every time the file gets copied into the directory logs, the filename gets changed from log.lammps to log.lammps10 if it came from the subdirectory 10 and when the file log.laamps from subdirectory 11 is copied into logs its name changes to log.lammps11 etc.
any help would be appreciated since right now i am only dealing with 30-40 files and in time i will be working with hundreds of files

A: That's easy-peasy with the magic of shell scripting.  I'm assuming you have bash available.  Create a new file in the directory that contains these subdirectories; name it something like copy_logs.sh.  Copy-paste the following text into it:
#!/bin/bash

# copy_logs.sh

# Copies all files named log.lammps from all subdirectories of this
# directory, except logs/, into subdirectory logs/, while appending the name
# of the originating directory.  For example, if this directory includes
# subdirectories 1/, 2/, foo/, and logs/, and each of those directories
# (except for logs/) contains a file named log.lammps, then after the
# execution of this script, the new file log.lammps.1, log.lammps.2, and
# log.lammps.foo will have been added to logs/.  NOTE: any existing files
# with those names in will be overwritten.

DIRNAMES=$( find . -type d | grep -v logs | sed 's/\.//g' | sed 's/\///g' | sort )

for dirname in $( echo $DIRNAMES )
do
    cp -f $dirname/foo.txt logs/foo$dirname
    echo "Copied file $dirname/foo.txt to logs/foo.$dirname"
done

See the script's comments for what it does.  After you've saved the file, you need to make it executable by commanding chmod a+x copy_logs.sh on the command line.  After this, you can execute it by typing ./copy_logs.sh on the command line while your working directory is the directory that contains the script and the subdirectories. If you add that directory to your $PATH variable, you can command copy_logs.sh no matter what your working directory is.
(I tested the script with GNU bash v4.2.24, so it should work.)
For more on bash shell scripting, see any number of books or internet sites; you might start with the Advanced Bash-Scripting Guide.

A: Something along this line should work:
for f in [0-9][0-9]/log.lammps; do
  d=$(dirname ${f})
  b=$(basename ${f})
  cp ${f} logs/${b}.${d}
done


text:
Q: colors in plotly - 'range' not meaningful for factors anybody can help? trying to create plotly scatter chart where I can change color of selected markers. I checked the dataframe source and indt$active is a num, not factor, yet plotly chart interprets it as a factor
see the code, everything is fine until i set color = ~active. I tried using inside the reactive indt$active <- as.numeric(as.character( indt$active )) but it still does nothing. I am struggling to find what factor the chart fails on. It fails to load (you can comment out the color=~active to see without the error). To select values, you need to draw a box
library(plotly)
library(shiny)
library(dplyr)
library(tidyr)

tms<-format(seq(as.POSIXct("2013-01-01 00:00:00", tz="GMT"),
                length.out=48, by='30 min'), '%H:%M')
dts<-c( "Day Before BH","BH","Sunday","Saturday","Friday","Thursday","Wednesday","Tuesday", "Monday" )

indt <- as.data.frame(matrix( c(0), nrow=9,  ncol=48, byrow = TRUE))
indt<-cbind(dts,indt)

colnames(indt) <- c("dt",tms)

indt<-gather(indt,tm,active,-dt)

pal <- c("red", "blue")
pal <- setNames(pal, c(0, 1))

ui <- fluidPage(
  plotlyOutput("plot")

)

server <- function(input, output, session) {

  ind<-reactive({
    d <- event_data("plotly_selected")
    indt[d$pointNumber+1,3]<-1
    indt<<-indt
    return(indt)
  })

  output$plot <- renderPlotly({

    f1 <- list(size = 8)

    yform <- list(title = "",
                  categoryorder = "array",
                  categoryarray = dts
                  ,tickfont = f1)

    plot_ly(ind()
            , x = ~tm, y = ~dt, mode = "markers", type = "scatter",
            color = ~active,
            colors = pal,
            marker = list(size = 20)

    ) %>%
      layout(dragmode = "select") %>%
      layout(xaxis = list(title = "", tickfont = f1),
             yaxis = yform)
  })
}

shinyApp(ui, server)

A: In your plot_ly function try using color = ~as.character(active)instead of color = ~active


text:
Q: Familiarising with Exception Handling I can't figure out why my getHours() is catching InputMismatchException when I have only thrown InvalidHrExcep to the method itself. Can anyone enlighten me?
public static void main (String [] args)
{
    do
    {
        try
        {
            getHours();
            getAmPm();
            accept = true;
        }
        catch(InvalidHrExcep h)
        {
            System.out.println (h);
            accept = false;
            console.nextLine();
        }
        catch (InputMismatchException e)
        {
            System.out.println (e);
            System.out.println("Input must be AM or PM.");
            accept = false;
            console.nextLine();
        }
    }while(accept == false);
}

My method for getHours()
public static int getHours() throws InvalidHrExcep
{
    System.out.print ("Enter hours: ");
    int hour = console.nextInt();

    if(hour > 0 && hour <= 12)
    {
        return hour;
    }
    else
    {
        throw new InvalidHrExcep();
    }
}

A: console.nextInt() can definitely throw InputMismatchException exception, and your getHours method doesn't have to specify that exception in a throws clause, since it's an unchecked exception.
If you don't want getHours() to throw that exception, you should put console.nextInt() in a try block and catch it.


text:
Q: How can I put Net::SSH into a model method? I've got a rails model Instance, that represents an EC2 instance.
At the moment, every time I have a method that must SSH it, I have to set up Net::SSH everywhere I want to do it, which is a lot.
for example:
Net::SSH.start(ip, 'ubuntu', keys: "mykey.pem" ) do |ssh|
  ssh.exec "sudo chmod +x /tmp/provision.sh"
end

Is there a way I can factor the 'ssh' set up bit into the Instance model?

A: How about encapsulating it into a private method, and yielding the connenction to the calling place.
class Instance

  def chmod
    start do |ssh|
      ssh.exec "sudo chmod +x /tmp/provision.sh"
      # other operations on ssh
    end
  end

  private

    def start
      Net::SSH.start(ip, 'ubuntu', keys: "mykey.pem" ) do |ssh|
        yield ssh
      end
    end
end


text:
Q: Info on Apache's code 302, where does it redirect to? I'm running a LAMP system (on a Pi) and I get a lot of mischievous requests which seem to result in a 302 status code, like:

140.143.16.158 - - [06/Mar/2020:18:32:32 +0100] "GET /TP/public/index.php HTTP/1.1" 302 540 "-" "Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6)"

As I understand it, my Apache webserver indicates a temporary redirect. But where does it redirect to? I just don't know how my webserver handles this (correctly ??) and I don't know where or what to check .. Can somebody explain?
Whatever is needed to solve this question will be provided. For instance, here's my  000-default.conf (comments left out):
<VirtualHost *:80>

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        RewriteEngine On
        RewriteRule .*   https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

</VirtualHost>

Any help will be much appreciated!

A: Never mind, I think I figured it out .. For those interested:
The rewrite rule was put in place as a permanent redirect from http to https, so I was expecting a 301 code (permanent redirect). But it turns out when only using [R], Apache issues a 302 (temporary redirect) not a 301.
It was the 'temporary' part that confused me. I changed the rewriterule flags to [R=301,L] (BTW, L stands for last rule to process). I'll be monitoring my access log to see if I'm right.


text:
Q: How do conflicting CSS rules affect performance? I'm cleaning up some old CSS and I'm not sure I've commented out or removed all the conflicting rules. The project uses a lot of CPU for rendering, which is why I ask about what seems like a relatively small optimization.
For example, if I had CSS like this, does the browser spend time on the rule color: red ?

span {
  color: red;
  color: black;
}

Is  overriding within the same block (above) handled differently than the below:
span {
  color: red;
}
span {
  color: black;
}

Is there a good resource I can refer to for exactly how rules are processed from a CPU/GPU standpoint? There's plenty of info on the high level of how CSS rules are applied, but I'm wondering how much of a difference conflicting rules make. In my case, conflicting rules I may have overlooked are generally much more complicated than the simple example I gave above, involving multiple selectors, gradients, shadows, etc.

A: Short: yes, it spend some time more to composition than paint (it will merge to one computed version which is visible in Chrome DevTool)
Long: It is more about size of CSS that you push on 3G devices rather than composition. Every bites mater as you push unnecessary code to everyone.
Main rule: Optimize that and other simple task by PostCSS, locally or in pipeline :) Or even by online processor.
Best: Write better code so less work afterwards :D


text:
Q: Pandas: dataframe is highly fragmented. this is usually the result of calling `frame.insert` many times, which has poor performance I have a pandas data frame with 111 columns and 75k rows. I want to add 6 columns based on other columns' calculations:
df['col1_4'] = df['col1_1'] - df['col1_2'] - df['col1_3']
df['col2_4'] = df['col2_1'] - df['col2_2'] - df['col2_3']
df['col3_4'] = df['col3_1'] - df['col3_2'] - df['col3_3']
df['col4_4'] = df['col4_1'] - df['col4_2'] - df['col4_3']
df['col5_4'] = df['col5_1'] - df['col5_2'] - df['col5_3']
df['col6_4'] = df['col6_1'] - df['col6_2'] - df['col6_3']

I get the warning:

PerformanceWarning: DataFrame is highly fragmented.  This is usually the result of calling frame.insert many times, which has poor performance.  Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use newframe = frame.copy()

First of all, should I be wary of a 'fragmented' data frame? what does it mean and will that cause problems using the data frame going forward? How does copying the data frame make it 'de-fragmented'?
I rewrote the same operations like this:
col1 = df['col1_1'] - df['col1_2'] - df['col1_3']
col2 = df['col2_1'] - df['col2_2'] - df['col2_3']
col3 = df['col3_1'] - df['col3_2'] - df['col3_3']
col4 = df['col4_1'] - df['col4_2'] - df['col4_3']
col5 = df['col5_1'] - df['col5_2'] - df['col5_3']
col6 = df['col6_1'] - df['col6_2'] - df['col6_3']

df = pd.concat([df, col1, col2, col3, col4, col5, col6], axis=1])

and didn't get any warning. But I still don't understand the warning or why using this method helps. I've essentially just added one more step in between.

A: As I understand it, there is nothing "wrong" with the way you did it originally, it is more a matter of performance.  The warning serves to tell you that there is a better way to do it.  As the notebook screenshot on this page" https://github.com/pandas-dev/pandas/issues/42477 demonstrates, using pd.concat can be 10x faster or more.


text:
Q: html5 Audio - pitch bend without web audio API I've been looking online for an alternative or polyfill to the web audio API. Specifically i'm looking for a way to pitch bend Audio and i'm thrown off by the Web Audio API as it's not supported in IE. There's a lot of other web audio api features i'd love to use but the pitch bend one is critical so not sure if there is a library out there that can achieve this with html5 audio or if it's even possible to?
This leads me to ask also if anyone would know if Microsoft are planning on releasing support for the Web Audio API for IE11 anytime?
Cheers

A: AFAIK, IE will not get support for WebAudio.  But Edge supports WebAudio.


text:
Q: Working C# Example: Writing & Reading NTFS Alternate Data Stream Under Win7 64 bit I'd like to be able to use an alternate data stream to store some synchronization information for files that are referenced in a database application I'm building.
However, every approach I've found on the web has failed in one way or another. Not being experienced at Win32 API programming I'm not sure why the failures are occurring. In some cases the method calls appear to succeed, only no alternate stream is created (i.e., I can't later read from the alternate file, nor can AlternateStreamViewer see it). In other cases the write succeeds, but the read fails because calling CreateFile() results in an invalid SafeFileHandle.
At this point I'd just like to find some working code. Or be advised that "ya can't get there from here". In which case I'll use another, less attractive option (e.g., encode the sync/reference information in the filename itself, and hope no one ever changes a file name).

I understand the request for what approaches I tried. But there were quite a few (I spent hours on this), and I was really interested in learning about offerings I hadn't tried.
However, you're right that it would've helped, as it turns out I was using one of the approaches -- the Trinet one referred to below -- incorrectly. I think the problem was that I hadn't yet created the "base" file for which I was trying to save an alternate stream.
Here are links to the code bases I tried:

*

*St. Croix Skipper

*DevDump

*Trinet

A: I've had success on Windows 7 x64 using this library:
https://github.com/hubkey/Trinet.Core.IO.Ntfs
I can't find my old code, and the documentation page I have bookmarked is down at the moment, so I'll try to post some code when it's back up if you're still having problems.
Edit:
Apparently it's as simple as:
using Trinet.Core.IO.Ntfs;

var fileInfo = new FileInfo(@"C:\path\to\file.dat");
if (AlternateDataStreamExists("MyStreamName"))
{
    var alternateStream = fileInfo.GetAlternateDataStream("MyStreamName").OpenRead();
}
else
{
    var alternateStream = fileInfo.GetAlternateDataStream("MyStreamName").OpenWrite();
}

A: You can also try my Platform.VirtualFileSystem library which supports listing, reading and writing NTFS alternate data streams in just a few lines of code.
https://github.com/platformdotnet/Platform.VirtualFileSystem/wiki
https://github.com/platformdotnet/Platform.VirtualFileSystem/wiki/Alternate-Data-Streams


text:
Q: Hidden Field value returns null when i access it from javascript function on the same page what i wrote in my aspx form ::
     <%@ Page Title="Sector Composition" Language="C#" MasterPageFile="~/UIPages/ApexM.Master"
     AutoEventWireup="true" CodeFile="Sector_Composition.aspx.cs" Inherits="Anonymous_Sector_Composition" %>

   <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">

    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="cphContent" runat="Server">

        <asp:HiddenField ID="JSON_DataTable_DataHolder"  runat="server" />

  </asp:Content>

In my Code behind :::
   protected void Page_Load(object sender, EventArgs e)
  {

    psp_Chart_Composition_MktCapTableAdapter composition = new psp_Chart_Composition_MktCapTableAdapter();

    DataTable compositions = composition.GetData();
    JSON_Class Object_JSON_Class = new JSON_Class();
    ///////// JSON String with Rows And Cols////////////////////////////
    JSON_DataTable_DataHolder.Value = Object_JSON_Class.JSON_DataTable(compositions);

   }

what is the problem with the code ?? i could not get the value of the hidden field in the javascript function. i have tried with function call window.onload= OnPageLoad; and also of a button onclientclick event.

A: Change this line
var oJSON_DataTable_DataHolder = document.getElementById("JSON_DataTable_DataHolder");

to
var oJSON_DataTable_DataHolder = document.getElementById("<%= JSON_DataTable_DataHolder.ClientID %>");

A: You may change the code:
var oJSON_DataTable_DataHolder = document.getElementById("JSON_DataTable_DataHolder");

to:
var oJSON_DataTable_DataHolder = document.getElementById("ctl00_cphContent_JSON_DataTable_DataHolder");


text:
Q: How can i tell if a radiobutton is checked in action ? (MVC) I would really like to be able to do this
if myRB.Checked = true then
    return redirecttorout("SomeRoute")
else
    someother route

i am used to web forms, in which i could do this in the code behind

A: Mvc like normal html post returns values by an input's name not id.  In a radio button collection all radio buttons have the same name.  So what you get back is the name of the radio button with the value of the selected radio button
The code ends up looking like

if(model.radio=="va1")
   {
   ....
  }

A: In the action that the form posts to you need to create a string var that will hold the value.
public ActionResult GetRadioButtonValue(string RadioButtonVal)
{

The Name of the radio buttons all need to match on the view, but the value will be what is sent to the Action.  Ensure that the string as seen above matches the Name of the radio buttons.  It would also be a good idea to check that string for is null or empty.
string.IsNullOrEmpty(RadioButtonVal)

A: View
@model MvcApplication2.Models.CountryModel
@using (Html.BeginForm())
{
            @Html.RadioButton("Gender", "Male" new { @checked = "checked" }) Male
            @Html.RadioButton("Gender", "Female")Female
            <input type="submit" text="submit"/>
}

MODEL
   public class CountryModel
    {
        public string Gender{ get; set; }

    }

CONTROLLER
public ActionResult Index()
{
    return View();
}
[HttpPost]
public ActionResult Index(CountryModel model)
{
    //for radio button
    CountryModel dd = new CountryModel();
    string date1 = model.RDB;
    return View(model);
}


text:
Q: How to add a search form to Magento's breadcrumbs/anywhere In Magento, I'm trying to implement a search box to the right of breadcrumbs for easy searching from any internal page.
I have seen tutorials for adding a (top) search form to the header, but breadcrumbs aren't in the header...
Some things I have tried include adding echo $this->getChildHtml('newSearch'); where I would like breadcrumbs to show up, having a newSearch.phtml in my theme's categorysearch folder, and adding             <block type="core/template" name="new.search" as="newSearch" template="catalogsearch/newSearch.phtml" /> to my page.xml to attempt to register it.
Good documentation for Magento theming is very hard to come by, and any help is greatly appreciated, even if it's a book or set of docs. :)

A: I think you had it right:

*

*Copy the mini search .phtml file (to your theme or base/default), giving it a new name

*Adding the block declaration to your page.xml (or theme/layout/local.xml)

*Depending on where the block is, adding a 'getChildHtml' in the page template

However, that 'newSearch' name is camel case which is not what is generally done for .phtml files (they are all lower case in the standard install).
'newSearch' expands out to 'new/search' when un-camelCased. Try using a different name without camelCase, e.g. just 'search.phtml'. That won't randomly become something else.


text:
Q: How to avoid type annotations with literal numbers and types based on them? In Typed Racket, if I have the following type and function:
(define-type A (U 'one 'two))
(define (f [a : A]) : A
  a)

Then the function call (f 'one) typechecks. However, if I use literal numbers as components of a union type like this:
(define-type B (U 1 2))
(define (g [b : B]) : B
  b)

Then (g 2) fails to typecheck with the type error:
Type Checker: type mismatch
  expected: B
  given: Positive-Byte in: 2

However, (g 1) typechecks because 1 has it's own type, One.
I can solve the problem with (g (ann 2 B)) (or (g #{2 :: B})), but this is awkward and cumbersome. Is this a fundamental limit of Typed Racket's handling of numeric types, or is there a way to make the explicit type annotation unnecessary?


text:
Q: Is any artificial degree of freedom caused by the electrical current concept? The electrical current concept multiplies together charge distribution and charge velocity distribution. It thus transforms two degrees of freedom into one. Combining two degrees of freedom into one can later in derivations lead to an artificial degree of freedom.  Is any such found for electrical current?

A: The only known freedom is gauge freedom
$$
\begin{cases}
\mathbf {A} \rightarrow \mathbf {A} +\nabla \psi \\
\varphi \rightarrow \varphi - {\frac {\partial {\psi }}{\partial t}}
\end{cases}
$$

A: Maxwell's equations are gauge-independent, meaning that they are unchanged under a 4D, relativistic gauge transformation. Dynamics under Maxwell's equations also conserves charge, meaning that the net change in charge of an area is equal to the net amount of charge flowing into the area. These two concepts are equivalent to one another, via the process described on Wikipedia's "Gauge theory", generalizing the Noether concept of continuous symmetries leading to conserved quantities.

A: Charge and current form a Lorentz four vector $j$. Current conservation reduces the degrees of freedom of $j$. When the field of $j$ is described by a four vector potential $A$, this is a loose fit: gauge freedom.


text:
Q: Sending single emails works, but sending to the same email in a distribution list is bounced I'm running an Exchange 2003 server on a Telstra Business internet connection (in Australia).
I'm routing emails through the SMTP connecter, using the host smtp.telstrabusiness.com
When users send single emails to a single recipient, the emails are sent correctly.
However, when users send emails to a distribution list, they bounce back with:
The message could not be delivered because the recipient's destination email system is unknown or invalid. Please check the address and try again, or contact your system administrator to verify connectivity to the email system of the recipient.
One of the people in the list was able to recieve a single email from us just a few minutes afterwards, but did not recieve any of the email that should have come from the distribution list.
Is there a way I can throttle the number of messages that Exchange will send at a time, so as not to appear as spam to Telstra?

A: It sounds like it's rejecting based on the "to" address ("destination email") rather than rejecting on the basis of volume. When you send via the list, what's the "to" address on the email? Is this one of those list managers that sends "to" the list and BCCs the actual recipients? If so, try replicating that scenario with a single email and see what happens. I'm sure I don't have to tell you that SMTP server administrators have to implement a variety of limitations to minimize spamming, one of which is sometimes to only allow messages to be sent via that SMTP server that are to one of the addresses it serves...
The other thing to check is whether SMTP AUTH is working correctly. Typically if you're correctly authenticating, the other limits are not enforced; but if you don't, they come into play, which can mask the real problem.

A: Are these from an internal distribution list or an external distribution list?  I'm kind of thinking that your exchange server isn't actually sending any emails at all since you said you are using the smtp connector.  IF it's going straight to telstra (instead of hitting your exchange smtp server first) then they won't have any idea what the email addresses are.
I think you might want to us the smtp smarthost instead of the connector.


text:
Q: Multiple references and bibtex files I'd like to create a single latex file where I can add many bibtex files, (or only one but that has different sections.)
So for example, I'd ideally just want a document that looks like this:
Literature Review 1
[1] Author1, "MCMC sampling", 2015
[2] Author2, "Stochastic Gradient Descent", 2017

Literature Review 2
[1] AuthorA, "SIFT key point descriptors", 2018
[2] AuthorB, "HOG for pedestrian detection", 2012

Instead of how it usually looks like whenever I use references:
References
[1] Author1, "MCMC sampling", 2015
[2] Author2, "Stochastic Gradient Descent", 2017
[3] AuthorA, "SIFT key point descriptors", 2018
[4] AuthorB, "HOG for pedestrian detection", 2012

So far this has been my strategy:
\usepackage{etoolbox}

\patchcmd{\ComputerVision}{\chapter*}{\section*}{}{}
\patchcmd{\MachineLearning}{\chapter*}{\section*}{}{}

\begin{document}
\input{ComputerVision}
\input{MachineLearning}
\end{document}

ComputerVision.tex is the following file:
\renewcommand\refname{Computer Vision}

{\small
\bibliographystyle{ieee}
\bibliography{egbib_CV}
}

MachineLearning.tex is the following file:
\renewcommand\refname{Machine Learning}

{\small
\bibliographystyle{ieee}
\bibliography{egbib_ML}
}

egbib_ML.bib is:
@article{hash1,
  title={MCMC sampling},
  author={Author1},
  year={2015}
}

@article{hash2,
  title={Stochastic Gradient Descent},
  author={Author2},
  year={2017}
}

egbib_CV.bib is:
@article{hashA,
  title={SIFT key point detector},
  author={AuthorA},
  year={2018}
}

@article{hashB,
  title={HOG for pedestrian detection},
  author={AuthorB},
  year={2012}
}

The output that I get instead just looks like this (where everything repeats itself...):
Literature Review 1
[1] Author1, "MCMC sampling", 2015
[2] Author2, "Stochastic Gradient Descent", 2017
[3] AuthorA, "SIFT key point descriptors", 2018
[4] AuthorB, "HOG for pedestrian detection", 2012

Literature Review 2
[1] Author1, "MCMC sampling", 2015
[2] Author2, "Stochastic Gradient Descent", 2017
[3] AuthorA, "SIFT key point descriptors", 2018
[4] AuthorB, "HOG for pedestrian detection", 2012


text:
Q: ¿Cómo puedo agregar un redirectview a esta función? Lo que hace mi codigo es mostrar una lista con todos los usuarios que hay en mi Aplicación.
Necesito agregar una redirección al inicio-sesion.html en caso de que no tenga el atributo "userAuth".No se como agregarlo sin que me tire error la aplicación
@Controller
public class UserController {
@GetMapping("/usuarios")
public String list(Model model, HttpSession session ) {
    try {
        IDaoUsuario daoUsuario = new MysqlDaoUsuario();
        ArrayList<Usuario> usuarios = daoUsuario.getAll();
        var userAuth = session.getAttribute("userAuth");
        if (userAuth == null){
            //aca iria la redirección
        }
        model.addAttribute("usuarios", usuarios);
        return "usuarios/list";

    } catch (SQLException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}


text:
Q: How to avoid incrementing version field with mongo document if there were no changes? Assuming the following method that just fetch the data from the MongoDB and then save it immediately, without any changes:
@Transactional
public void doNothing() {
  MyDocument doc = repository.findById(1L).orElse(null);
  repository.save(doc);
}

MyDocument contains a field with the @Version annotation.After calling the previous method, I have the version incremented.
Is there any way to stop doing that?
I'm asking this because, e.g., in spring-data-jpa the behaviour is different (because of JPA-provider's dirty check mechanism).


text:
Q: How to use a different version of Java on the command line OK I have 2 different version of Java install on my machine (CentOS 5), the system defaults to 1.5.0_14 but I need to run a command on the command line with the newer version of Java. How can I pass the newer version in the command line?
Sorry this is such a n00b question but I googled and didn't find anything, thanks.

A: Just use the full pathname for your java executable, rather than allowing the OS to pick one based on your PATH.

A: Use the absolute path to the java executable:
/opt/java-1.4/bin/java

A: You could make a link to the file:
ln myJava1 <java version you want>
ln myJava2 <java version you want>

and then when you want one or the other, type the appropriate link.
Or if you want a standard java and just have the other for one offs, you could do:
ln theJava <myJava1 or myJava2>

and then just use theJava (or whatever you want to call it


text:
Q: SSRS lookup missing dataset I have a dataset which looks like this
Name              Spend
"First Aid"       2
"Healing Arts"    0
"Surgeon"         NULL

I then have three separate textboxes which will be filled with the value of the column which matches the name.
Example: show value of spend in textbox if value of name equals First Aid
for this I've made following expression
=Lookup(Fields!skill_name.Value, "First Aid", Fields!skill_spend.Value, "Skills")

My problem is however that I get an error saying that skill_name is missing its dataset, which doesn't make sense to me as it is informed in the end of the expression (skills)

A: I think you may be misunderstanding the purpose of Lookup and how it is used.  The purpose of the Lookup function is akin to a JOIN in SQL in some ways.  Basically, you would have two datasets that each have a matching field with the other.  In that scenario, the expression would match on the skill_name field and lookup the skill_spend value and the expression would look something like the following.
=Lookup(Fields!skill_name.Value, Fields!skill_name.Value, Fields!skill_spend.Value, "Skills")

As the documentation shows, the first reference to skill_name is the field you are referencing from the current dataset.  The second reference is to the dataset from which you are attempting to look up a value.  The third expression is the field you are looking up and the dataset should be the one you are attempting to look up a value from, not the current dataset scope.

Lookup(source_expression, destination_expression, result_expression, dataset)

From the best I can tell, you have a single dataset but separate textboxes that need the correct spend value.  I think the following expression will work.
= IIF(Fields!skill_name.Value = "First Aid", Fields!skill_spend.Value, Nothing)

This expression should get the skill_spend value associated with the row "First Aid" only and leave the textbox blank otherwise.


text:
Q: Setting 100% Height on an Absolutely Positioned Column I have a design using some bootstrap styling which has a white column on the right. The height should be 100%, but it isn't rendering at 100%.  It renders at 100% of the initial screen height, but when you scroll down it's no longer white.
I've looked at several other CSS solutions on this site. I've tried making all parent elements 100% height.  I've tried making it a flexbox column. I've tried putting "position: relative;" in the body.  Nothing has worked yet.  I'd prefer not to use JS to achieve this.
Simplified version of my HTML:

This is the main content area

The CSS:
body,html {
    height: 100%;
    background-color: #aaa;
}
body {
    position: relative;
}
.main  {
        display: inline-block;
}

.container {
    height: 100%;
}
.right {
        display: inline-flex;
        flex-direction: column;
        background-color: #fff;
        width: 350px;
        height: 100%;
        min-height: 100%;
        border: 1px solid #E1E6E9;
        margin-right: 100px;
        position: absolute;
        right: 100px;
}
.content {
    height: 300px;
    min-height: 300px;
    margin: 10px 10px;
    background-color: #ccc;
    border: 1px solid #000;
}

A: Change your .right class to have height: auto;
It will size itself to fit with its content.
.right {
        display: inline-flex;
        flex-direction: column;
        background-color: #fff;
        width: 350px;
        height: auto;
        min-height: 100%;
        border: 1px solid #E1E6E9;
        margin-right: 100px;
        position: absolute;
        right: 100px;
}

http://codepen.io/smlariviere/pen/WrWgxQ


text:
Q: Avoid having to select "Include Network Devices" every time when scanning in Preview I set up a wireless HP Printer for my mother, prints and scans just fine. The annoying thing is that every single time we try to scan in Preview, we first have to do the following:

*

*Select File > Import from Scanner > Include Networked Devices

*Select File > Import from Scanner > Printer name

Is there a way to avoid having to do that first step every time? Didn't see a preference in Preview and obviously we aren't going to keep it running all of the time. :)

A: That answer is very well done, but an even better option is to use "image capture".

A: tell application "Preview"
    activate
end tell

tell application "System Events"
    tell process "Preview"
        tell menu bar 1
            tell menu bar item "File"
                tell menu "File"
                    tell menu item "Import from Scanner"
                        tell menu "Import from Scanner"
                            click menu item "Include Networked Devices"
                            -- added a delay because the list of networked printers doesn't appear immediately. AH 11/21/11
                            repeat until menu item "Printer name" exists
                            end repeat
                            click menu item "Printer name"
                        end tell
                    end tell
                end tell
            end tell
        end tell
    end tell
end tell

To use this, copy the script, open the the Script Editor application under /Applications/AppleScript/, and paste into a new script. I am going to guess that click menu item "Printer name" will have to be changed as I don't think the menu item really says "Printer name", I'm guessing it says something like "HP OfficeJet 6500". Make sure that all menu names match.
Save the script as either an application, which can be launched from the dock, or a script, which can be run from the AppleScript menu bar item.
Note, I believe that you must enable "Enable access for assistive devices" in the "Universal Access" preference pane of System Preferences for this to work:


text:
Q: How to check for collision in if-statement I have method to buy a tile and i need to check if it collides with another tile owned by player.
I know about func OnCollisionEnter and etc but i think i need other way and check it in if-statement.
void BuyTile()
{
    if (_selected.tag == "Free") // if no owners
    {
        _selected.GetComponent<Renderer>().material.color = Color.green;
        _selected.tag = "Player1";
        pc.CountTiles();
    }
    _selected = null;
}

i need smth like that if (_selected.tag == "Free" && _selected.CollideWithGO.tag == "Player1") but idk how to do that using no func

A: Keep track of the collision:
public class CollisionTracker : MonoBehaviour
{
    Collision collision;

    void Update()
    {
        if (collision != null && collision.gameObject.tag == "Player")
        {
            Debug.Log("Colliding with Player!");
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        this.collision = collision;
    }

    void OnCollisionExit(Collision collision)
    {
        this.collision = null;
    }
}

A: p.s: solve it
bool Neighboor(GameObject centerTarget)
{
    bool GotTrue = false;
    Collider[] hitColliders = Physics.OverlapSphere(centerTarget.transform.position, 1f);
    for (int i = 0; i<hitColliders.Length; i++)
    {
        if(hitColliders[i].tag == "Player1")
        {
            GotTrue = true;
            break;
        }
    }
    if (GotTrue)
        return true;
    else return false;
}


text:
Q: Meteor path length when using electrify When I package an app for windows using electrify, the npm dependencies have path lengths that exceed the 260 character limit imposed by Windows.
I've tried using "flatten-packages", but still no success.
How can I reduce the path lengths without breaking the app? At this point any solution is welcome - even a manual one.

A: I found the answer thanks to MasterAM - you need to update both the electrify dependencies and meteor's npm. For posterity, these are the required steps:
1) meteor npm install -g npm@3 (deep dependency problem has been fixed with npm v 3)
2) meteor remove arboleya:electrify
3) npm install -g electrify-updated-test (this is an unofficial updated version of electrify with new dependencies)
4) remove any node_modules folder from your project + .electrify folder
5) meteor update (this updates to 1.3.5.1 - the deep dependency problem has been fixed since 1.3.4)
6) electrify package


text:
Q: Как убрать поля с e-mail, именем пользователя и т. д.?
Пользуюсь django-threadedcomments, реализация простая как пять копеек, но у меня есть своя система аккаунтов, и хотелось бы привязать комментарии к ней. Но для начала, мне надо убрать вот эти вот чудесные поля, или чтоб они сами заполнялись за пользователя, но были скрыты от него. Пользуюсь модулем threadedcomments из-за того, что нигде нормально не объясняют, как реализовать многоуровневые комментарии. В документации никаких наводок даже близко не нашел. Главное - помогите узнать, где находится код, который мне нужен, я дальше сам все сделаю
UPD: ещё порылся в доках, там говорят, что каким-то образом можно оверрайднуть их шаблоны, но не написано где они

A: Удалите из формы те поля которые не хотите получать установив null=True blank=True. Затем переопределите форму в представлениях:
views.py
if form.is_valid():
    comment = form.save(commit=False)
    comment.username = request.user.username
    comment.email = request.user.email # Если почта используется


text:
Q: "cd -" equivalent on Windows?
Possible Duplicate:
Navigate to previous directory in windows command prompt

Is there an equivalent of Linux's cd - (change to previous directory) in Windows?

A: popd, which is to be used alongside pushd.

A: See Navigate to previous directory in windows command prompt

A: Yeah, it's identical, see here:

cd is frequently included built directly into the command line interpreter. This is the case in most of the Unix shells (Bourne shell, tcsh, bash, etc.), cmd.exe and Windows PowerShell on Windows and COMMAND.COM on DOS.


text:
Q: Synchronize arrays php Help me please but just started to learn php and already here is an obscure task, arrays in php have a slightly different structure than in other programming languages so I can not fully understand what and how to do in a task.
Create 2 Arrays:
cities (3), districts
areas, streets, houses.
Display the data with the synchronization table


text:
Q: c# - Add to string[] member I have a List<string[]> called lst:
[0] "ABC" "DEF" "GHI"
[1] "JKL" "MNO" "PQR"
[2] etc, etc...

How do I add another string to the end of each lst member?
string s = "EndOfBlock";
[0] "ABC" "DEF" "GHI" "EndOfBlock"
[1] "JKL" "MNO" "PQR" "EndOfBlock"
[2] etc, etc...

Thank you.

A: Should be something like this:
var lst = new List<string[]>();
lst.Add(new string[] { "ABC", "DEF" });
lst.Add(new string[] { "GHI", "JKL" });

foreach (var item in lst)
{
    Console.WriteLine(item.Length);
}

for (int i = 0; i < lst.Count; ++i)
{
    var array = lst[i];
    Array.Resize(ref array, array.Length + 1);
    array[array.Length - 1] = "EndOfBlock";
    lst[i] = array;
}

foreach (var item in lst)
{
    Console.WriteLine(item.Length);
}

Array.Resize Reference

A: As the commenters have noted, it sounds like you really want a List<List<string>>. But if you want to stick with a List<string[]>, here's how I'd expand each array.
List<string[]> list = ...
for(int i = 0; i < list.Count; i++)
{
    // copy to a local variable (list[i] is a property, which can't be passed 'ref')
    string[] array = list[i];

    // resize the local variable. (this creates a new string[] object)
    Array.Resize(ref array, array.Length + 1);
    array[array.Length - 1] = "EndOfBlock";

    // put the new object back in the list, replacing the old smaller one.
    list[i] = array;
}

A: I would also recommand you use a List<List<string>>:
List<List<string>> lst = new List<List<string>>();
lst.ForEach(i=>i.Add("EndOfBlock"));

A: If you really want to do this with a IList<string[]> you can do this,
var lst = new List<string[]>
{
    { "ABC", "DEF", "GHI" },
    { "JKL", "MNO", "PQR" },
    ...
}

var blockEnd = new string[] { "EndOfBlock" };

lst = lst.Select(a =>
    (a.Select(s => s).Concat(blockEnd))
    .ToArray()).ToList();

This would be much "nicer" if lst was a Ilist<Ilist<string>>.
var lst = new List<List<string>>
{
    { "ABC", "DEF", "GHI" },
    { "JKL", "MNO", "PQR" },
    ...
}

foreach(var row in lst)
{
   row.Add("EndOfBlock");
}

A: If you want to keep your list of arrays, you can do this:
List<string[]> lst = new List<string[]); //Where this is the poplated list instead of new;
for (ini i = 0; i < lst.Count; i++)
{
   List<string> tmpList = new List<string>(lst[i]);
   tmpList.Add("EndOfBlock");
   lst[i] = tmpList.ToArray();
}


text:
Q: Excel и массив Python
        df = pd.read_excel(r'E:\PYTHON\exelbot\Образец_бот.xlsx', dtype={'Долг': 'str','Телефон1': 'str'})

        # print(df)
        a123 = df.loc[df['Телефон1'] == str(a)] # str(a) в данном случае это номер телефона 505808904

        print(a123.values) #этот принт выдает [[1 3 '505808904' nan nan 'АА1580ТЕ' nan nan nan '450']]
        a222 = str(a123.values)
        print(a222) # [[1 3 '505808904' nan nan 'АА1580ТЕ' nan nan nan '450']]
        print(len(a222)) #56
        if len(a222) == 2:
            bot.send_message(m.chat.id,'Такого номера нет')
            print('rabotaet')
        else:
            bot.send_message(m.chat.id, 'Долг : ' + a222[9])#выдает цифру 5из номера тел(505808904)

А проблемма заключается в том что: скрипт выдает цифру номера телефона, и почему то скобки массива работают не правильно (при индексе [ 1 ] -выводит [)
Тоесть переменная a222 вроде бы и отображается как масив,но возможно из-за модуля Panda ,не является массивом
Подскажите ,как можно достать поле долг (450) и поместить его в переменную abc например.

A: Попробуйте так:
abc = df.loc[df['Телефон1'] == str(a)]['Долг'].values[0]


text:
Q: Embedding HTTP content into HTTPS site We have a unified portal which links multiple services through a jQuery tab based interface making use of iframes to display content from different services. Our portal runs on a secure server with HTTPS/SSL. While most of our external services are HTTPS, two of them aren't. Obviously we are aware of the issues with mixed content and we didn't like the idea of having non-https sites within the portal, but we didn't have a choice. Everything was ok until a few days ago when Google updated chrome to version 30, which now silently blocks mixed content.This has created a great number of problems for us. We contacted the external services  and asked them if they could upgrade their services to HTTPS and one of them has come back saying they have no plans to do so for the next 2 years.
Obviously this is a problem. We tried getting around the problem by getting this service to open into a new browser window, but this is a rather inelegant workaround which I would like to get rid of, if at all possible. Is there any way that I can use AJAX or PHP to prefetch the page in question and then display it within the portal iframe without Chrome blocking it?
I would be very grateful for any advice at all. I do understand how bad an idea it is to mix secure content with non secure content, but I have no choice in the matter as my manager is adamant that the service have to be a part of the portal.
Thanks in advance.
Regards
Alex

A: A somewhat simple solution would be to use a reverse proxy. You can configure Apache quite easily to take an HTTPS connection, fetch the requested content from another URL and return it. See mod_proxy. The problem is that the browser will necessarily see a different URL/domain on its part (your reverse proxy), which may or may not cause problems with cookies or hardcoded links.


text:
Q: mat-expansion-panel-header title alignment issue I have added a button to my mat-expansion-panel: mat-expansion-panel-header in Angular Material 7.
Without the button the alignment of the title is correct but with the button it is shifted upwards. Image link below.

I am using the following scss to move the button to the right.

.right-aligned-header > .mat-content {
    justify-content: space-between;
}

.mat-content > mat-panel-title, .mat-content > mat-panel-description {
  flex: 0 0 auto;
}

How can I get the header text to be in its normal, centered, position?

A: I used the following:
mat-panel-title {
    justify-content: center !important;
}

A: Create a CSS class .headers-align and add it to your <mat-accordion class="headers-align">
The code for the CSS is this:

    .headers-align .mat-expansion-panel-header-title,
    .headers-align .mat-expansion-panel-header-description {
      flex-basis: 0;
     }

   .headers-align .mat-expansion-panel-header-description {
     justify-content: space-between;
     align-items: center;
    }

   mat-form-field {
    margin-right: 12px;
   }


text:
Q: Circular Doubly Linked List- Delete node I am working on building circular doubly linked list code.
In my code, there are four function- add node, delete node, print clockwise, print counterclockwise. All my code works fine, besides the delete function. The if(recycle->name == x) line seems not working properly, and free(recycle) also doesn't successfully free the recycle node.
My original code are. as follows
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define nameLen 20

struct Node
{
    char name[nameLen];
    struct Node *left; //next
    struct Node *right; //previous
};
struct Node* current;
struct Node* head;
int count = 0;

struct Node* GetNewNode(char *x)
{
    struct Node* newNode;

    newNode = (struct Node*)malloc(sizeof(struct Node));
    strncpy(newNode->name, x, nameLen);
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

void add_name(char *x)
{
    struct Node* temp = current;
    struct Node* newNode = GetNewNode(x);
    count++;
    if(current == NULL)
    {
        current = newNode;
        head = current;
    }
    else
    {
        current->left = newNode;
        newNode->right = temp;
        current = newNode;
        current->left = head;
        head->right = current;
    }
    printf("Add %s into database.\n\n", current->name);
}

void delete_name(char *x)
{
    int i, j;
    struct Node* recycle = current;
    if(current == NULL)
    {
        printf("No data input.");
    }
    else
    {
        for (i = 0; i < count; i++)
        {
            if(recycle->name == x)
            {
                free(recycle);
                j++;
                printf("Delete %s from database.\n", x);
            }
            recycle = recycle->left;
        }
        if(j == 0)
        {
            printf("There is no %s in data", x);
        }
        current = recycle;
    }
}

void print_clock(int number)
{
    int i;
    struct Node* temp = current;

    if(temp == NULL)
    {
        printf("No data input.");
    }
    else
    {
        printf("Clockwise: \n");
        for(i = 0; i < number; i++)
        {
            printf("%s ",temp->name);
            temp = temp->left;
        }
    }
    printf("\n\n");
}

void print_counter(int number)
{
    int i;
    struct Node* temp = current;
    if(temp == NULL)
    {
        printf("No data input.");
    }
    else
    {
        printf("Counterclockwise: \n");
        for(i = 0; i < number; i++)
        {
            printf("%s ",temp->name);
            temp = temp->right;
        }
    }
    printf("\n\n");
}

int main()
{
    char s1;
    char s2[nameLen];

    char name[nameLen];
    int number;

    while(1)
    {
        printf("Enter the instruction: ");
        scanf("%s %s", &s1, s2);

        if (s1 == '+' && sscanf(s2, "%d", &number) == 1)
        {
            printf("Print out %d name(s) clockwise.\n", number);
            print_clock(number);
        }
        else if (s1 == '-' && sscanf(s2, "%d", &number) == 1)
        {
            printf("Print out %d name(s) counterclockwise.\n", number);
            print_counter(number);
        }
        else if (s1 == '+' && sscanf(s2, "%s", name) == 1)
        {
            add_name(s2);
        }
        else if (s1 == '-' && sscanf(s2, "%s", name) == 1)
        {
            delete_name(s2);
        }
        else if (s1 == 'e')
        {
            printf("Bye.\n");
            break;
        }
        else // No match.
            printf("Wrong Input. %s %s\n", &s1, s2);
    }

    system("pause");
    return 0;
}

A: Statement recycle->name == x checks if two pointers point to the same object in memory. It does not check if two (different) objects in memory have equal content.
Use
if (strcmp(recycle->name, x) == 0) { ...

to check for equal string contents.


text:
Q: Interface result delphi to c# - class define dll use in c# I have a class define in dll. I export this class by interface. I use this dll and class in other Delphi project very good but I want use this class in c# but send error for me.
Source DLL:
type
  IMyDate = interface
    ['{D032F796-167D-4B0D-851D-2AEEA226646A}']
    Procedure Analyze_Date(var y:Integer; m,d:Integer); stdcall;
  end;

  TMyDate = Class(TInterfacedObject, IMyDate)
  Public
    Procedure Analyze_Date(var y:integer; m,d:Integer); stdcall;
  End;

procedure TMyDate.Analyze_Date(var y:Integer; m, d: Integer);
begin
  y:= m+d;
end;

Function MyDate:IMyDate; stdcall;
begin
  result:= TMyDate.Create;
end;

exports
  MyDate;

Unit use in Delphi example:
Function MyDate:IMyDate; stdcall; external 'Project11';

implementation

procedure TForm3.Button1Click(Sender: TObject);
var
  md:IMyDate;
  var y,m,d:Integer;
begin
  md:= MyDate;
  y:=10;
  m:=20;
  d:=30;
  md.Analyze_Date(y,m,d);
  showMessage(intTostr(y));
end;

Use in c# but get error:
//[Guid("D032F796-167D-4B0D-851D-2AEEA226646A")]
public interface IMyDate
{
    void Analyze_Date(ref int y, int m, int d);
}

[DllImport(
"Project11.dll"
, EntryPoint = "MyDate"
, SetLastError = true
, CallingConvention = CallingConvention.StdCall
, CharSet = CharSet.Unicode)]
public static extern IMyDate MyDate();

private void button9_Click(object sender, EventArgs e)
{
  int y, m, d;
  IMyDate da;
  da = MyDate(); // get error this line
  y = 10;
  m = 20;
  d = 30;
  da.Analyze_Date(ref y, m, d);
}

Update
thank you for answer
i add new function to Interface and class but my function only return false
also my function and procedure in delphi is stdcall and interface in C# is normaly !!!
IMyDate = interface
['{D032F796-167D-4B0D-851D-2AEEA226646A}']
Function testing():Boolean; stdcall;
end;

TMyDate = Class(TInterfacedObject, IMyDate)
Public
Function testing():Boolean; stdcall;
End;

function TMyDate.testing(): Boolean;
begin
result:= true;
end;

c#:
[ComImport, Guid("D032F796-167D-4B0D-851D-2AEEA226646A"),
 InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMyDate
{
    bool testing();
}

[DllImport(
      "Project11.dll"
      , EntryPoint = "CreateMyDate"//"MyDate"
      , SetLastError = true
      , CallingConvention = CallingConvention.StdCall
      , CharSet = CharSet.Unicode)]
public static extern void CreateMyDate(out IMyDate Date);

    Boolean b;

    b = da.testing();  //this line only return false
    if (b)
    {
        MessageBox.Show("ffff");
    }

A: The first issue I see is that Delphi's binary interface for function return values is different from that used by C# (and indeed every other major Windows compiler).
So instead of using a function, use an out parameter.
procedure CreateMyDate(out Date: IMyDate); stdcall;
begin
  Date := TMyDate.Create;
end;

Then on the C# you can declare the function like this:
[DllImport(@"Project11.dll")]
public static extern void CreateMyDate(out IMyDate Date);

Note that I removed a load of spurious parameters to your DllImport attribute. I guess you were adding them at random!
The other issue is the interface. It needs to be declared as being a COM interface that supports IUnknown. Like this:
[ComImport, Guid("D032F796-167D-4B0D-851D-2AEEA226646A"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMyDate
{
    void Analyze_Date(ref int y, int m, int d);
}

Update 1
The first problem with the updated question is something I failed to pick up in my original answer. The way the C# interface is declared means that that the marshaller assumes that the native functions all return HRESULT COM error codes. If the C# method has a return value then it is implicitly converted into an out parameter. There is a simple way to achieve this in Delphi. You replace stdcall with safecall on each method in the interface, and obviously in the implementation of that interface. Note that you should not change the calling convention of the CreateMyDate function.
So your Delphi code should be like this:
IMyDate = interface
  ['{D032F796-167D-4B0D-851D-2AEEA226646A}']
  Function testing():Boolean; safecall;
end;

TMyDate = Class(TInterfacedObject, IMyDate)
Public
  Function testing():Boolean; safecall;
End;

Another problem with the method in updated question is that C# marshals bool as a 4 byte value, but Delphi Boolean is just a single byte. This error is actually benign, but you can fix the problem by making the two sides of the interface match. For example:
[return: MarshalAs(UnmanagedType.U1)]
bool testing();

And I repeat what I said above. I removed spurious parameters from your DllImport attribute. In particular don't use SetLastError because your code is not setting the Win32 last error. Your DllImport should be exactly as per my answer. Don't confuse things by adding needless extra parameters to the attribute.
Update 2
You say in comments that you can't use safecall on the Delphi side. Which means that you need to suppress the HRESULT signature transformation on the C# side of the interface. That's done with MethodImplOptions.PreserveSig. You need to apply it to each method on your C# interface.
[ComImport, Guid("D032F796-167D-4B0D-851D-2AEEA226646A"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMyDate
{
    [MethodImplAttribute(MethodImplOptions.PreserveSig)]
    void Analyze_Date(ref int y, int m, int d);

    [MethodImplAttribute(MethodImplOptions.PreserveSig)]
    [return: MarshalAs(UnmanagedType.U1)]
    bool testing();
}

This interface matches up with a Delphi interface declared like this:
IMyDate = interface
  ['{D032F796-167D-4B0D-851D-2AEEA226646A}']
  procedure Analyze_Date(var y: Integer; m, d: Integer); stdcall;
  function testing(): Boolean; stdcall;
end;


text:
Q: How to not accept special characters in a string on Delphi 10.3 I am trying to write a program for my school-based assignment. It is supposed to accept names as strings, and a salary input as an integer, and tell you whether you are illegible or able to participate in party sections, and repeats until stop=9.
Everything went well, but the issue is the string variables accept erroneous names as inputs and continue. For example 'John32@#$^^'.
I want the program to not accept these inputs, and write a line stating that it will not continue with any name with anything other than characters. This should also not add a number to stop. The source code is below.
program Sba;

Uses
  Windows;

var
  FName,LName:String;
  Stop,Salary:Integer;

//procedure Sleep(milliseconds: Cardinal); stdcall; external 'kernel32.dll'; //Added sleep as a procedure for delay

Begin
  Repeat //Repeats until stop = 9
    Writeln('Hi User,please Enter your First Name'); //Prompting user to enter their First initials
    Readln(FName); //Attaches the string entered to the variable FName
    Sleep(1000);//Delay 1second
    Writeln('First Name entered');  //Lets the user know they have entered their first initials
    Sleep(1000);
    Writeln('Please Enter your Last name'); //Prompting user to enter their last initial
    Readln(LName);  //Attaches the string entered to the variable LName
    Sleep(1000);
    Writeln('Last Name entered'); //Lets the user know they have entered their last initials
    Sleep(800);
    Writeln('Hi ',' ',FName,' ',LName); //Writes Line Hi (First Name) (Last Name)
    Sleep(1000);
    Writeln('Please enter The amount you have paid');//Prompts user for their payment
    Readln(Salary); //Atttached value entered to Salary
    Writeln('Reading your payment will be done in four seconds');
    Sleep(4000);//delay 4 seconds
    Writeln('Done!');
    If (Salary<1000) Then
    Begin
      Writeln('You do not have sufficient funds to play in a section');
    Sleep(1000);
    End;
    Sleep(1000);
    If (Salary>=1000) AND (Salary<=2000) then //Testing conditions
    Begin
      Sleep(1000);
      Writeln('Congrats, You are eligible to play in the Tribe Section'); //Tells use what section they are available to play in
    End;
    If (Salary>=2100) AND (Salary<=3000) then //Testing conditions
    Begin
      Sleep(1000);
      Writeln('Congrats, You are eligible to play in the Poison Section');
    End;
    If (Salary>=3100) AND (Salary<=5000) then //Testing conditions
    Begin
      Sleep(1000);
      Writeln('Congrats, You are eligible to play in the Harts Section');
    End;
    Writeln('Press enter to continue');
    Readln;
    Writeln('Enjoy your day ' , FName,'!');
    Stop:=Stop+1; //Repeats until stop= 9
    Sleep(1000);
  Until Stop=9;//Repeats this 10 times
  Writeln('Written By Timothy Adams 4-1');
  Readln;
end.

A: Since this is homework, I will not give you exactly what you ask for. Instead, I'll give you a somewhat more involved example to study.
First, we must decide what a valid name looks like. Because if we don't know exactly what names are to be considered valid, we surely cannot program a computer to tell the difference!
Just as a toy example, let's say that a name is valid iff:

*

*It contains only letters, whitespace, and the HYPHEN-MINUS (-) character. [Notice that everything in a string is a character. Examples of character classes are letters, digits, whitespace, and punctuation. So when you say that the string must only contain "characters", you mean something else, like "only letters".]

*It contains at least two letters.
This is by far not good enough for a real-world application. It would disallow many valid names. But it is good enough for this toy example.
Let's implement this!
function IsValidName(const S: string): Boolean;
var
  i, c: Integer;
begin

  // The string must only contain letters, whitespace, and HYPHEN-MINUS

  for i := 1 to S.Length do
    if not (S[i].IsLetter or S[i].IsWhiteSpace or (S[i] = '-')) then
      Exit(False);

  // The string must contain at least two letters

  c := 0;
  for i := 1 to S.Length do
    if S[i].IsLetter then
      Inc(c);

  if c < 2 then
    Exit(False);

  Result := True;

end;

Study this function until you fully understand how it works!
Done? Great! Now let's make use of it:
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Character;

var
  Name: string;

function IsValidName(const S: string): Boolean;
begin
  // same as above, won't repeat it here
end;

begin
  try
    try

      Writeln('Hello! What is your name?');

      while True do
      begin
        Readln(Name);
        Name := Name.Trim;
        if IsValidName(Name) then
        begin
          Writeln('Welcome, ', Name, '!');
          Break;
        end
        else
          Writeln('Surely that isn''t your real name? What is your actual name?');
      end;

    except
      on E: Exception do
        Writeln(E.ClassName, ': ', E.Message);
    end;
  finally
    Writeln('Program about to end. Press Return to exit.');
    Readln;
  end;
end.

Again, since I am almost breaking the rules by doing your homework for you, I won't explain the logic in detail. Instead, I'll let you figure out how it works for yourself. That way you will learn a lot more.
Update: The complete program should look like this:
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Character;

var
  Name: string;

function IsValidName(const S: string): Boolean;
var
  i, c: Integer;
begin

  // The string must only contain letters, whitespace, and HYPHEN-MINUS

  for i := 1 to S.Length do
    if not (S[i].IsLetter or S[i].IsWhiteSpace or (S[i] = '-')) then
      Exit(False);

  // The string must contain at least two letters

  c := 0;
  for i := 1 to S.Length do
    if S[i].IsLetter then
      Inc(c);

  if c < 2 then
    Exit(False);

  Result := True;

end;

begin
  try
    try

      Writeln('Hello! What is your name?');

      while True do
      begin
        Readln(Name);
        Name := Name.Trim;
        if IsValidName(Name) then
        begin
          Writeln('Welcome, ', Name, '!');
          Break;
        end
        else
          Writeln('Surely that isn''t your real name? What is your actual name?');
      end;

    except
      on E: Exception do
        Writeln(E.ClassName, ': ', E.Message);
    end;
  finally
    Writeln('Program about to end. Press Return to exit.');
    Readln;
  end;
end.


text:
Q: about read system call in c when i use read system call, the buffer that i provide in the second argument, where the data
from reading are supposed to get stored, gets overwritten right!?
thanks,
Nikos

A: Yes, that is the point of read(), to fill (=overwrite) the buffer with the content read from the file.

A: Only as many bytes as the value returned from the read() call are overwritten.
ovr = read(f, buf, 1000);
if (ovr < 0) /* error */;
/* `ovr` bytes of `buf` were overwritten */


text:
Q: Converting existing Angular App with completly New UI design I have one Angular project, which is already created by another developer.
Now the requirement is to create a complete New UI with already existing features.
I have two options:

*

*Create a new Angular app and add one by one features with new UI changes

*Add new UI changed in existing projects with one by one features.
I am confused, which one I should pick up.
The existing code is very complex and messy.
I also want to change the design architecture with modular design, because it doesn't follow lazy loading and  each & every module is loading in starting only.
Please help me to finalize the design.
Thanks in advance.


text:
Q: Dynamically add columns to temp table based on rows in another temp table I am trying to build a temp table with a dynamic number of columns based on the number of rows from another temp table. Say I have 89 rows in #table1, in #table2 I would like to use the row count and take that corresponding row value as the column name. I've been fiddling with this for a while but I keep getting errors. Here's my query which will be turned into a proc later.
My table looks like this (all columns are varchar with null allowed in case the imported date has no data for that CVE Number - CVEId relates to FK constraint CVEID on CVENumber table):
CVEId     D20160901     D20160902     D20160903     D20160904     D20160905
1         6182          6473          5879          NULL          NULL
2         72862         76583         NULL          NULL          74772

CVENumber Table:
CVEID     CVENumber
1         CVE-781-2016
2         CVE-006-2016

What I'm hoping for is to get the date of the column or perhaps use an injected date as the first row - run a query against this data where I can specify 09-01-2016 TO 09-03-2016. And return all rows from the table with the CVENumber referred to in the CVENumber table. What I want my result to look like:
CVE Number     09-01-2016     09-02-2016     09-03-2016
CVE-781-2016         6182           6473           8579
CVE-006-2016        72682          76583              0

I hope this clarifies what I am trying to do.
My current query using STUFF() which takes the rows from #FixedDates and turns those into columns. I want to take those columns returned to @cols to be added as columns to #query_results
Set nocount on

Insert #tmp
EXEC sp_columns @table_name = N'CVECountsByDate'

-- Using collate to force the DB to only look at Uppercase values
DECLARE @cols varchar(max), @query varchar(max), @cols2 varchar(MAX)

INSERT #FixedDays
SELECT Replace(COLUMN_NAME, 'D' collate Latin1_General_CS_AS, '' collate Latin1_General_CS_AS) from #Tmp
WHERE COLUMN_NAME LIKE 'D%' collate Latin1_General_CS_AS OR COLUMN_NAME = 'CVEId' ORDER BY COLUMN_NAME DESC

SET @cols = STUFF((SELECT ',' + QUOTENAME(QT.COLUMN_NAME) + ' varchar(100)'
                 FROM #FixedDays QT
                 GROUP BY QT.COLUMN_NAME
                 ORDER BY QT.COLUMN_NAME
                 FOR XML PATH(''), TYPE
                 ).value('.', 'VARCHAR(MAX)')
                 ,1,1,'')

SET @cols2 = N'CREATE TABLE #query_results (' + @cols + ') '
--EXEC(@cols2)
SELECT @cols2

DROP TABLE #FixedDays
DROP TABLE #Tmp

A: This is what I ended up doing...
CREATE TABLE #Tmp
(TABLE_QUALIFIER varchar(40),
  TABLE_OWNER varchar(20),
  TABLE_NAME varchar(40),
  COLUMN_NAME varchar(40),
  DATA_TYPE int,
  TYPE_NAME varchar(20),
  PREC int, LENGTH int,
  SCALE int, RADIX int,
  NULLABLE char(4),
  REMARKS varchar(128),
  COLUMN_DEF varchar(40),
  SQL_DATA_TYPE int,
  SQL_DATETIME_SUB int,
  CHAR_OCTET_LENGTH int,
  ORDINAL_POSITION int,
  IS_NULLABLE char(4),
  SS_DATA_TYPE int)
CREATE TABLE #FixedDays
 (COLUMN_NAME varchar(40))
CREATE TABLE #query_results
(CVENumber varchar(100) null)
Set nocount on
Insert #tmp
EXEC sp_columns @table_name = N'CVECountsByDate'
INSERT #FixedDays
SELECT Replace(COLUMN_NAME, 'D' collate Latin1_General_CS_AS, '' collate Latin1_General_CS_AS) from #Tmp
WHERE COLUMN_NAME LIKE 'D%' collate Latin1_General_CS_AS OR COLUMN_NAME = 'CVEId'
DECLARE @listStr VARCHAR(MAX)
DECLARE @FixedList VARCHAR(MAX)
SELECT @FixedList = COALESCE(@FixedList,'[') + COLUMN_NAME + '] VARCHAR(MAX) NULL, [' FROM #FixedDays
SELECT @FixedList = substring(@FixedList, 1, len(@FixedList) -1)
SET @FixedList = LEFT(@FixedList, len(@FixedList)-1) -- Altered Column List
EXEC(N'ALTER TABLE #query_results ADD ' + @FixedList + '')
INSERT INTO #query_results
SELECT CVEDetails.CVENumber, CVECountsByDate.* FROM CVECountsByDate INNER JOIN CVEDetails ON  CVECountsByDate.CVEId = CVEDetails.CVEID
ALTER TABLE #query_results DROP column CVEId

DROP TABLE #query_results
DROP TABLE #Tmp
DROP TABLE #FixedDays


text:
Q: How do I specify a CodeDeploy application and deployment group name in SAM template? I'm using a SAM template for B/G deployment. The problem is a CodeDeploy resource is automatically created. Is it possible to specify a name for application and deployment group?
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/automating-updates-to-serverless-apps.html

If you enable gradual deployments through your AWS SAM template, a
CodeDeploy resource is automatically created for you. You can view the
CodeDeploy resource directly through the AWS Management Console.


text:
Q: cocos2d position sprite according to touch I have a sprite looking like a pencil. I want to draw a line when user touches this sprite.
I am able to draw the line on touch location & move the sprite accordingly. The problem is that the line is not drawing from tip of the pencil which lies at left bottom of the sprite.
I don't want to move the left bottom edge of sprite under the touch point because then user will not be able to see the tip but instead shift the coordinates to draw to the tip itself.
I tried setAnchorPoints but that's not helping. Anyone tried this or has better ideas please do share. Thanks.

A: You could draw the line at something like pencil.position.y - (pencil.sizeofthesprite.y / 2) and it should be fine.


text:
Q: Similaridade de elementos em diferentes vetores Tenho dois vetores:
A <- c("RS", "DF", "CE")
B <- c("Porto Alegre - RS", "Brasília - DF", "Fortaleza - CE", "Porto Alegre - RS",
"Acre - AC", "Recife - PE")

e uma função:
f <- function(a,b) {
  lista <- grep(a,b, fixed = FALSE)
  return(lista)
}
mm <- lapply(A, B, FUN = f)

Estou obtendo a posição dos elementos de A em B, mas preciso dos elementos de B e não a posição.
Pensei que isso funcionaria:
B[mm]

Mas não deu. Como faço isso?

A: O resultado de lapply(A, B, FUN = f) é uma lista. Rode
B[unlist(mm)]

que o resultado vai ser o desejado:
[1] "Porto Alegre - RS" "Porto Alegre - RS" "Brasília - DF"
[4] "Fortaleza - CE"

Se quiser obter os resultados únicos, sem repetição, faça
unique(B[unlist(mm)])
[1] "Porto Alegre - RS" "Brasília - DF"     "Fortaleza - CE"


text:
Q: How to calculate the month begin and end month date from date in polars? Is there an efficient way to get the month end date on a date column.  Like if date ='2023-02-13" to return "2023-02-28", also beginning of the month would be great as well.
Thanks!
df = pl.DataFrame({'DateColumn': ['2022-02-13']})

test_df = df.with_columns([
    pl.col('DateColumn').str.strptime(pl.Date).cast(pl.Date)
]
)

┌────────────┐
│ DateColumn │
│ ---        │
│ date       │
╞════════════╡
│ 2022-02-13 │
└────────────┘

Two new columns would be perfect.

A: You could use .truncate
and
.offset_by
test_df.with_columns(
   MonthStart = pl.col("DateColumn").dt.truncate("1mo"),
   MonthEnd = pl.col("DateColumn").dt.offset_by("1mo").dt.truncate("1mo").dt.offset_by("-1d")
)

shape: (1, 3)
┌────────────┬────────────┬────────────┐
│ DateColumn | MonthStart | MonthEnd   │
│ ---        | ---        | ---        │
│ date       | date       | date       │
╞════════════╪════════════╪════════════╡
│ 2022-02-13 | 2022-02-01 | 2022-02-28 │
└────────────┴────────────┴────────────┘


text:
Q: How to encrypt or obfuscate strings inside NSURL? I have a path to a URL, in objective C code
I want to obfuscate or encrypt this value so that users won't see this code
They are integrating my entire code into their apps, but I don't want them to see the url.
What's a way for me to obfuscate the url?

A: Assuming you have control of the web server, your URLs can be as meaningless or meaningful as you want.  They can be anything and you can map them anyway you want.  Munge bits. Use encryption.  Whatever you want.
The first question to ask is what are you trying to achieve?  Protection from casual hacking or full on security?
Hopefully the former.   If the latter, then you need to hire a security expert.
If the former, then:
• use https and verify the server certificate(s)
• use public key encryption and have your app grab the public key and then encrypt the URL contents
• obfuscate your arguments and values, etc...
... etc ...
Some combination of the above would get you pretty far from keeping casual prying eyes out of your URL space.   If your goal is to keep people out of your server, think about employing a time limited UUID or something that is tagged to the session, generated by the server and cannot be generated on the client.

A: There's no way to do that since you need the plain url to be translated to a ip address by a nameserver, more than that, once you have the url obfuscated you will won't have anything that can be translated by all servers envolved.
The best way to obfuscate data in a url is by obfuscating only parameters values.

A: I assume that you need the URL to send HTTP requests to a server. So every user that has a WLAN with a firewall capable of logging all requests will be able to log and see your URL.
Whatever encryption or obfuscation method you use, it will not have the intended effect. Logging on the firewall is probably even easier than disassembling the app even if the URL is not obfuscated at all.


text:
Q: too many 'where' clauses in rails(using MySQL) for one-to-one connection I have a kind of restaurant description database and users can search which restaurant is what they are looking for. But there are too many columns that describes different attributes and my search form doesn't get much queries(? I don't know it is the right expression in this context, I'm so newbie in programming...) just for category, locations and names.
So I made one distinct database(rest_key) which looks like this
class CreateRestKeys < ActiveRecord::Migration
  def change
    create_table :rest_keys do |t|
      t.integer :category
      t.string :name
      t.string :addr
      t.integer :restaurant_id  # reference for real Restaurant model
      t.timestamps
    end
  end
end

and my Restaurant model & RestKey model looks like below (one-to-one association)
class Restaurant < ActiveRecord::Base
  has_one :rest_key
end

class RestKey < ActiveRecord::Base
  belongs_to :restaurant
end

and I wanted at first, get queries from users and find RestKey, then retrieve restaurants related with that RestKey. This kind of logic
Restaurant.joins(:rest_key).where("rest_keys.category = ? AND
                                   rest_keys.name LIKE ? AND
                                   rest_keys.addr LIKE ?",
                                   search_category, "%#{search_name}%", "%#{search_addr}%")

But the problem is that users can put many words in search_addr input box for accuracy. So I thought first I can make array for address like arr = params[:search_addr].split and do the previous process with many many where clauses.
Restaurant.joins(:rest_key).where("rest_keys.category = ? AND
                                   rest_keys.name LIKE ? AND
                                   rest_keys.addr LIKE ? AND   # addr search starts
                                   rest_keys.addr LIKE ? AND
                                   rest_keys.addr LIKE ? AND
                                   rest_keys.addr LIKE ? AND
                                   rest_keys.addr LIKE ?",
                                   search_category, "%#{search_name}%", "%#{arr[0]}%", "%#{arr[1]}%", "%#{arr[2]}%", "%#{arr[3]}%", "%#{arr[4]}%")

Even though I have so poor knowledge, I could feel this code can't be called code. Can I loop the where clauses or is there any idea that can filter with address input? Any comments will be a huge help for me!(I think users can type address words in odd order, so I have to split them and filter with every words)

A: You can try this.
Instead of doing arr[0], arr[1] you can simple use matches_any with array
rest_key_table = RestKey.arel_table
rest_key_table[:addr].matches_any(arr)

You can use below  way
You can try it by part by part
rest_key_table = RestKey.arel_table
@rest_categories = Restaurant.where(:rest_keys => {:category => search_category}, :joins => :rest_keys)
@rest_categories.where(rest_key_table[:addr].matches_any(arr))

A: I didn't know that SQL can have string as the query in rails. So I changed the above codes like
sql = ""
array = []
params[:search_addr].split.each do |addr|
  addr = "'%" + addr + "%'"
  array << "rest_keys.addr LIKE " + addr
end
sql = array.join(' AND ')

Restaurant.joins(:rest_key).where(sql)

I hope this answer can help anyone newbie like me. If there is a better way, please let me know, it will be a good lesson to me.


text:
Q: Stat tools and methodologies for principal-agent problem What are the most useful, popular or important statistical tools and/or methodologies for empirical study of 'agent-principal problem'?
A simple example will be very useful.
References or book recommendations are highly appreciated.
Thank you very much!!


text:
Q: Construct a rational function whose graph in the xy-plane has a vertical asymptotes lines x = 3 and x = 5 oblique asymptote the lines y = 2x -3 I'm studying for a test and I came across this example problem and the oblique part is throwing me off. How do i go about solving this?

A: Look at the oblique and vertical asymptotes separately.  An expression for a function with the vertical asymptote is
$$y=\frac{1}{(x-3)(x-5)}$$
Since this goes to zero as x goes to infinity, it does not affect the oblique asymptote.  Then you can consider the function
$$y=\frac{1}{(x-3)(x-5)}+2x-3$$
This graph has all the features that you want.  To convert to a rational form, you just need to find a common denominator to combine.

A: Alright, so the denominator should obviously be something like $(x-5)(x-3)$, or $x^2-8x+15$.
To get the desired oblique asymptote, let the numerator equal the denominator times $2x-3$. However, make sure to add some random constant to the numerator, or else your rational equation will become a line. Thus, your equation should be something like this:
$$\frac{2x^3-19x^2+54x-45+C}{x^2-8x+15}$$
Where $C$ is some arbitrary nonzero constant.


text:
Q: The category of hypergraphs as a topos It seems known that the category of hypergraphs is a topos.
I am looking for any reference here, or just a statement of this in the literature, but can't find anything. There is one paper

A category-theoretical approach to hypergraphs,
  W. Dörfler and D. A. Waller, ARCHIV DER MATHEMATIK, Volume 34, Number 1, 185-192, DOI:10.1007/BF01224952, 1980

which might contain information about that, but I don't have access to this paper (and it might take some time to get a copy, likely a paper-copy).
By a hypergraph I mean here a triple $(V,E,h)$, where $V$, $E$ are arbitrary sets, while $h$ is a map from $E$ to the set of finite subsets of $V$ (so $V$ is the set of vertices, $E$ the set of hyperedge-labels, and $h$ yields the hyperedge of a hyperedge-label). Morphisms are pairs $a: V \rightarrow V'$, $b: E \rightarrow E'$, which fulfill the usual commutativity condition.

A: One can reinterpret a hypergraph as a span-shaped diagram of sets where the left leg of the span is a finite map (meaning, all preimages are finite). Indeed, given a hypergraph, consider the span
$$V\leftarrow\lbrace(v,e)\in V\times E\mid v\in h(e)\rbrace\rightarrow E;$$
it is clear that this gives a correspondence.
This seems more natural to work with.
The category of sets is a topos. The category of diagrams of some given shape in a topos is itself a topos, so the category of span-shaped diagrams of this sort is again a topos. Imposing finiteness conditions tends not to destroy the property of being a topos, and one can rapidly check that philosophy in this case.

A: According to this presentation:

Will Grilliette and Lucas Rusnak, Natural Generalizations of Graphs Part II: Commas, Topoi, & Homomorphisms,
  Discrete Mathematics Seminar, Texas State University (2017) DOI:10.13140/RG.2.2.13627.92961

Quote:

The classical categories H of hypergraphs and M of (undirected) multigraphs arise naturally as a comma category using the power-set functor P. However, P is well-known not to preserve limit processes, and both H and M fail to be Cartesian closed as a result, among other issues. On the other hand, the category Q of quivers arises equivalently as both a comma category and a functor category. Consequently, Q can be represented as a topos of presheaves, inheriting a significant amount of structure immediately.

note: quiver = directed multigraph.


text:
Q: SR-IOV with Qualcomm adapter I have a Lenovo laptop with Ubuntu-20.04 installed. The lspci command shows the following.
lspci | grep Ethernet
01:00.0 Ethernet controller: Qualcomm Atheros AR8152 v2.0 Fast Ethernet (rev c1)

Most examples in search results seem to refer to Intel devices. So, how do I enable SR-IOV for my Ubuntu laptop?


text:
Q: How to add attributes to input fields in JSP How can I add the following attributes:

*

*placeholder="text here"

*required

*data-parsley-type="number"

*checked (only for he radio)

To the following inputs in a form:
<html:text property="text" value="text" />
<html:radio property="radio" value="1" />
<html:select property="text" value="1" />


text:
Q: Call make from script, only if main.c is modified The problem: I want to run only a script (e.g. run.sh), which will decide for me if make should be called (and call it if needed) and then run the executable.

My project has only one file, that is main.c. However, just the linking makes me wait a bit, something that I do not like when I debug and I am eager for the program to run. I would like something like this into run.sh:
#!/bin/bash
if[ main.c has changed from the last time make was called] then
  make > compile.txt
fi
./a.out

so that the make is called only if main.c is modified. By modified, one could take that the timestamp is changed (even if that may not the actual criterion). Is this feasible?

If so, I saw this answer, which made me think that every time I enter the body of the if statement that calls make, a copy of main.c would be created, or the timestamp of the file would be stored (in a file maybe), so that the next time the script runs, it will restore that information and check the if condition to see if timestamps differ. So, the second question is, how to do it?

A: Simply
#!/bin/bash

if [ a.out -ot main.c ]; then
    make > compile.txt
fi

./a.out

-ot is equivalent to older than
However, this behaviour is expected from make itself. I would prefer a makefile like
CC = gcc
CFLAGS = -Wall -W

main: main.c
    $(CC) $(CFLAGS) -o $@ $^

The main rule would run only if main.c is updated after last make


text:
Q: i got an error type 'String' is not a subtype of type 'int' of 'index' how should i fix this? enter image description here
enter image description here
i try to make a comment screen to make a comment from post like instagram but when i click the button icon to the comment screen page, i got the error "type 'String' is not a subtype of type 'int' of 'index'"
The relevant error-causing widget was CommentsScreen. i dont know how to fix this, here is the code..
`
 IconButton(
                onPressed: () => Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => CommentsScreen(
                      snap: widget.snap['postId'].toString(),
                    ),
                  ),
                ),
                icon: const Icon(
                  Icons.comment_outlined,
                ),
              ),

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:instagram/models/user.dart';
import 'package:instagram/providers/user_provider.dart';
import 'package:instagram/resources/firestore_methods.dart';
import 'package:instagram/utils/colors.dart';
import 'package:instagram/widgets/comment_card.dart';
import 'package:provider/provider.dart';

class CommentsScreen extends StatefulWidget {
  final snap;
  const CommentsScreen({super.key, required this.snap});

  @override
  State<CommentsScreen> createState() => _CommentsScreenState();
}

class _CommentsScreenState extends State<CommentsScreen> {
  final TextEditingController _commentController = TextEditingController();

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _commentController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final User user = Provider.of<UserProvider>(context).getUser;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: mobileBackgroundColor,
        title: const Text('comments'),
        centerTitle: false,
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('posts')
            .doc(widget.snap['postId'])
            .collection('comments')
            .orderBy(
              'datePublished',
              descending: false,
            )
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          return ListView.builder(
            itemCount: (snapshot.data! as dynamic).docs.length,
            itemBuilder: (context, index) => CommentCard(
              snap: (snapshot.data! as dynamic).docs[index].data(),
            ),
          );
        },
      ),
      bottomNavigationBar: SafeArea(
        child: Container(
          height: kToolbarHeight,
          margin: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          padding: const EdgeInsets.only(left: 16, right: 8),
          child: Row(
            children: [
              CircleAvatar(
                backgroundImage: NetworkImage(
                  user.photoUrl,
                ),
                radius: 18,
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left: 16, right: 8.0),
                  child: TextField(
                    controller: _commentController,
                    decoration: InputDecoration(
                      hintText: 'comment as ${user.username}',
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),
              InkWell(
                onTap: () async {
                  FirestoreMethods().postComment(
                    widget.snap['postId'],
                    _commentController.text,
                    user.uid,
                    user.username,
                    user.photoUrl,
                  );
                  setState(() {
                    _commentController.text = "";
                  });
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    vertical: 8,
                    horizontal: 8,
                  ),
                  child: const Text(
                    'post',
                    style: TextStyle(
                      color: Colors.blueAccent,
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

`
i try to make a comment from post i was expecting that it works fine