text:
Q: Serving static web resources in Spring Boot & Spring Security application I am trying to develop Spring Boot web application and securing it using Spring security java configuration.
After placing my static web resources in 'src/main/resources/public' as advised here in Spring blog, I am able to get the static resources. i.e hitting https://localhost/test.html in browser do serves the html content.
Problem
After I enabled Spring Security, hitting the static resource URL requires authentication.
My relevent  Spring Security Java config looks like this:-
@Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.
            authorizeRequests()
                .antMatchers("/","/public/**", "/resources/**","/resources/public/**")
                    .permitAll()
                .antMatchers("/google_oauth2_login").anonymous()
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/home")
                    .and()
                    .csrf().disable()
                    .logout()
                        .logoutSuccessUrl("/")
                        .logoutUrl("/logout") // POST only
                .and()
                    .requiresChannel()
                    .anyRequest().requiresSecure()
                .and()
                    .addFilterAfter(oAuth2ClientContextFilter(),ExceptionTranslationFilter.class)
                    .addFilterAfter(googleOAuth2Filter(),OAuth2ClientContextFilter.class)
                .userDetailsService(userService);
        // @formatter:on
    }

How should I configure antMatchers to permit static resources placed inside src/main/resources/public ?

A: If you are using webjars. You need to add this in your configure method:
http.authorizeRequests().antMatchers("/webjars/**").permitAll();
Make sure this is the first statement. For example:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

You will also need to have this in order to have webjars enabled:
@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }

A: @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] resources = new String[]{
                "/", "/home","/pictureCheckCode","/include/**",
                "/css/**","/icons/**","/images/**","/js/**","/layer/**"
        };

        http.authorizeRequests()
                .antMatchers(resources).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout().logoutUrl("/404")
                .permitAll();
        super.configure(http);
    }
}

A: i had the same issue with my spring boot application, so I thought it will be nice if i will share with you guys my solution. I just simply configure the antMatchers to be suited to specific type of filles. In my case that was only js filles and js.map. Here is a code:
   @Configuration
   @EnableWebSecurity
   public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
      .antMatchers("/index.html", "/", "/home",
       "/login","/favicon.ico","/*.js","/*.js.map").permitAll()
      .anyRequest().authenticated().and().csrf().disable();
   }
  }

What is interesting. I find out that resources path like "resources/myStyle.css" in antMatcher didnt work for me at all. If you will have folder inside your resoruces folder just add it in antMatcher like "/myFolder/myFille.js"* and it should work just fine.

A:   @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/resources/**"); // #3
      }

Ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.

A: This may be an answer (for spring boot 2) and a question at the same time.
It seems that in spring boot 2 combined with spring security everything (means every route/antmatcher) is protected by default if you use an individual security mechanism extended from
WebSecurityConfigurerAdapter

If you don´t use an individual security mechanism, everything is as it was?
In older spring boot versions (1.5 and below) as Andy Wilkinson states in his above answer places like public/** or static/** are permitted by default.
So to sum this question/answer up - if you are using spring boot 2 with spring security and have an individual security mechanism you have to exclusivley permit access to static contents placed on any route. Like so:
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

private final ThdAuthenticationProvider thdAuthenticationProvider;

private final ThdAuthenticationDetails thdAuthenticationDetails;

/**
 * Overloaded constructor.
 * Builds up the needed dependencies.
 *
 * @param thdAuthenticationProvider a given authentication provider
 * @param thdAuthenticationDetails  given authentication details
 */
@Autowired
public SpringSecurityConfiguration(@NonNull ThdAuthenticationProvider thdAuthenticationProvider,
                                   @NonNull ThdAuthenticationDetails thdAuthenticationDetails) {
    this.thdAuthenticationProvider = thdAuthenticationProvider;
    this.thdAuthenticationDetails = thdAuthenticationDetails;
}

/**
 * Creates the AuthenticationManager with the given values.
 *
 * @param auth the AuthenticationManagerBuilder
 */
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {

    auth.authenticationProvider(thdAuthenticationProvider);
}

/**
 * Configures the http Security.
 *
 * @param http HttpSecurity
 * @throws Exception a given exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .antMatchers("/management/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())
            .antMatchers("/settings/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())

            .anyRequest()
            .fullyAuthenticated()
            .and()
            .formLogin()
            .authenticationDetailsSource(thdAuthenticationDetails)
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/bundle/index", true)
            .failureUrl("/denied")
            .and()
            .logout()
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login")
            .logoutUrl("/logout")
            .and()
            .exceptionHandling()
            .accessDeniedHandler(new CustomAccessDeniedHandler());
}

}
Please mind this line of code, which is new:
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

If you use spring boot 1.5 and below you don´t need to permit these locations (static/public/webjars etc.) explicitly.
Here is the official note, what has changed in the new security framework as to old versions of itself:
Security changes in Spring Boot 2.0 M4
I hope this helps someone.
Thank you!
Have a nice day!

A: Here is the ultimate solution, after 20+ hours of research.
Step 1. Add 'MvcConfig.java' to your project.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
    }
}

Step 2. Add configure(WebSecurity web) override to your SecurityConfig class
@Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**");
    }

Step 3. Place all static resources in webapp/resources/..

A: In the latest Spring Security 6, the WebSecurityConfigurerAdapter is deprecated.
Declare a WebSecurityCustomizer bean instead.
 @Bean
 public WebSecurityCustomizer ignoringCustomizer() {
     return (web) -> web.ignoring().requestMatchers("...");
 }

A: There are a couple of things to be aware of:

*

*The Ant matchers match against the request path and not the path of the resource on the filesystem.

*Resources placed in src/main/resources/public will be served from the root of your application.
For example src/main/resources/public/hello.jpg would be served from http://localhost:8080/hello.jpg
This is why your current matcher configuration hasn't permitted access to the static resources. For /resources/** to work, you would have to place the resources in src/main/resources/public/resources and access them at http://localhost:8080/resources/your-resource.
As you're using Spring Boot, you may want to consider using its defaults rather than adding extra configuration. Spring Boot will, by default, permit access to /css/**, /js/**, /images/**, and /**/favicon.ico. You could, for example, have a file named src/main/resources/public/images/hello.jpg and, without adding any extra configuration, it would be accessible at http://localhost:8080/images/hello.jpg without having to log in. You can see this in action in the web method security smoke test where access is permitted to the Bootstrap CSS file without any special configuration.

A: It,s work for spring security 6.0.*
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
                .csrf()
                .disable()
                .authorizeHttpRequests()
                .requestMatchers(
                        "/home/**",
                        "/login/**",
                        "/account/starter/**",
                        "/register/**",
                        "/plugins/**",
                        "/dist/**",
                        "/js/**",
                        "/**/favicon.ico").permitAll()
                .and()
                .httpBasic()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return http.build();
    }

                        "/plugins/**",
                        "/dist/**",
                        "/js/**",

... they are located in resources/
plugins, dist, js - these are the names of directories with resources


text:
Q: Leaflet - Creating LayerGroups Dynamically Is it possible to create LayerGroups Dynamically? I'm developing an web map that shows the tree species that exists in the parks, an i'm trying to create a LayerGroup for each species so that with a LayerControl i can hide and show certain species, for the sake of testing, i have been creating LayerGroups like this:
l1 = new L.LayerGroup();
//...
l100 = new L.LayerGroup();

And i'm sure that there is a way to do it depending on the number of species that exists, i have tried:
for (var i = 0; i < numberOfSpecies ; i++) {
  l[i] = new L.LayerGroup();
}

But this way, i cant do this:
l[0].addLayer(marker);

What is the best way to do something like this?

A: Yes, you can.
For example:
var layerGroups = {}

for (var i = 0; i < 3; ++i) {
    layerGroups[i] = L.layerGroup().addTo(map);
}

for (var i = 0; i < 3; ++i) {
    layerGroups[i].addLayer(L.marker([i,i]))
}

You can try it here : https://jsfiddle.net/mckbda9y/6/

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSRegularExpression usage in iOS I'm looking for usage of regular expression in my user input string for presence of the following:
- atleast one character in uppercase
- atleast one numberic character
- atleast 8 characters wide.
Any help would be appreciated.
Thanks

A: Try this (probably ascii only):
(?=.*[A-Z])(?=.*[0-9]).{8,}

or the Unicode variant (which, according the docs, should be supported):
(?=.*\p{Lu})(?=.*\p{Nd}).{8,}

Meaning:
(?=.*[A-Z])  # an upper case, anywhere in the string (or \p{Lu})
(?=.*[0-9])  # a digit, anywhere in the string      (or \p{Nd})
.{8,}        # 8 or more chars


text:
Q: Python Selenium: stale element reference: element is not attached to the page document My program is throwing an error message "Stale element reference: element is not attached to the page document". When I looked at the previous posts (such as Python Selenium stale element fix),, I found that I am not updating the url after calling click function. I updated the url. However, it didn't fix the issue. Could anyone point out where am I making mistake please? Here is my code:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-infobars")
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path="path of driver here")

driver.get("https://stackoverflow.com/users/37181/alex-gaynor?tab=topactivity")
if driver.find_elements_by_xpath("//a[@class='grid--cell fc-white js-notice-close']"):
    driver.find_element_by_xpath("//a[@class='grid--cell fc-white js-notice-close']").click()

inner_tabs = driver.find_elements_by_xpath("//div[@class='tabs']//a")

for inner_tab in inner_tabs:

    if inner_tab.text == "answers":
        inner_tab.click()
        time.sleep(3)
        driver.get(driver.current_url)
        continue

    if inner_tab.text == "questions":
        inner_tab.click()
        time.sleep(3)
        driver.get(driver.current_url)
        continue

driver.quit()

A: when you open new URL by clicking link or driver.get() it will create new document element so old element (inner_tab) will invalidate. to solve, first collect all URL then open in loop.
urls_to_visit = []

for inner_tab in inner_tabs:
    if inner_tab.text in ["questions", "answers"]:
        urls_to_visit.append(inner_tab.get_attribute("href"))

for url in urls_to_visit:
    driver.get(url)
    time.sleep(3)

A: This is one of the most frustrating errors you can get with Selenium.
I recommend to try it like this:
for tab in ['answers', 'questions']:
  js = "window.tab = [...document.querySelectorAll('div.tabs > a')].filter(a => a.innerText === '" + tab + "')[0]"
  driver.execute_script(js)
  driver.execute_script("if(window.tab) window.tab.click()")
  time.sleep(3)
  print(driver.current_url)

By selecting inside of the browser context you can avoid the stale references.


text:
Q: Telerik grid with a JavaScript confirm box to update a column I have a Telerik grid.  For each row there is a details table. The row is of type NominationTypeClass and the rows in the details table is of type Nomination.  So what this means for each nomination type there is a list of nominations.  The grid's code:
<telerik:RadGrid
   AllowPaging="true"
   AllowSorting="true"
   AutoGenerateColumns="false"
   GridLines="None"
   ID="rgMyNominations"
   OnDetailTableDataBind="rgMyNominations_DetailTableDataBind"
   OnItemDataBound="rgMyNominations_ItemDataBound"
   OnNeedDataSource="rgMyNominations_NeedDataSource"
   OnUpdateCommand="rgMyNominations_UpdateCommand"
   PageSize="5"
   runat="server"
   ShowHeader="false"
   ShowStatusBar="true">
   <MasterTableView DataKeyNames="NominationTypeID" HierarchyDefaultExpanded="true" Width="100%">
      <Columns>
         <telerik:GridTemplateColumn>
            <ItemTemplate>
               <asp:Label ID="lblNominationType" runat="server" Text='<%# DataBinder.Eval( Container, "DataItem.NominationType") %>' />
            </ItemTemplate>
            <ItemStyle Width="100%" />
         </telerik:GridTemplateColumn>
      </Columns>
      <NoRecordsTemplate>No Nomination Types.</NoRecordsTemplate>
      <DetailTables>
         <telerik:GridTableView PageSize="5" Name="Nominations" GridLines="None" Width="100%" ShowHeader="true" DataKeyNames="NominationID">
            <Columns>
               <telerik:GridTemplateColumn HeaderText="Person / Team">
                  <ItemTemplate>
                     <asp:Label ID="lblName" runat="server" Text='<%# GetName(DataBinder.Eval(Container, "DataItem")) %>' />
                  </ItemTemplate>
                  <ItemStyle VerticalAlign="Top" Width="20%" />
               </telerik:GridTemplateColumn>
               <telerik:GridTemplateColumn HeaderText="Date Nominated">
                  <ItemTemplate>
                     <asp:Label ID="lblNominationDate" runat="server" Text='<%# FormatDate(DataBinder.Eval(Container, "DataItem.NominationDate")) %>' />
                  </ItemTemplate>
                  <ItemStyle VerticalAlign="Top" Width="14%" />
               </telerik:GridTemplateColumn>
               <telerik:GridTemplateColumn HeaderText="Action" UniqueName="Action_Column">
                  <ItemTemplate>
                     <asp:HyperLink ID="hlEdit" runat="server" Text="Edit" />

                        <asp:LinkButton
                           CausesValidation="false"
                           CommandName="Update"
                           ID="lbWithdrawnStatus"
                           runat="server"
                           Text="Withdraw"
                           OnClientClick="javascript:return ConfirmWithdrawnStatusChange();" />

                  </ItemTemplate>
                  <ItemStyle VerticalAlign="Top" Width="7%" />
               </telerik:GridTemplateColumn>
            </Columns>
            <NoRecordsTemplate>No Nominations.</NoRecordsTemplate>
         </telerik:GridTableView>
      </DetailTables>
   </MasterTableView>
   <ClientSettings AllowExpandCollapse="true"></ClientSettings>
</telerik:RadGrid>

Here is how I populate my rows:
protected void rgMyNominations_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
   try
   {
      if (!e.IsFromDetailTable)
      {
         rgMyNominations.DataSource = GetNominationTypes();
      }
   }
   catch (Exception ex)
   {
      // Handle exceptions
   }
}

Here is how I populate my details table:
protected void rgMyNominations_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
{
   try
   {
      GridDataItem gridDataItem = (GridDataItem)e.DetailTableView.ParentItem;
      if (e.DetailTableView.Name == "Nominations")
      {
         int nominationTypeID = int.Parse(gridDataItem.GetDataKeyValue("NominationTypeID").ToString());

         List<Nomination> nominations = new List<Nomination>();

         // For each nomination type, add the nomination
         foreach (Nomination n in myNominationsList)
         {
            if (n.NominationType.NominationTypeID == nominationTypeID)
            {
               nominations.Add(n);
            }
         }

         e.DetailTableView.DataSource = nominations;
      }
   }
   catch (Exception ex)
   {
      // Handle exceptions
   }
}

I have an action column that has a link that says Withdrawn.  When clicked I have a JavaScript confirm box with a Yes or No option.  If yes, then the nomination status is updated to withdrawn.  Then I want the grid to be refreshed to show the updated status.  I used the grid's update command to to show the show the JavaScript's command box.  It updates, but is it the correct way to do it?
protected void rgMyNominations_UpdateCommand(object source, GridCommandEventArgs e)
{
   try
   {
      StatusManager.InsertStatus( /* required parameters */ );

      // Refresh grid
      rgMyNominations.DataSource = GetNominationTypes();
      rgMyNominations.DataBind();
   }
   catch (Exception ex)
   {
      // Handle exceptions
   }
}

The binding of the grid doesn't want to work properly after the status was updated.  The grid row is of type NominationTypeClass and the details table is of type Nomination.  I debugged, and there where it set the datasource for each it is correct, but when the view is rendered for:
<asp:Label ID="lblNominationDate" runat="server" Text='<%# FormatDate(DataBinder.Eval(Container, "DataItem.NominationDate")) %>' />

...it says that NominationDate is not a property of NominationTypeClass.  This is wrong, I don't know why it is taking the type for the row to be the type of the details table?  NominationDate is a property of Nomination.  It seems like it is overriding the datasources.
Are there any online samples of what I am trying to accomplish?  Any advice would be appreciated.

A: One thing that sticks out a bit, and I'm not sure this is where the issue is coming from, is that you specifically set the DataSource and call DataBind() within the UpdateCommand event of the RadGrid.
First of all, when refreshing the RadGrid (if you're still binding to the same source) you should only need to call the .Rebind() function, instead of setting the data source and calling .Databind()
Secondly, the OnUpdateCommand should call .Rebind() without you having to specifically call it, and using that (or the method you use above) could lead to various odd issues. This could potentially be the source.
Aside from that, have you tried submitting a support ticket over at Telerik? I believe that their support team will be your best bet at handling this issue.


text:
Q: ADODB Connection Issues So I have a macro setup that will connect to an Access Database and output an SQL query to a specified worksheet. The macro itself runs fine, but when I try to use it a day after it will not work. It does work after I delete the existing connection string, get a new ADODB connection string, and paste it back into the code, but I don't want to go in every day to redo it. Here is the code I currently have (and I have edited it for readability):
Sub AccessDatabaseCopy()

    Dim AccessConn As ADODB.Connection
    Dim AccessData As ADODB.Recordset
    Dim AccessField As ADODB.Field

    Set AccessConn = New ADODB.Connection
    Set AccessData = New ADODB.Recordset

    AccessConn.ConnectionString =
 "Provider=Microsoft.ACE.OLEDB.12.0;Password="""";User ID=Admin;...."

AccessConn.Open

On Error GoTo CloseConnection

    With AccessData
        .ActiveConnection = AccessConn
        .Source = "SELECT DISTINCTROW dbo_GEN_STW_Name1.master_stw, ..."
        .LockType = adLockReadOnly
        .CursorType = adOpenForwardOnly
        .Open
    End With

    Worksheets("Access Table").Range("A1").Select

    For Each AccessField In AccessData.Fields
        ActiveCell.Value = AccessField.Name
        ActiveCell.Offset(0, 1).Select
    Next AccessField

    Range("A1").Select
    Range("A2").CopyFromRecordset AccessData
    Range("A1").CurrentRegion.EntireColumn.AutoFit

CloseRecordSet:
    AccessData.Close

CloseConnection:
    AccessConn.Close

End Sub

EDIT: Sorry here is the full connection string:
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password="""";User ID=Admin;Data Source=S:\ISS\CELSON\Carestream Database.accdb;Mode=Share Deny Write;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=6;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLEDB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;Jet OLEDB:Bypass ChoiceField Validation=False"


text:
Q: Filter text between two patterns with preceding n lines Assume, that we have a file like this:
l1 abcdefgh
l2 abcde
l3 some line i want to retrieve
l4 another line i want to retrieve
l5 matching pattern
l6 abc
l7 abcdef
l8 unmatching pattern
l9 blah blah

I want to retrieve the following output:
l3 some line i want to retrieve
l4 another line i want to retrieve
l5 matching pattern
l6 abc
l7 abcdef

So I want to output two lines before first occurence of matching pattern, matching line and all lines until I hit 'unmatching pattern'. Of course there can be more than one text range to retrieve.
What is the easiest way to achieve that? Which tools should I use? What to google about? Learning awk from basics is not possible at this moment.

A: In awk
{ a[i++ % 3 ]=$0}
/ matching pattern/ {print a[(i-3)%3];print a[(i-2)%3];i=0}
/matching pattern/,/unmatching pattern/ {if($0 !~ /unmatching pattern/) print }

Working here

A: awk '/pattern/{print p"\n"q"\n"$0;f=1;next} {p=q;q=$0} f{s=s"\n"$0; if ($0~/unmatching/) { print s;exit} }' file

A: In sed:
sed -n '1N;N;/pattern/{N;N;p;s/.*//;N;N;};$!D' filename


text:
Q: how can we compare data between two different tables much faster I have two different tables from two different databases. I have huge amount of data in both the tables but i do have same columns in both the tables.
When i am trying with the below code i am facing some performance issue (although it has only 2 records in employee table but in department table i have 100 000 records) comparison is taking more than 10 minutes.
Is there any way i can reduce the performance and make it faster.
EmplTbl = cur.execute("select A , B , C from EmployeeTable where EmplName in ('A','B')")
for line in EmplTbl:
    EmplData.append(line)

DeptTbl = cur.execute("select A , B , C from DeptTable")

for line in DeptTbl:
    DeptData.append(line)

for Empl in EmplData:
    DeptResult = all(Empl in DeptData for elm in DeptData)
    if DeptResult:
        print("Yes")
    else:
        print("No")

A: If the tables are almost identical it would be faster to compare hashes of chunks of data, and then only compare all the data for the chunks with a difference.
I bet most of the run time was spent transferring and transforming data.  Reading 100,000 rows from an Employee table probably only takes a few seconds in the database.  Using the function DBMS_SQLHASH.GETHASH, Oracle can quickly generate hashes for a large set of data.  (You will probably need to have a DBA run grant execute on sys.dbms_sqlhash to your_user;)
For example, imagine these two tables (in reality they are much larger, and on separate databases):
create table EmployeeTable1 as
select 1 a, 2 b, 3 c, 'abcdefg' EmplName from dual union all
select 1 a, 2 b, 3 c, 'bcdefg'  EmplName from dual union all
select 1 a, 2 b, 3 c, 'cdefg'   EmplName from dual;

create table EmployeeTable2 as
select 1 a, 2 b, 3 c, 'abcdefg' EmplName from dual union all
select 1 a, 2 b, 3 c, 'bcdefg'  EmplName from dual union all
select 9 a, 9 b, 9 c, 'cdefg'   EmplName from dual;

Generate a hash for each first-letter of the employee names.
--Table 1 hashes:
select 'a', dbms_sqlhash.gethash('select a,b,c,EmplName from EmployeeTable1 where EmplName like ''a%'' order by 1,2,3', 3) from dual union all
select 'b', dbms_sqlhash.gethash('select a,b,c,EmplName from EmployeeTable1 where EmplName like ''b%'' order by 1,2,3', 3) from dual union all
select 'c', dbms_sqlhash.gethash('select a,b,c,EmplName from EmployeeTable1 where EmplName like ''c%'' order by 1,2,3', 3) from dual;

a   923920839BFE25A44303718523CBFE1CEBB11053
b   355CB0FFAEBB60ECE2E81F3C9502F2F58A23F8BC
c   F2D94D7CC0C82329E576CD867CDC52D933C37C2C <-- DIFFERENT

--Table 2 hashes:
select 'a', dbms_sqlhash.gethash('select a,b,c,EmplName from EmployeeTable2 where EmplName like ''a%'' order by 1,2,3', 3) from dual union all
select 'b', dbms_sqlhash.gethash('select a,b,c,EmplName from EmployeeTable2 where EmplName like ''b%'' order by 1,2,3', 3) from dual union all
select 'c', dbms_sqlhash.gethash('select a,b,c,EmplName from EmployeeTable2 where EmplName like ''c%'' order by 1,2,3', 3) from dual;

a   923920839BFE25A44303718523CBFE1CEBB11053
b   355CB0FFAEBB60ECE2E81F3C9502F2F58A23F8BC
c   6B7B1D374568B353E9A37EB35B4508B6AE665F8A <-- DIFFERENT

The Python program only has to compare the hashes, and can quickly discover that "a" and "b" are identical, and the difference is in employees that start with "c".  Then the program only has to compare all the details for a smaller set of results.
Unfortunately, this solution requires more coding, as you have to build loops in Python, and construct multiple SQL statements.  And the solution will be slower if your tables are wildly different, and you'll need to play around with the data to find the right chunk size.

A: your code seems to be doing exponentially more work than you expect.  your line:
DeptResult = all(Empl in DeptData for elm in DeptData)

is implicitly doing:
DeptResult = True
for elem in DeptData:
  for tmp in DeptData:
     DeptResult = DeptResult and Empl == tmp

i.e. you're making two nested passes over DeptData when you only need one, so it'll take len(DeptData) ** 2 operations.  which would mean you're trying to do 1e10 comparisons and it would indeed take a very long time to complete
I'd rewrite this as:
cur.execute("select A , B , C from DeptTable")
dept_entries = set(cur)

cur.execute("select A , B , C from EmployeeTable where EmplName in ('A','B')")
for empl in cur:
  if empl in dept_entries:
    print(empl, 'Yes')
  else:
    print(empl, 'No')

note that Python database connectors don't normally return results from their execute method, and you should call one of their fetch* methods or iterate on the cursor.  I don't use Oracle, but other posts suggest they should follow standards and your code is broken
putting the DeptTable into a set means that lookup is now O(1) and hence the empl in dept_entries is very cheap
note: it might be worth going over some tutorials on how tuple equality works in Python, as well as data structures like set and maybe even just basic iteration

A: Consider a pure SQL solution to avoid the multiple Python loops. Specifically, run aLEFT JOIN and test NULL matches in all three columns:
select e.A as emp_A, e.B as emp_B, e.C as emp_C,
       d.A as dept_A, d.B as dept_B, d.C as dept_C,
       case
           when not (d.A is null or d.B is null or d.C is null) then 'Yes'
           else 'No'
       end as DeptResult
from EmployeeTable e
left join DeptTable d
    on e.A = d.A and e.B = d.B and e.C = d.C
where e.EmplName in ('A', 'B')

A: pure sql.
select * from DeptResult
minus
select * from EmployeeTable

union

select * from EmployeeTable
minus
select * from DeptResult


text:
Q: if statement within double for loop: specific example I'm writing a short code which compares two dataframes- list & knownlocation. I want to know for each item in list, whether it falls within a knownlocation.
colnames(list) <- c("gene_symbol", "chromo", "start", "end")
colnames(knownlocation) <- c("snp", "chr", "s", "e")

To find this I wrote the code to make a new column in "list" saying TRUE or FALSE whether it's in any of knownlocation:
for (i in 1:nrow(list)) {
for (j in 1:nrow(knownlocation)) {
if ( (list[i, 2] == knownlocation[j, 2]) && (list[i, 3] >= knownlocation[j, 3]) && (list[i, 4] <= knownlocation[j, 4]) ) {
list[i, 5] = "TRUE" }
else { list[i, 5] = "FALSE"}
}}

This code looks fine to me and it runs with no errors. Problem is the entire list shows FALSE, even if it does fall within a location in knownlocation. Can anyone find something obviously wrong that I'm missing?

A: Issue is the else clause will overwrite with FALSE on previous instances where TRUE was found. Basically, you only want to store TRUE when condition is met, but initialize all values to FALSE prior to execution of the loop.
Try and remove the else clause.
To initialize column 5 of the list with FALSE do the following right before the the nested looping:
list$V5 = FALSE

Code:
list$V5=TRUE
for (i in 1:nrow(list)) {
  for (j in 1:nrow(knownlocation)) {
    if ( (list[i, 2] == knownlocation[j, 2]) && (list[i, 3] >= knownlocation[j, 3]) && (list[i, 4] <= knownlocation[j, 4]) ) {
      list[i, 5] = "TRUE" }
}


text:
Q: Yarn Install packages over proxy - trouble with your network I'm having a issue with proxy on my work, I've already added proxy config and can run yarn commands such serve.
Now this is a new problem I'm facing, I can't npm install or even yarn install, what should I do to install?
Edit: --network-timeout 100000 don't work.
This is what I want to use: https://www.creative-tim.com/product/vue-black-dashboard

C:\Users{my-user}\Documents\Github\vue-black-dashboard-master>yarn
install                                          yarn install v1.22.5
info No lockfile found.
[1/4] Resolving packages...
info There appears to be trouble with your network connection.
Retrying...                                              info There
appears to be trouble with your network connection. Retrying...
info There appears to be trouble with your network connection.
Retrying...                                              info There
appears to be trouble with your network connection. Retrying...
error An unexpected error occurred:
"https://registry.yarnpkg.com/chart.js: connect ETIMEDOUT
104.16.21.35:443".        info If you think this is a bug, please open a bug report with the information provided in
"C:\Users\{my-user}\Documents\Github\vue-black-dashboard-master\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation
about this command.

A: Try something like this npm --https-proxy=http://proxy.company.com:8080 install package.
Check out this link for more information

A: First check if 'https-proxy' exist in yarn config: yarn config list
If not, try adding a new value as follows:
yarn config set https-proxy http://proxy.myproxy.com:8080


text:
Q: How to use $firebaseArray to syncronize to particular group of child? Hi I am new to Angularfire.I have database structure as follow,
--+User
  |
  +---+record1
  |   |
  |   +item1
  |
  +---+record2
  |   |
  |   +item2
  |
  +---+record3
  |
  |
  +...

For a user I need to track many record say 3 records for a user. I need to change the $firebaseArray dynamically for every user.
This is what I have tried until now,
$scope.citem=$firebaseArray( firebase.database().ref('user/record1'));

$scope.citem.push($firebaseArray( firebase.database().ref('user/record2'))[0]);

Here I tried to get the path record1 and record2 but my result is pointing to item1 and item2. Am I wrong someway.Is there some other way?Can someone please help me


text:
Q: How to predict translations (decode) for IBM models in nltk? I'm fairly new to the NLTK API and wanted to get started with the simplistic IBM Model 1, which does word-level translations. This is what I did so far, with the help of the NLTK API documentation.
from nltk.translate.ibm1 import IBMModel1
from nltk.translate import AlignedSent

def get_text(filename):
    senteces = []
    with open(filename,'r') as f:
        for sentence in f:
            sentences.append(sentence.split())
    return sentences

src_sentences = get_text('source.txt')
trg_sentences = get_text('target.txt')

bitext = []
for i in range(len(src_sentences)):
    bitext.append(AlignedSent(src_sentences[i], trg_sentences[i]))

ibm1 = IBMModel1(bitext, 5)

Now that IBMModel1 has been created, I'm unsure how to perform the decoding, ie. predicting translations from a test set. I can't seem to find this on the documentation as well.
In simple words, I want to obtain a predicted translation, given a random source sentence using this model. How do I achieve this?

A: See these examples at https://www.nltk.org/api/nltk.translate.ibm1.html#nltk.translate.ibm1.IBMModel1
>>> bitext = []
>>> bitext.append(AlignedSent(['klein', 'ist', 'das', 'haus'], ['the', 'house', 'is', 'small']))
>>> bitext.append(AlignedSent(['das', 'haus', 'ist', 'ja', 'groß'], ['the', 'house', 'is', 'big']))
>>> bitext.append(AlignedSent(['das', 'buch', 'ist', 'ja', 'klein'], ['the', 'book', 'is', 'small']))
>>> bitext.append(AlignedSent(['das', 'haus'], ['the', 'house']))
>>> bitext.append(AlignedSent(['das', 'buch'], ['the', 'book']))
>>> bitext.append(AlignedSent(['ein', 'buch'], ['a', 'book']))

>>> ibm1 = IBMModel1(bitext, 5)

>>> print(ibm1.translation_table['buch']['book'])


text:
Q: Javascript function not defined and SyntaxError? HTML:
<html>
<body>
    <button onclick="bgTime()">CHANGE BACKGROUND</button>
</body>
    <script type="text/javascript" src="script.js">
    </script>
</html>

JavaScript:
function bgTime() {
    var d = new Date();
    if (d getHours() >= 21) {
        document.body.style.backgroundImage = "url('bg/H.png')"
    }
    else if (d getHours() >= 18) {
        document.body.style.backgroundImage = "url('bg/G.png')"
    }
    else if (d getHours() >= 15) {
        document.body.style.backgroundImage = "url('bg/F.png')"
    }
    else if (d getHours() >= 12) {
        document.body.style.backgroundImage = "url('bg/E.png')"
    }
    else if (d getHours() >= 9) {
        document.body.style.backgroundImage = "url('bg/D.png')"
    }
    else if (d getHours() >= 6) {
        document.body.style.backgroundImage = "url('bg/C.png')"
    }
    else if (d getHours() >= 3) {
        document.body.style.backgroundImage = "url('bg/B.png')"
    }
    else {
        document.body.style.backgroundImage = "url('bg/A.png')"
    };
};

Okay so I am probably just being an idiot somehow, but I cannot find what I am doing wrong. I get two errors:
 1. "script.js:3 | Uncaught SyntaxError: Unexpected identifier"
 2. "(index):3 | onclick | Uncaught ReferenceError: bgTime is not defined "
Can someone please tell me what I am doing wrong? Thank you in advance!

P.S. This is just a project for learning JS, don't judge lol.

A: Write
d.getHours()

getHours is a method of d which is accessed using the dot ..

A: You forgot a period. It should be:
d.getHours() >= 21 et cetera. :)

A: You need to use dot notation on all of your if statements:
if (d.getHours() >= 21) { ... }

bgTime is not defined because the JS interpreter can't decode your program. Once you fix your ifs, everything should work fine.

References:

*

*MDN Property Accessors Documentation


text:
Q: File append issue for an SFTP producer - Apache Camel I am trying to append the data to a file which is in SFTP server using Apache Camel SFTP component but data is not appending to the file in SFTP server rather it is creating a new file. I am using this file append in split component. Below is the small snippet used to transfer the data. Any suggestions please?
<to uri="sftp://{{rue.sftp.username}}@{{rue.sftp.host}}:{{rue.sftp.port}}/{{rdx.FileLocation}}?password={{rue.sftp.password}}&fileName=${exchangeProperty.failedFileName}&fileExist=Append" />


text:
Q: How to monitor unexpected shutdowns of my application on windows I have an executable that i created in python.
This executable is supposed to always run in the background silently and send information to the server.
I distribute this executable to many clients.
Sometimes the server stops receiving information from a client for some unexpected reason.
I would assume that the executable stopped running for some reason on the clients computer.
I would like to monitor why I have unexpected shutdowns on the executable.
How should i monitor these unexpected shutdowns?
A solution using windows service for me is not acceptable because of administrative issues for some of the clients.

A: See this answer to a previous question:
https://superuser.com/questions/461546/run-a-python-script-in-background-and-restart-it-on-crash
Basically it says:
#!/bin/bash
until myscript.py; do
    echo "'myscript.py' crashed with exit code $?. Restarting..." >&2
    sleep 1
done

Then just start the monitor script in background:
nohup monitor.sh &
end quote
If these scripts are running on remote machines adjust the monitor script to send yourself an email, notifying you of the error.


text:
Q: Kohana 3.2 error ErrorException [ Fatal Error ]: Class 'Model_Categories' not found
MODPATH/orm/classes/kohana/orm.php [ 37 ]
32  public static function factory($model, $id = NULL)
33  {
34      // Set class name
35      $model = 'Model_'.ucfirst($model);
36
37      return new $model($id);
38  }
39
40  /**
41   * "Has one" relationships
42   * @var array

im keeping on having this error... i have no idea how to fix it.
after i uploaded it to the shared host, i keep getting this error
i already checked for the following:
1. changed .htaccess RewriteBase and made it
RewriteBase /

2. Also changed bootstrap.php base_url to "/"
3. Checked Model_Categories and it is visibile in the directory
i dont know the error

A: Make sure the file that contains "Model_Categories" is called "categories.php" (lowercase) and is in "application/classes/model"
Windows file system is case insensitive but Linux is not which might explain why it works on your machine but not on the remote host.

A: exists class / model / categories ? Pay attention to uppercase and lowercase letters in name of file.


text:
Q: Как во Vue.js получать значение из input не используя v-model? Есть такой пример. При нажатии на кнопку "добавить заметку" идёт проверка не пустой ли input и добавляется блок  с ведённым в input текстом. Как сделать этот же пример не используя v-bind так как он не работает в framework7?
Как взять значение из инпут во vue?
Пытался как-то так сделать но не работает
let getCat = document.getElementByClassName('inputCat').value;
let newCat = this.getCat;
this.cats.push(this.newCat);
this.newCat = '';
this.saveCats();

Работающий пример с v-model
  <f7-block v-for="(cat, n) in cats">
      {{ cat }}
      <f7-button fill color="red" @click="removeCat(n)">Удалить</f7-button>
  </f7-block>

    <f7-list form>
        <f7-list-input
          class="inputCat"
          v-model="newCat"
          type="text"
          placeholder="Заметка"
        ></f7-list-input>
        <f7-button fill color="blue" @click="addCat">Добавить заметку</f7-button>
    </f7-list>

export default {
data() {
    return{
        cats:[],
        newCat: null
  }
},
mounted() {
  if (localStorage.getItem('cats')) {
    try {
      this.cats = JSON.parse(localStorage.getItem('cats'));
    } catch(e) {
      localStorage.removeItem('cats');
    }
  }
},
methods: {
  addCat() {
    // убедиться, что было что-либо введено
    if (!this.newCat) {
      return;
    }
    this.cats.push(this.newCat);
    this.newCat = '';
    this.saveCats();
  },
  removeCat(x) {
    this.cats.splice(x, 1);
    this.saveCats();
  },
  saveCats() {
    const parsed = JSON.stringify(this.cats);
    localStorage.setItem('cats', parsed);
  }
}
}

A: f7-list-input не обычный input, а div с вложенным input
let getCat = document.querySelector('.inputCat input').value;


text:
Q: How can I determine why a jQuery ajax $.post request wasn't successful? I'm trying to determine, based on the result of this call, if it was successful. The successFunction doesn't get called, so I'm assuming it was not. How do I know what went wrong?
xmlRequest = $.post("/url/file/", { 'id' : object.id }, successFunction, 'json');

Do I use the xmlRequest object?

A: You can use:
$.ajax({
    url:"/url/file/",
    dataType:"json"
    data:{ 'id' : object.id }
    error:function(request){alert(request.statusText)}
    success:successFunction
})

A: You could use the $.ajaxComplete() and/or $.ajaxError() methods to attach function to those events.  I would also recommend using the Firefox browser with the Firebug pluging, you can get a lot of information about the requests and responses.


text:
Q: Difference between super and this while calling a function in sub class in js

class A {
  data1 = 1;
  constructor(){
    this.data2 = 2;
  }
  test() { console.log(this) }
}
class B extends A {
  constructor() {
    super();
  }
  funcA() { this.test() }
  funcB() { super.test() }
}
let foo = new B()
foo.funcA();
foo.funcB();

what's the difference between funcA() and funcB() while calling, or they are exactly the same thing?
BTW, what's the difference between data1 and data2 declared in and out the constructor, which is preferred

A: With this.test(), you reference the instance. No test property exists directly on the instance, so as with standard prototypal inheritance, the prototype object is examined for the property. This prototype is A.prototype, which does have a test property, so that gets called.
With super.test(), you instead start looking for the test property on the superclass - A.prototype, which is found immediately and called.
If you had a test method on B as well, you'd see the difference.

class A {
  data1 = 1;
  constructor(){
    this.data2 = 2;
  }
  test() { console.log('a') }
}
class B extends A {
  constructor() {
    super();
  }
  test() {
    console.log('b');
  }
  funcA() { this.test() }
  funcB() { super.test() }
}
const foo = new B()
foo.funcA();
foo.funcB();

BTW, what's the difference between data1 and data2 declared in and out the constructor, which is preferred

It's up to you. Though, class fields (assigning outside of the constructor) are slightly more concise (especially if your constructor doesn't contain anything else) but less supported - if you want to use them, make sure to transpile your code.


text:
Q: Translating strings python script is it possible to translate strings of a Python script?
Example: from English to Italian or from English to Francais...
Another detailed example:
print("My string")

English user will see My string while an Italian will see La mia stringa and a Francais user will see Ma corde
Thanks

A: Solved with Gettext, thanks to Ignacio Vazquez-Abrams.
I followed this guide to understand how to use this module.


text:
Q: Using array page name together with page id to deregister script If I use this:
if (is_page(array(blabla-test-page, 20726, 20720, 38881))) {wp_deregister_script( 'gdsr_script' );
}

the blabla-test-page looks like it overrides different pages, even if certain pages have not the same body class.
For example: the page with id 5555 has no body class blabla-test-page, but for some reason, it deregisters this script too... If I remove blabla-test-page and change it to the ID number it has, 5555 will not be affected... How can this be happening? How should I use page name and page id together?
FYI: in the codex, it says is_page( array( 42, 'about-me', 'About Me And Joe' ) ), but when I do this, the page-named class won't deregister the scripts. I think that this is very weird.


text:
Q: Need a Regular expression to validate comments in the webpage Need a regular expression to check if webpage has special characters in the comments field.
Comments should only have characters,numbers and  @ = - ' " . i inside the comments.
I am using C#.net to check it
THis is the code I have and it does not work
 if (!Regex.IsMatch(comments.Text,@"^[a-zA-Z''-'\s]$"))
 {
     lblError.Text = "Please Check your Comment.";
     return false;
 }

A: Try this:
[a-zA-Z0-9@=\-'"]+

A: You are checking if the comment contains only one character because of the interval between ^ and $. Just remove them and if I remember correctly what Regex.IsMatch does, it should work.
Regex.IsMatch(comments.Text,@"[^a-zA-Z''-'\s]")
On a side note, perhaps you should allow numbers, too.
Oh, and I should note that it will return true if any other character than those indicated is found.

A: The regex should be something like @"[^\w\s''-'@\"]"
\w gives you the alphabetic characters (including accented character), numeric characters and the underscore
\s gives you the whitespace
(I escaped the ", but it may or may not be needed.  It's a little after 3am and I'm a little fuzzy, so you may need to play with that a bit...)


text:
Q: probability that at least $n$ first events are a success A game consists of jugling a ball by touching the ball on the screen. The score is the number of jugles. So if $p$ is the probability of touching the ball at the right moment so that it bouces back, what is the probability of beating your hight score $:=n$ i.e. maknig at least $n$ succssful jugles in a row?
I find the value $$\sum\limits_{k=n}^\infty\prod\limits_{m=1}^k p^m$$ because it's the union of "making m successful jugles in a row" with $m\geq n$ assuming those events are independent. Is that true?

A: Probability of getting a score $k\equiv f(k)$
$$f(k)=p^k(1-p)$$
Now you break the highscore $n$ if you do atleast $n+1$ juggles.
$$P(k>n)=\sum_{k=n+1}^\infty p^k(1-p)=\frac{p^{k+1}(1-p)}{1-p}=p^{k+1}$$


text:
Q: Creating choropleth map using OpenLayers? Is there any way to generate a chloropleth map using OpenLayers 3?
The map will contain static data that is stocked in a JSON variable.
The map will be published like the picture below:

A: Here is an example for OpenLayers 4 (not 3!):
getStyle = function (feature, resolution) {
    if (feature.get('my_attribute') < 10) {
        return new ol.style.Style({
            fill: new ol.style.Fill({
                color: [255, 0, 0, 0.5] // semi-transparent red
            })
        });
    }
    // else if ...
    else {
        return new ol.style.Style({
            fill: new ol.style.Fill({
                color: [255, 255, 0, 0.5] // semi-transparent yellow
            })
        });
    }
};

my_layer = new ol.layer.Vector({
    source: /* source definition here */,
    style: function (feature, resolution) {
        return getStyle(feature, resolution);
    }
});

The general approach is to define a function which returns the style or the fill color value depending on the value of a specified feature attribute.


text:
Q: Локальное хранилище в PHP (как в JS - localStorage) Доброго времени суток!
Подскажите пожалуйста, есть ли в PHP такая же или схожая функция как и в JS - localStorage (где можно хранить данные, текст, массивы)
Не использую SESSION и COOKIE так как создаю Бота для Сообщества во ВКонтакте, и как я уже убедился, ВК не хранит Куки, и из за этого при каждом новом вызове скрипта - новая сессия получается (надеюсь понятно объяснил..)
MySQL не хочу использовать - так как не вижу смысла для такого типа данных (всего массив из 2 ключей и значений), поэтому хотелось бы  что то встроенное из PHP, если есть вообще такая возможность

A: Для меня это Новость, но как оказалось, в PHP есть встроенная функция SQLite3 -> это та же mysql, на сколько я понимаю, но к ней не нужно подключаться по сети (она работает локально), это огромный плюс в некоторых случаях, думаю это именно то что я и искал. Отклик должен быть очень быстрым, вроде..)
https://www.php.net/manual/ru/book.sqlite3.php


text:
Q: How to use multiple versions of unison on one system? I have two machines. One with unison v. 2.40 (Debian Jessie) and a new one (Debian Stretch) where I installed package unison-all, which brought in unison versions 2.32, 2.40 and 2.48. However, I was unable to make my 2.40 work against the new machine, since it only presented v. 2.48. No matter what I do, I get:
expected "Unison 2.40\n" but received "Unison 2.48\n\000\000\000\000\017",

I worked around the issue by removing unison-all and installing v. 2.40 explicitly, but I wonder what to do if I ever want to use two concurrent versions of unison on this machine.

A: I just ran into this problem myself, and it took quite a bit of searching to find the answer! So here it is, and it works for me.
To use multiple versions of unison, install unison-all. Then...
Using multiple versions of Unison on the client
Choose a specific version to run by appending the version number, like so:
unison-2.40 ...

Or, if you want to run the latest version, you can simply type:
unison

Using multiple versions of Unison on the server
Instruct the client version of Unison to invoke the matching version of Unison on the server using the -addversionno tag, like so:
unison -addversionno

For futher details
and if you still get an
Fatal error: Received unexpected header from the server

see this solution.


text: Q: Embed SymmetricDs for CDC (Change Data Capture ) Is it possible to embed Symmetric Ds for CDC operations ? If yes how can I do that ? If no is there other open source tools that can be embedded for CDC ? Other than kafka and Debezium ?


text:
Q: XSD to MySQL Schema I need to convert an XML to a MySQL DB Schema.
I have been able to generate the XSD from the XML. Now i want to use the XSD to generate the DB schema in MySQL or PostgreSQL. Can anyone tell me how can i do this or point to any tools which i can use for this?

A: There is a command-line tool called XSD2DB, that generates database from xsd-files, available at sourceforge.
For more info: please refer to this existing question How can I create database tables from XSD files?


text:
Q: Updating values of ENUM in java I have one ENUM and I am updating those enum value from database on initialization of application. And then using that enum all-over application.
The reason to do so is that if Value need to change from database then just add that value in property table and update it, so that on initialization enum values got updated else enum default value will be working.
Example :
I have this enum :
public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    private void setMass(double mass) { this.mass = mass; }
    private void setRadius(double radius) { this.radius = radius; }

}

And I update values of Enum with set methods.
I would like to know whether doing this is correct or not. What is the right way to do for such scenarios?

A: Java enums mutability usecases and possibilities?
i would not advise you to make enum values mutable, they should almost always be finalized.

A: Enum constants are singleton and immutable objects can be used all over the application and mass and radius
fields cannot be changed on the fly according to database updates.
Instead, in-memory cache can be created to store mass and radius values and this internal Map can be refreshed on every database update. But if you need to make your application more scalable, then you have to use external cache such Redis to store PlanetStats objects instead in internal Map.
enum Planet {
    MERCURY,
    VENUS,
    EARTH
}

class PlanetStats {
    private final double mass;
    private final double radius;

    PlanetStats(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public double getMass() {
        return mass;
    }

    public double getRadius() {
        return radius;
    }
}

class PlanetCache {

    private final Map<Planet, PlanetStats> stats = new ConcurrentHashMap<>();

    // can be invoked on database update for each Planet object change
    public void refresh(Planet planet, PlanetStats planetStats) {
        stats.put(planet, planetStats);
    }

    // can be invoked to fetch PlanetStats for specified Planet
    public PlanetStats getPlanetStats(Planet planet) {
        return stats.get(planet);
    }
}

A: For an update with a setter the fields should not be final.
That is all. Other arguments are moot. If you have a final range of named values, an enum is fine.
An immutable class (with final fields) would have been better, but not achievable with a database unless with a static initialisation. Needing a database during initialisation may be acceptable, but in general should be avoided when possible and when it is not an embedded database.

A: Even if you can change the state of an enum -  I would not recommend it.
Enums are singletons and this means that

*

*your state changes should be thread-safe, because one thread might use the enum while another changes it's state.

*the state is not serialized like the state of other objects. If you use serialization, either direct or through another framework or technology like RMI or springs remoting, the state changes will not work as you might expect.
E.g.
public static void main(String[] args) {
    Planet mercury = Planet.MERCURY;

    mercury.setMass(1.0);

    byte[] mercurySerialized = SerializationUtils.serialize(mercury);

    mercury.setMass(2.0);

    Planet mercuryDeserialized = SerializationUtils.deserialize(mercurySerialized);

    System.out.println(mercuryDeserialized.mass());
}

It prints
2.0

The mass property of the deserialized Planet doesn't have the value that the Planet had when it was serialized.
I also discuss this in my blog Singleton implementation pitfalls in the section serialization bypass.
PS: I use SerializationUtils from commons-lang3


text:
Q: How to replace Softmax ouput Layer with Logistic Layer in Tensorflow? I need a bit help in my work. Right now, I am using Softmax layer as output layer for classification scores in neural network. But, I need to replace Softmax layer with logistic layer on the output layer. I have some inputs that belongs to multiple classes. Softmax is showing probability over all the classes and assigned the class to the highest probability and its hard to decide a threshold to predict more than one classes at a time. While in case of logistic function each neuron will display a number between (0-1) and I can decide a threshold in that case.
Here is my code:
2 layer Network Initialization
# Parameters
training_epochs = 10#100
batch_size = 64
display_step = 1
batch = tf.Variable(0, trainable=False)
regualarization =  0.009

# Network Parameters
n_hidden_1 = 250 # 1st layer num features
n_hidden_2 = 250 # 2nd layer num features

n_input = model.layer1_size # Vector input (sentence shape: 30*10)
n_classes = 12 # Sentence Category detection total classes (0-11 categories)

#History storing variables for plots
loss_history = []
train_acc_history = []
val_acc_history = []

# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])

#Strings
trainingString = "\n\nTraining Accuracy and Confusion Matrix:"
validationString = "\n\nValidation set Accuracy and Confusion Matrix:"
testString = "\n\nTest set Accuracy and Confusion Matrix:"
goldString = "\n\nGold set Accuracy and Confusion Matrix:"

# Create model
def multilayer_perceptron(_X, _weights, _biases):
    #Single Layer
    #layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1']))
    #return tf.matmul(layer_1, weights['out']) + biases['out']

    ##2 layer
    #Hidden layer with RELU activation
    layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1']))
    #Hidden layer with RELU activation
    layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2']))
    return tf.matmul(layer_2, weights['out']) + biases['out']

# Store layers weight & bias
weights = {
    ##1 Layer
    #'h1': w2v_utils.weight_variable(n_input, n_hidden_1),
    #'out': w2v_utils.weight_variable(n_hidden_1, n_classes)

    ##2 Layer
    'h1':  w2v_utils.weight_variable(n_input, n_hidden_1),
    'h2':  w2v_utils.weight_variable(n_hidden_1, n_hidden_2),
    'out': w2v_utils.weight_variable(n_hidden_2, n_classes)
}

biases = {
    ##1 Layer
    #'b1': w2v_utils.bias_variable([n_hidden_1]),
    #'out': w2v_utils.bias_variable([n_classes])

    ##2 Layer
    'b1': w2v_utils.bias_variable([n_hidden_1]),
    'b2': w2v_utils.bias_variable([n_hidden_2]),
    'out': w2v_utils.bias_variable([n_classes])
}

# Construct model
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
#learning rate
# Optimizer: set up a variable that's incremented once per batch and
# controls the learning rate decay.
learning_rate = tf.train.exponential_decay(
    0.02*0.01,                # Base learning rate.
    batch * batch_size,  # Current index into the dataset.
    X_train.shape[0],    # Decay step.
    0.96,                # Decay rate.
    staircase=True)

#L2 regularization
l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])

#Softmax loss
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))

#Total_cost
cost = cost+ (regualarization*0.5*l2_loss)

# Adam Optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost,global_step=batch)

 # Initializing the variables
 init = tf.initialize_all_variables()

 print "Network Initialized!"

How we can modify this network to have a probability in between (0-1) on each output Neuron?

A: just change line:
# Construct model
pred = multilayer_perceptron(x, weights, biases)

To
# Construct model
model pred = tf.nn.sigmoid(multilayer_perceptron(x, weights, biases))


text:
Q: Extend .NET TreeView CheckBox I have a .NET TreeView control with checkboxes on the leaves. I want to be able to get the value of the node when a checkbox is selected. Basically, this is a tree of email contacts and when the user selects a checkbox I want to pull the node value (email address) and place that in a text box. The second part is no problem, I'll just call a JS function to append the email to the text box.
So, the issue is how to extract the node's value from the checkbox with JS. Unless someone has an alternate method, I was thinking about extending the TreeView to not include a normal checkbox but rather one that can store a value. Note: I have an existing control called CheckBoxValue that will do exactly this. Fundamentally, my question is how can I extend the TreeView to include this? I believe this would be in the CreateChildControls method but would love some help.
Any ideas?
Thanks,
Ryan

A: If the  value you are trying to store is a string then you could use TreeNode.Value to store it. Here's an example you could refer to.
 <asp:TreeView ID="TreeView1" runat="server"  onclick=" __doPostBack('','');"
        ontreenodecheckchanged="TreeView1_TreeNodeCheckChanged">
    </asp:TreeView>

and to load the tree
        if (!IsPostBack)
        {
            TreeNode node = new TreeNode("RootNode");
            TreeView1.Nodes.Add(node);

            TreeNode childNode = new TreeNode("ChildNode");
            childNode.ShowCheckBox = true;
            childNode.Value = "foo@bar.com";
            node.ChildNodes.Add(childNode);
        }

and the check CheckChanged event handler
    protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
    {
        TextBox1.Text = e.Node.Value;
    }


text:
Q: Jquery .append and appendto() sadness I need to append the following HTML fragment into a document, substituting a value for the display_spinner param:

    <object class="tableauViz" width="654" height="1469" style="display:none;">
        <param name="host_url" value="http%3A%2F%2Fpublic.tableausoftware.com%2F"
        />
        <param name="site_root" value="" />
        <param name="name" value="AnalyticsIncJavaScript/AnalyticsInc" />
        <param name="tabs" value="no" />
        <param name="toolbar" value="yes" />
        <param name="static_image" value="tableau.russellchristopher.org:81/Background.gif"
        />
        <param name="animate_transition" value="yes" />
        <param name="display_static_image" value="yes" />
        <param name="display_spinner" value="" id="display_spinner" />
        <param name="display_overlay" value="yes" />
        <param name="display_count" value="yes" />
    </object>

Here's what I've come up with (JSFiddle here: http://jsfiddle.net/9vBGq/ )
$(document).ready(function () {
    var $placeholder = $('

'),
        $noscript = $(' '),
        $tableauViz = $('<object class="tableauViz" width="654" height="1469"></object>'),
        $host_url = $('<param name="host_url" value="http%3A%2F%2Fpublic.tableausoftware.com%2F">'),
        $site_root = $('<param name="site_root" value="" />'),
        $sheetName = $('<param name="name" value="AnalyticsIncJavaScript/AnalyticsInc" />'),
        $tabs = $('<param name="tabs" value="no" />'),
        $toolbar = $('<param name="toolbar" value="yes" />'),
        $static_image = $('<param name="static_image" value="http://tableau.russellchristopher.org:81/Background.gif"/>'),
        $animate_trasnsition = $('<param name="animate_transition" value="yes" />'),
        $display_static_image = $('<param name="display_static_image" value="yes" />'),
        $display_overlay = $('<param name="display_overlay" value="yes" />'),
        $display_count = $('<param name="display_count" value="yes" />'),
        $display_spinner = $('<param name="display_spinner" value="' + 'no' + '" />');
    $placeholder.append($noscript).append($tableauViz).append($host_url).append($site_root).append($sheetName).append($tabs).append($toolbar).append($static_image).append($animate_trasnsition).append($display_static_image).append($display_overlay).append($display_count).append($display_spinner).appendTo('body');
    console.log(document.body);
});

From what I can see in my console.log, there are multiple problems - and I'm still too new to this stuff to know exactly why:

*

*The URL Encoding in my
 looks munged. What did I do wrong?

*The  tag nested inside the noscript block looks bad

*There is a closing </object> tag when it should close after I list my params

*Closing /> on each my my params is missing- again URL encoding
strangeness, I assume but not sure how to handle.

I suspect you pros and kick me in the right direction in a couple of seconds....please kick me as you see fit? Thanks.

A: I think the best solution would be to create a template in your html and read that instead of making it in javascript..
Something like

then you need this code to load the template and change the placeholder
var template = $('#tableau').html(),
    filledTemplate = template.replace('{placeholder}','value for spinner');

$('body').append( filledTemplate );

Demo at http://jsfiddle.net/gaby/9vBGq/1/
(I have removed the noscript element from the template since everything is done through script)

A:
The URL Encoding in my  looks munged. What did I do wrong?

You ended the style too early. Remove the quotes from the background image url.
var $placeholder = $('

')

There is a closing  tag when it should close after I list my params

It already closed itself. What you did was append params to $placeholder, not $tableauViz  You should append stuff to it if you want them in it.
$tableauViz.append(stuff).append(some_more_stuff)

Closing /> on each my my params is missing- again URL encoding strangeness, I assume but not sure how to handle.

The console ignores the /> during display. It's perfectly fine, they are all siblings to each other. If it weren't, each param would have been nested in the previous.

Regarding the , test it by turning off your JS. That way you can see it if it rendered properly or not.


text:
Q: Is it normal that JavaScript can create otherwise invalid DOM? Somewhat by accident, I found out that a span inserted directly inside a tbody stays in place when done with JavaScript (insertBefore), where such invalid DOM would if created with literal HTML lead to the span being placed before the entire table.
I expected either the same behaviour as with literal HTML or some DOM Exception being thrown.
E.g. this HTML

Table Header

        from HTML → goes up

Table Contents

with this JavaScript:
var span = document.createElement('span'),
    tbody = document.querySelector('tbody');
span.innerHTML = 'Created with JS → stays in place';
tbody.insertBefore(span, tbody.querySelector('tr'));

renders "Created with JS → stays in place" between the header and the first row; the original, literal, span moves outside of the table.
Is this normal, and can/should I count on this? (It behaves the same in FF, Chrome, Opera, IE >= 9 (not tested below)).
Also, is there a way to query the DOM whether content of a certain type would (under normal circumstances) be valid at a certain point in the DOM? This is actually what I wanted to do when I found out about this quirk (which it is, imho).
The fiddle is here: http://jsfiddle.net/xr37g9kw/2/

A: As for "is this normal, and can/should I count on this?" Sadly, yes. But mostly you should be aware of the node types you are working with. NB, in case of table, there are a handful of not so well known DOM methods (HTMLTableElement.rows. InsertRow() and so on).
As for "is there a way to query the DOM whether content of a certain type would (under normal circumstances) be valid at a certain point in the DOM?" nothing built-in for this exact purpose, but you could exploit one native feature of JavaScript -> DOM API: you can let browser to re-parse HTML chunk in the "literal way". Yes, I am speaking about innerHTML.
In your fiddle, adding**tbody.outerHTML = tbody.outerHTML** "fixes" the structure, so you could hypothetically take some DOM node, look at its DOM tree, clone, "re-eval" it and compare with original.

A: Yes, that is the default behavior, as you saw. It's not valid HTML of course as you can check here http://www.freeformatter.com/html-validator.html if you input the HTML.


text:
Q: ViewModel Properties in Query String are not bound when arriving at Controller I'm working in an ASP.net MVC application, and I have a table of products as shown in the screenshot:

I would like the ability to filter that table of products, and I'd like the filtering to happen via the query string params (as a GET) so that the URL can be shared.
The ViewModel for the page is like this:
public class InventoryReportViewModel
{
  public SearchViewModel Search { get; set; } // 2 string props [Type and Term]
  public IEnumerable<ProductViewModel> Products { get; set; }
  public PaginationViewModel Pagination { get; set; } // 3 int props [currentPage, recordsPerPage, totalRecords]
}

I'm using Razor helpers to draw the filter inputs, like this:
@Html.EditorFor(m => m.Search.Term, new { htmlAttributes = new { @class = "form-control" } })

And also I've set up my form to use GET like so:
@using (Html.BeginForm("Inventory", "Report", FormMethod.Get))
{
   // form elements
}

My ReportController.cs has the following method that is relevant to my question here:
public ActionResult Inventory(string SearchTerm, string SearchType, int page = 1)
{
  var viewModel = _reportService.GetProducts(page, SearchTerm, SearchType);
  return View(viewModel);
}

When I pass a Search term, and click the Filter Results button, I do arrive at my Controller method above, but the SearchTerm and SearchType are null.
I know how to "hack" this to work, for example, if I do this:
<input type="text" name="SearchTerm" class="form-control"/>

Then the search term I input would be picked up by the Controller, but is there no other way?

A: since you already made a viewmodel for Search
public SearchViewModel Search { get; set; }

you just need to pass it to the controller like this
public ActionResult Inventory(SearchViewModel Search, int page = 1
{
  var viewModel = _reportService.GetProducts(page, Search.Term, Search.Type);
  return View(viewModel);
}

you were getting null because the textboxes were named as Search.Term that is why it was not matching the parameters.

A: The form should be post
@using (Html.BeginForm("Inventory", "Report", FormMethod.Post))
{
  // form elements
}

This can also be cleaner:
@Html.EditorFor(m => m.Search.Term, new { htmlAttributes = new { @class = "form-control" } })

to
@Html.EditorFor(m => m.Search.Term, new { @class = "form-control" } )

Another question,
In the razor view, do you have a model specified on the first line?


text:
Q: Magento2: CRON Job is scheduled but Not Running I have created a Cron job followed this question Installed the Extension and check it from admin back it says the job is pending.  Below is the screenshot and my code in detail, Please let me know if I am doing wrong anywhere.

All jobs are in a pending state for a very long time.

app\code\Autosynch\synchProduct\etc\corntab.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="custom_AutoSynch_cronjob" instance="Autosynch\synchProduct\Page\Service" method="execute">
            <schedule>10 * * * *</schedule>
        </job>
    </group>
</config>

I need to run this below Code.

app\code\Autosynch\synchProduct\Controller\Page\Service.php

<?php
namespace Autosynch\synchProduct\Controller\Page;
use Magento\Framework\HTTP\Client\Curl;

class Service extends \Magento\Framework\App\Action\Action {
        /**
        * @param \Magento\Framework\App\Action\Context $context
        * @param \Magento\Framework\HTTP\Client\Curl $curl
        */
        protected $_curl;

        public function __construct(
            \Magento\Framework\App\Action\Context $context,
            Curl $curl
        )
        {

            parent::__construct($context);
            $this->_curl =$curl;
        }
         /**
         * Send SMS
         * @param type $mobile_no
         * @param type $body
         */
        public function getMyCurlResponse($url)
        {
          //$url = urlencode($url);
          $this->_curl->get($url);
          $response = $this->_curl->getBody();

         return $response;
        }

        public function myPostCallResponse(){
            $ch = curl_init();
            $url = "http://api.geonames.org/citiesJSON";
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, "north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=jb1234");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $data = curl_exec($ch);
            $resultArray = json_decode($data)->geonames;

            //print_r($data);

            foreach ($resultArray as $key => $value) {
                # code...
                echo " City : ".$value->toponymName.", \n";
            }

            die();
        }

        public function execute()
        {
            //$priceCheck = 'http://alaincopheadofficen-2.fortiddns.com:555/webservices/getupdates.php';

            $priceCheck = 'http://alaincopheadofficen-2.fortiddns.com:555/webservices/getupdates.php';

             $result = $this->getMyCurlResponse($priceCheck);

             $resArray = json_decode($result)->result;

             foreach ($resArray as $key => $value) {
                 # code...
                //echo " SKU: ",$value->sku,", name: ",$value->name,", Price: ",$value->price, ", Qty: ",$value->qty,". \n";

                $product_id = $value->sku;
                $price = $value->price;
                $qty = $value->qty;
                 echo " \n\n in check for update Method SKU: ", $product_id,", Price: ", $price, ", Qty: ",$qty;
                 $this->updateProduct($product_id, $price, $qty);
             }

        }

        public function updateProduct($product_id, $price, $qty1){

 // echo "in Update Product",$product_id,", price : ",$price, ", Qty : ",$qty1,"";
       ini_set('max_execution_time', 0);
       $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
       $objectManager = $bootstrap->getObjectManager();
       $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
       $state = $objectManager->get('\Magento\Framework\App\State');
       $state->setAreaCode('frontend');
       $storeId = '1'; //Store ID
       //$product = $objectManager->get('catalog/product');

       $productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
        //$product = $productFactory->create()->setStoreId($storeId)->load($product_id);
       $product = $productFactory->create();
       $prduct_id_sku = $product->load($product->getIdBySku($product_id));
       //echo "in Update Product method : ", pro;

       $oldprice = $product->getPrice();
       $productName = $product->getName();

      // echo "Product Name:", $productName, ",\n Product ID:",$product->getId(),", SKU: ",$prduct_id_sku->getSku()," ";

    //   echo ",\n product Quantity: ",$prduct_id_sku->getStockItem();

            // $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
            // echo $stock->getQty();
               $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');

               $oldstock = $StockState->getStockQty($product->getId());
         //echo $StockState->getStockQty($product->getId());//, $product->getStore()->getWebsiteId());
         //echo $StockState->getStockQty(1);
         //$StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId())
         //$product->getStore()->getWebsiteId()->suggestQty("101");
         //$Product->

         //$StockState->save();

        // echo " \n Current price is : ", $oldprice;

         if ((($oldprice != $price) || $oldstock != $qty1 ) && $oldstock) {

          $product->setPrice($price);

         // echo ",\n new price Updated ",$price;

          if ($oldstock != $qty1) {
            $product->setStockData(array(
                    'use_config_manage_stock' => 0,
                    'manage_stock' => 1,
                    'is_in_stock' => 1,
                    'qty' => $qty1 ));
            //$product->setStockData(['qty' => $qty1, 'is_in_stock' => 1]);
        $product->setQuantityAndStockStatus(['qty' => $qty1, 'is_in_stock' => 1]);

           // echo " \n Updated Stock:";
           // print_r($product->getStockData()['qty']);
          }else{
            //echo " \n oldStock & new stock are equal ".$qty;

          }

          $product->save();

        }else {
          //echo " \n oldprice & new price are equal ".$price;
        }

        unset($storeIds, $websiteObj, $_websiteId);
        unset($product);

        }
}

A: Try this :
You can run CRON by this command: php bin/magento cron:run by terminal or cmd. Even you can configure CRON in server by ssh using crontab -e command. Maybe you will need root user of server you can learn about Magento 2 CRON configuration from here : Magento 2 cron.
You can check CRON successful run or not from cron_schedule database table. You can check CRON status by this command on the server : sudo service cron status.

A: Create the cron job
To create a cron job for the Magento file system owner, enter the following command as a user with root privileges:
crontab -u <Magento file system owner user name> -e

For example,
crontab -u magento_user -e

A text editor displays. (You might need to choose a text editor first.)
\* * * * * <path to php binary> <magento install dir>/bin/magento cron:run | grep -v "Ran jobs by schedule" >> <magento install dir>/var/log/magento.cron.log

\* * * * * <path to php binary> <magento install dir>/update/cron.php >> <magento install dir>/var/log/update.cron.log

\* * * * * <path to php binary> <magento install dir>/bin/magento setup:cron:run >> <magento install dir>/var/log/setup.cron.log

where
<path to php binary> is the absolute file system path to your PHP binary
<magento install dir> is the directory in which you installed the Magento software; for example, /var/www
| grep -v "Ran jobs by schedule"

Reference


text:
Q: How to solve a simple boundary value problem for TISE on python I am trying to solve the TISE for an infinite potential well V=0 on the interval [0,L]. The exercise gives us that the value of the wavefunction and its derivative at 0 is 0,1 respectively. This allows us to using the scipy.integrate.odeint function in order to solve the problem for a given energy value.
The task is to now find the energy eigenvalues given the further boundary condition that the wavefunction at L is 0, using a root finding function on python. I have done some research and could only find something called the 'shooting method' which I cannot figure out how to implement. Also, I have come across the solve BVP scipy function, however I can't seem to understand what exactly goes in the second input for this function (boundary condition residuals)
m_el   = 9.1094e-31      # mass of electron in [kg]
hbar   = 1.0546e-34      # Planck's constant over 2 pi [Js]
e_el   = 1.6022e-19      # electron charge in [C]
L_bohr = 5.2918e-11      # Bohr radius [m]

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def eqn(y, x, energy):              #array of first order ODE's
    y0 = y[1]
    y1 = -2*m_el*energy*y[0]/hbar**2

    return np.array([y0,y1])

def solve(energy, func):           #use of odeint
    p0 = 0
    dp0 = 1
    x = np.linspace(0,L_bohr,1000)
    init = np.array([p0,dp0])
    ysolve = odeint(func, init, x, args=(energy,))
    return ysolve[-1,0]

The method here is to input eqn as func in solve(energy,func). L_bohr is the L value in this problem. We are trying to numerically find the energy eigenvalues using some scipy method

A: For all the other solvers in scipy the argument order x,y, and even in odeint one can use this order by giving the option tfirst=True. Thus change to
def eqn(x, y, energy):              #array of first order ODE's
    y0, y1 = y
    y2 = -2*m_el*energy*y0/hbar**2

    return [y1,y2]

For the BVP solver you have to think of the energy parameter as an
extra state component with zero derivative, thus adding a third slot
in the boundary conditions. Scipy's solve_bvp allows to keep it as parameter,
so that you get 3 slots in the boundary conditions, allowing to fix the first derivative at x=0 to select one non-trivial solution from the eigenspace.
def bc(y0, yL, E):
    return [ y0[0], y0[1]-1, yL[0] ]

Next construct an initial state that is close to the suspected ground state and call the solver
x0 = np.linspace(0,L_bohr,6);
y0 = [ x0*(1-x0/L_bohr), 1-2*x0/L_bohr ]
E0 = 134*e_el

sol = solve_bvp(eqn, bc, x0, y0, p=[E0])
print(sol.message, "  E=", sol.p[0]/e_el," eV")

and then produce the plot
x = np.linspace(0,L_bohr,1000)
plt.plot(x/L_bohr, sol.sol(x)[0]/L_bohr,'-+', ms=1)
plt.grid()

The algorithm converged to the desired accuracy.   E= 134.29310361903723  eV


text:
Q: Haar classifier for segmenting lips I have tried building my own Haar for segmenting out lips. But I have not achieved very good results. Can I get any Haar for lips segmentation just like the one we have for eyes. I searched the internet for such haar but couldn't find one.
My aim is to find if my mouth is widely open or closed.
If no one has done such haar. I will build one and opensource it.

A: If there are no Haar cascades in the OpenCV distribution that currently implement how to segment out lips, consider building your own.  Take a look at the guide to building Haar cascades from the OpenCV project for more details:
http://docs.opencv.org/trunk/doc/user_guide/ug_traincascade.html
I am assuming you already have positive and negative examples of what you want to classify, and so you can build your own cascades using your own ground truth data.  The above guide will get you started on creating your own Haar cascades.
NB: I am usually against deferring people to external links without some sort of closure in my posts, but the process to do this is quite involved, and I can't invest the effort in repeating that information here.

A: This will help u in matlab use Viola-Jones algorithm
vision.CascadeObjectDetector System object
Detect objects using the Viola-Jones algorithm
Description
The cascade object detector uses the Viola-Jones algorithm to detect people's faces, noses, eyes, mouth, or upper body. You can also use the Training Image Labeler to train a custom classifier to use with this System object. For details on how the function works, see Train a Cascade Object Detector.


text:
Q: POP / IMAP server under attack : what risks and how to secure? Since yesterday (7am), our POP server is under a dictionnary attack : this is what I found in /var/log/mail.log :
Mar 26 10:31:36 serv pop3d: LOGIN FAILED, user=monday, ip=[::ffff:91.121.**.***]
Mar 26 10:31:41 serv pop3d: Disconnected, ip=[::ffff:91.121.**.***]
Mar 26 10:31:41 serv pop3d: Connection, ip=[::ffff:91.121.**.***]
Mar 26 10:31:41 serv pop3d: LOGIN FAILED, user=monica, ip=[::ffff:91.121.**.***]
Mar 26 10:31:46 serv pop3d: Disconnected, ip=[::ffff:91.121.**.***]
Mar 26 10:31:46 serv pop3d: Connection, ip=[::ffff:91.121.**.***]
Mar 26 10:31:46 serv pop3d: LOGIN FAILED, user=monroe, ip=[::ffff:91.121.**.***]
Mar 26 10:31:51 serv pop3d: Disconnected, ip=[::ffff:91.121.**.***]
Mar 26 10:31:51 serv pop3d: Connection, ip=[::ffff:91.121.**.***]
Mar 26 10:31:51 serv pop3d: LOGIN FAILED, user=montana, ip=[::ffff:91.121.**.***]
Mar 26 10:31:56 serv pop3d: Disconnected, ip=[::ffff:91.121.**.***]

The IP leads to an agency serv. We warned them their security seams broken, and they answer they were aware of that and they were working on it.
But since yesterday 22pm, the IP changes and the new dosen't lead to anything. The IP seems to be blacklisted on some servers (TornevallNET, Spamhaus and CBL_AbuseAt).
Before it was on try each 5 seconds, now it's every second :
Mar 27 00:00:57 serv pop3d: Connection, ip=[::ffff:176.61.***.***]
Mar 27 00:00:58 serv pop3d: LOGIN FAILED, user=info, ip=[::ffff:176.61.***.***]
Mar 27 00:00:59 serv pop3d: Maximum connection limit reached for ::ffff:176.61.***.***
Mar 27 00:00:59 serv pop3d: Maximum connection limit reached for ::ffff:176.61.***.***
Mar 27 00:01:00 serv pop3d: LOGOUT, ip=[::ffff:176.61.***.***]
Mar 27 00:01:00 serv pop3d: Disconnected, ip=[::ffff:176.61.***.***]
Mar 27 00:01:01 serv pop3d: LOGOUT, ip=[::ffff:176.61.***.***]
Mar 27 00:01:01 serv pop3d: Disconnected, ip=[::ffff:176.61.***.***]
Mar 27 00:01:01 serv pop3d: Connection, ip=[::ffff:176.61.***.***]
Mar 27 00:01:01 serv pop3d: Maximum connection limit reached for ::ffff:176.61.***.***

And then they start the same thing on imap :
Mar 27 00:07:08 serv imapd: Connection, ip=[::ffff:176.61.***.***]
Mar 27 00:07:09 serv imapd: LOGIN FAILED, user=web, ip=[::ffff:176.61.***.***]
Mar 27 00:07:09 serv imapd: Disconnected, ip=[::ffff:176.61.***.***], time=6
Mar 27 00:07:09 serv imapd: Connection, ip=[::ffff:176.61.***.***]

That seems to have stop 25 minutes later, the IP changes again, and now, its :
Mar 27 10:20:01 serv postfix/smtpd[10390]: connect from localhost[127.0.0.1]
Mar 27 10:20:01 serv postfix/smtpd[10390]: lost connection after CONNECT from localhost[127.0.0.1]
Mar 27 10:20:01 serv postfix/smtpd[10390]: disconnect from localhost[127.0.0.1]
Mar 27 10:22:33 serv imapd: Connection, ip=[::ffff:88.190.***.**]
Mar 27 10:22:33 serv imapd: Disconnected, ip=[::ffff:88.190.***.**], time=0

Why is it still connexions from a stranger IP on our server ?
On our web production server, we don't use POP or IMAP, but SMTP with postfix. Relay is on our DNS provider.
What's happening ?
Thanks by advance and sorry for my english.

A: Sorry I need to add an answer because I still can't add comments. But Whatever you do you will ALWAYS have another IP address spamming you and brute forcing you. Best thing to do is block them and hope you don't have user admin with 1234 as a password. I've been through that with my Imap server. I feel your pain. But as Michael said, Welcome to the Internet. cheers

A: The risk of having a system compromised depends all on the security policies you have in place and how effective these are against your attackers.
If you have strong password policies, account lockouts (after a certain amount of unsuccessful logon attempts), source tracking (i.e. locking out IP addresses that send a large volume of unsuccessful authentication request to your server) and auditing in place you won't have much to worry about.
On the other hand, if you do not have these measures in place, you might be too late now to close it down and you should evaluate the risk & damage this could cause to your business. If the risk is too high to take, take the system offline, secure it and plug it back in. Securing a non-compromised system is always easier than recovering a compromised system.

A: Have you considered using secured versions for IMAP/POP3? While it won't stop attempts like this, because they are on different ports other than 110 and 143, it might "help".
Unless you have a huge user base, it might be easier to simply move port 110 and 143 to some non standard port numbers.  This is a piss poor solution honestly as it doesn't address any security concerns.  But it would likely work for small groups unless you have a big crew who can go around and reconfigure all the end user mail clients.
Or if you know where your users are connecting from, limit the connections to POP3 and IMAP to those subnets.


text:
Q: Can a CSV in a text variable be COPY-ied in PostgreSQL For example, say I've got the output of:
SELECT
$text$col1, col2, col3
0,my-value,text
7,value2,string
0,also a value,fort
$text$;

Would it be possible to populate a table directly from it with the COPY command?

A: Sort of. You would have to strip the first two and last lines of your example in order to use the data with COPY. You could do this by using the PROGRAM keyword:
COPY table_name FROM PROGRAM 'sed -e ''1,2d;$d'' inputfile';

Which is direct in that you are doing everything from the COPY command and indirect in that you are setting up an outside program to filter your input.


text:
Q: How to make a method that checks if a number is mixed with 1 odd digit and the other even digit i am new to java  and i built a method that checks if a number has following digits that 1 is odd or even and the followed digit is the opposite.
for example if a the number is 12121 the method supposed to return true;
here's the code
public static boolean isMix(int x)
{
    String s = Integer.toString(x);
    int counter = 0;

    for (int i = 0, j = 1; i < s.length() || j < s.length(); i++, j++)
    {
        if (Integer.parseInt("" + s.charAt(i)) % 2 == 0&& Integer.parseInt("" + s.charAt(j)) % 2 == 1
                || (Integer.parseInt("" + s.charAt(i)) % 2 == 1 && Integer.parseInt("" + s.charAt(j)) % 2 == 0))
            counter++;
    System.out.println(counter);
    }
    if (s.length() == counter)
        return true;

    return false;
}

A: You can simply return false if the parity of the current digit is the same as the previous digit.
public static boolean isMix(int x){
    String s = Integer.toString(x);
    for(int i = 1; i < s.length(); i++){
        if(Character.getNumericValue(s.charAt(i)) % 2
           == Character.getNumericValue(s.charAt(i - 1)) % 2) return false;
    }
    return true;
}


text:
Q: What's the equivalent of AndAlso (&&) and OrElse (||) logical operators in Python? In .NET VB and C#, we can use AndAlso (&&), OrElse (||) for logical operations
How about in Python, what is the equivalent logical operators? are they only limited to 'and' and 'or'?
Updated: Below is the difference between And/Or and AndAlso/OrElse
Quoted from https://stackoverflow.com/a/8409488/719998

Or/And will always evaluate both1 the expressions and then return a
  result. They are not short-circuiting evaulation.
OrElse/AndAlso are short-circuiting. The right expression is only evaluated if the outcome cannot be determined from the evaluation
  of the left expression alone. (That means: OrElse will only evaluate
  the right expression if the left expression is false, and AndAlso will
  only evaluate the right expression if the left expression is true.)

A: Python already does this:
def foo():
    print ("foo")
    return True

def bar():
    print ("bar")
    return False

print (foo() or bar())
print ("")
print (bar() or foo())

Returns:
foo
True

bar
foo
True

There is no need for AndAlso or OrElse in Python, it evaluates boolean conditions lazily (docs).

A: In python, you can use logic gates.
You can use either, for instance, and or &.
https://docs.python.org/2/library/stdtypes.html#bitwise-operations-on-integer-types


text:
Q: How to use RestSharp with OAuth? I am confused which factory OAuth1Authenticator factory method should I use. I think I should get a consumer secret token (can I get it with RestSharp?), then use OAuth1Authenticator.ForRequestToken, then obtain access token and secret access token(how?), then use OAuth1Authenticator.ForAccessToken and use the return value from this point forward.
But it seems that RestSharp is architectured to use the only one authenticator and I can't seem to find a way from a cold start (having only app token) to having all the necessary credentials (consumer key and secret, access key and secret).
Bonus questions:

*

*What .ForClientAuthentication and .ForProtectedResource methods are for?

*Why OAuth2Authenticatior is in a different namespace from OAuth1Authenticator?

A: OAuth 1 is multi-step, so you have to use a different static method each step of the way. There's an example here: https://github.com/restsharp/RestSharp/blob/master/test/RestSharp.IntegrationTests/OAuth1Tests.cs


text:
Q: Is return needed in JavaScript functions that do not return anything In JavaScript, I understand that return will both return some output a function may produce and stop the execution of that function.
My question is about those cases where the function doesn't return anything. It only performs something.
I primarily use JavaScript within the context of React and React Native so my examples are in React Native.
First example is a function that simply removes something from AsyncStorage. I typically use this when a user signs off. Do I need return in this case?
export const removeAuthData = async () => {
   return await AsyncStorage.removeItem('auth');
}

Another example is when I have a function that may update the state in my app:
setIsAuthenticated(value) {
   this.props.actions.setIsAuthenticated(value);
}

In these scenarios, do I need to use return in my functions?

A: No, in standard JavaScript, at the bottom of a function, if the return value isn't used;

*

*return is equivalent to

*return <someExpressionWithoutSideEffects>, which is equivalent to

*nothing at all (no return statement at the end)

Note that for those using TypeScript, things are a bit different - using the return keyword indicates that you really are trying to transfer a value from the function to its caller, in which case return or return undefined is not quite the same as lacking a return statement at all.

A: Since JavaScript is a weakly typed language, the return type and value of the function are entirely dependent on the value of the return.
Of course, if you don't plan on using the returned values of the functions, it doesn't matter whether you return it or not. Still, it may be a stylistic choice to return the last statement or not.
Lastly, if you return the result of an expression with value undefined, then it's completely indistinguishable, without looking at the body of the function, whether you actually returned or not.
TL;DR: Not needed, but up to stylistic choice and preference.

A: You don't have to return a value from a function.
Note that functions do have a default return value which is undefined.


text:
Q: browser to get machine-id by launching an electron app or similar I want to identify a user by unique machine id across all browsers. So came up with an idea of launching a app which determines the machine-id (like electron using nodejs) and passes back the info to the browser that launched it and use for identifying the user.
I have seen something like this been done on canyourunit
Can anyone point me right direction where can i find some info about this kind of approach.

A: As you would be asking a user to download and execute native code, electron or whatever else, there are several complicated issues to consider.
The obvious first one is that you must consider the user platform (OSX, Windows, Linux...) then, communicating back with the browser directly (which one?) is probably not practical.
Your native application could however send the machine id/fingerprint to your backend so you could identify what web client is what.
This is quite involved, fragile, and even if you only support Windows, will fail in many scenarios (system policies, firewalls, antivirus, proxies, strange network setups...)
All in all, it would seem that you should consider more standard Device fingerprinting techniques if you only need an ID.


text:
Q: Cygwin function "settitle" I was checking the .bashrc file that is installed by Cygwin and I found with a commented function named settitle:
settitle ()
{
   echo -ne "\e]2;$@\a\e]1;$@\a";
}

I would like to know what exactly does this function.

A: It sets the title of your terminal emulator window to its arguments.

A: It changes the title of your window by outputting a special string, called an escape sequence. Read (a lot) more about ANSI escape sequences on Wikipedia, on the Bash Prompt HOWTO and at the ANSI escape sequence reference.


text:
Q: How to import empty strings as null values from CSV file - using pgloader? I am using pgloader to import from a .csv file which has empty strings in double quotes. A sample line is

12334,0,"MAIL","CA","","Sanfransisco","TX","","",""

After a successful import, the fields that has double quotes ("") are shown as two single quotes('') in postgres database.
Is there a way we can insert a null or even empty string in place of two single quotes('')?
I am using the arguments -
WITH truncate,
           fields optionally enclosed by '"',
           fields escaped by double-quote,
           fields terminated by ','
SET client_encoding to 'UTF-8',
           work_mem to '12MB',
           standard_conforming_strings to 'on'

I tried using 'empty-string-to-null' mentioned in the documentation like this -
CAST column enumerate.fax using empty-string-to-null

But it gives me an error saying -

pgloader nph_opr_addr.test.load An unhandled error condition has been
  signalled: At LOAD CSV
^ (Line 1, Column 0, Position 0) Could not parse subexpression ";"
  when parsing

A: Use the field option:
null if blanks

Something like this:
...
having fields foo, bar, mynullcol null if blanks, baz

From the documentation:

null if
This option takes an argument which is either the keyword blanks or a double-quoted string.
When blanks is used and the field value that is read contains only space characters, then it's automatically converted to an SQL NULL value.
When a double-quoted string is used and that string is read as the field value, then the field value is automatically converted to an SQL NULL value