text:
Q: TokBox Controller / Model Ruby UPDATE: I have solved the NilClass issue! Thanks!
Now I am having a problem with:
unknown attribute 'sessionId' for Room.

SOLVEDI am currently having some issues where my code is telling me I have an error of "undefined method `create_session' for nil:NilClass" on line 9. I will provide the files.
This is the specific line:
   @new_room = Room.new(strong_param)

rooms_controller.rb
class RoomsController < ApplicationController
require "opentok"
before_filter :config_opentok,:except => [:index]
  def index
    @rooms = Room.where(:public => true).order("created_at DESC")
    @new_room = Room.new
  end

def create
  session = @opentok.create_session :media_mode => :routed
  params[:room][:sessionId] = session.session_id

  @new_room = Room.new(strong_param)

  respond_to do |format|
    if @new_room.save
      format.html { redirect_to("/party/"+@new_room.id.to_s) }
    else
      format.html { render :controller => 'rooms', :action => "index" }
    end
  end
end

def party
  @room = Room.find(params[:id])

  @tok_token = @opentok.generate_token @room.sessionId
end

  private
  def config_opentok
    if @opentok.nil?
     @opentok = OpenTok::OpenTok.new ########, "#########################################"
    end
  end
    def strong_param
      params.require(:room).permit(:name,:sessionId)
  end
end

rooms.rb (Models)
class Room < ActiveRecord::Base
end

I've tried several different modifications to these files to make my program work. I can get the listing page to work but once I try and actually create a new room, I receive this error message.
Look forward to any advice you can provide.

A: You are missing the before_filter :config_opentok,:except => [:index] line from the blog post in your previous post (https://railsfornovice.wordpress.com/2013/01/01/video-chatting-in-ruby-on-rails/)


text:
Q: double summation absolute convergence I'm trying to prove or disprove the absolute convergence of the sum $\sum_\limits{k,l=1}^{\infty}\frac{k-l}{k^4+l^4} $.
Every series that I found that bounds the absolute values of my original series from above diverges and every series that bounds it from below converges, so I'm stuck with respect to the comparison test.

A: We have that
$$ S := \sum_{k,l = 1}^{\infty} \frac{|k-l|}{k^4 + l^4} = \sum_{n=2}^{\infty} \sum_{k,l;\, k+l=n} \frac{|k-l|}{k^4 + l^4} \le \sum_{n=2}^{\infty} n \sum_{k,l;\, k+l=n} \frac{1}{k^4 + l^4}.$$
Now, notice that for any $a, b \in \mathbb{R}$ we have $(a + b)^2 \le 2a^2 + 2b^2$. Iterating,
$$ (a+b)^4 \le [2a^2 + 2b^2]^2 = 4(a^2 + b^2)^2 \le 8(a^4 + b^4).$$
Hence, we can write
$$ S \le \sum_{n=2}^\infty n  \sum_{k,l;\, k+l=n} \frac{8}{(k+l)^4} = 8\sum_{n=2}^\infty \frac{1}{n^2} < \infty.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to see the tab bar controller in Interface Builder I created a Tab Bar Application in XCode. Then I clicked on MainWindow.xib. In the document window there is a Tab Bar Controller. When you double-click on the window icon, the window is shown. Shouldn't something similar occur if you double-click on the Tab Bar Controller icon?

A: Controllers don't have any useful visual representation. You can hit Cmd-1 to view the attributes of the object. What would you expect a tab bar controller to look like? If you're talking about viewing the actual tab bar, that should be present in your window, and can be created by dragging a tab bar from the library.


text:
Q: Spring Boot + Security : unable to serve static page : Request method 'GET' not supported Built a web app using spring boot 1.5.6 with spring security (security-core 4.2.3). Getting below error when accessing the app root. Ideally acc to documentation it should serve the index page on context root, but getting this error.
2018-10-31 18:58:31.879  WARN 5536 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound             : Request method 'GET' not supported
2018-10-31 18:58:31.880  WARN 5536 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
Security Config is below,
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/token").permitAll();
    http.authorizeRequests().antMatchers("/").permitAll();
    http.authorizeRequests().antMatchers("/api/**").authenticated().and().exceptionHandling()
            .authenticationEntryPoint(entryPoint).and().authorizeRequests().antMatchers(HttpMethod.OPTIONS)
            .permitAll().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .addFilterAt(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("app/token");
    web.ignoring().antMatchers("/");
}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.temp.am</groupId>
<artifactId>app</artifactId>
<version>1.0.0</version>
<!-- For deployment comment the JAR packaging, disable CORS at class -->
<packaging>war</packaging>
<!-- <packaging>jar</packaging> -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
</parent>
<properties>
    <project.build.sourceEncoding>Cp1252</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <tomcat.version>8.0.15</tomcat.version>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <compilerVersion>1.8</compilerVersion>
                <fork>true</fork>
            </configuration>
        </plugin>

    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.3.0</version>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
    </dependency>

    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.6.0</version>
    </dependency>
</dependencies>

Properties spring.mvc.view.prefix=WEB-INF/
spring.mvc.view.suffix=.html
According to doc any static content in /public or /static or /resource should render as we hit application root in a browser. Also, I have noticed Authentication filter (custom filter extending AbstractAuthenticationProcessingFilter) is called twice by spring, first: VirtualFilterChain, second: ApplicationFilterChain. I not am sure why Authentication filter is placed in both FilterChains : originalFilter as well as additionalFilters. I have tried my best to go through stackoverflow answers and spring documentation: went through doc many times to see if I am missing any configuration.


text:
Q: Ionic 2 / Typescript Build Fails: Unexpected character '@' I'm having trouble with using my own typescript files that are outside of a ionic 2 project in the project. I have an auth module that I would like to use and it's just not working. I'm not sure if it's an issue with the typescript setup or ionic.
app.module.ts
import { NgModule } from '@angular/core';
import {IonicApp, IonicModule} from 'ionic-angular';
import { MyApp } from './app.component';
import { LoginComponent } from './login/login.component';
import {AuthModule} from "../../../web/src/shared/services/auth/auth.module";

@NgModule({
    declarations: [
        MyApp,
        LoginComponent
    ],
    imports: [
        IonicModule.forRoot(MyApp),
        AuthModule
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        LoginComponent
    ],
    providers: [
    ]
})
export class AppModule {}

tsconfig.json
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": true,
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["dom", "es2015"]
  },
  "exclude": ["node_modules"],
  "compileOnSave": false,
  "atom": { "rewriteTsconfig": false }
}

auth.module.ts
import {NgModule} from "@angular/core";
import {HttpModule} from "@angular/http";
import {IdentityService} from "./identity.service";
import {IdentityEventService} from "./identity-event.service";
@NgModule({
    imports: [HttpModule],
    providers: [
        IdentityService,
        IdentityEventService
    ]
})
export class AuthModule {
}

I get the following error:
[14:34:24]  bundle failed: Unexpected character '@' (5:0) in ..../web/src/shared/services/auth/auth.module.ts
So it appears as if it's finding the package but choking on the NgModule declaration. If I remove the reference to the auth.module, it works. I've added all of the packages that the auth module needs to my ionic project's package.json file so references shouldn't be an issue.
Let me know if there's any more relevant information that is needed to debug this.

A: Im making my first ionic2 app and had the same issue. I found that when i imported my providers(which were marked  @injectable) to app.module.ts , they were imported as '../authservice.ts' etc instead of '../authservice'. Check if thats the case and remove .ts ..  im on ionic 2.1.0

A: @lincoln comment to @jayraparla answer has saved my day...
I have executed this on my Ionic2 RC1 project...
$ grep -r \\.ts src/

... and I have found something like this in my AppModule generated by my IDE's automatic imports
import { mySubcomponent } from "./_path_/mySubcomponent.ts"

With ".ts",
$ ionic serve

executes without errors, but after DELETE ".ts", and make other changes in my code as described here, I can execute again too
$ ionic build android

I hope this can help someone.


text:
Q: Trying to show an activity indicator in a custom cell in iOS 7 I had a custom cell defined in a xib file where I later place an UIActivityIndicatorView programmatically in a view controller. This was correctly working for iOS 6 and earlier, but I'm not able to see the activity indicator in iOS 7.
I'm doing this way: I firstly register the nib in the view controller's viewDidLoad
[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"customCell"];

Then, in cellForRowAtIndexPath: and if system version is 7.0 or above, I do:
        UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activityIndicator.frame = CGRectMake(259, 21, activityIndicator.frame.size.width, activityIndicator.frame.size.height);
        [cell.contentView addSubview:activityIndicator];

But, as I said, the activity indicator is not shown. Subviews in iOS7 are supposed to be added to cell's contentView, am I missing anything else?
Thanks

A: Try with this, change the activity indicator color as clear color before animating.
[self.activityIndicator setBackgroundColor:[UIColor clearColor]];
[self.activityIndicator startAnimating];

Even its not working,then try to uncheck Animating behavior in attributes inspector in IB

A: i belive you have created  cell by using interface builder i.e "Customcell" in your case. but added activity indicator by coding in "cellForRowAtIndexPath" which is wrong. Try creating activity indicator using interface builder which is easy and hide it if necessary in "cellForRowAtIndexPath"

A: Use [cell.contentView.view addSubview:activityIndicator] instead.


text:
Q: Vertically centered images with Bootstrap in thumbnail and grid I want vertically centered images with Bootstrap inside an grid class and in thumbnail class. The thumbnail classes should be same height. And the paragraph should be at the same level below the images.
Have tried everything possible and on the Internet search I have not found a suitable solution that works. Examples there are only images with grid or images with thumbnail, but not in combination with grid and thumbnail.
Does anyone have a solution to my problem?

Some Text

Some Text

Some Text

Some Text

That doesn't work!
.thumbnail{
    display: inline-block;
    vertical-align: middle;
}

A: The parent element containing .thumbnail must have display:table; for vertical-align: middle; to work. Best-practice is to use a
 layout and assign vertical-align to elements you want aligned middle vertically, such as:
table, tbody, thead, th, tr, td, td table {
  padding: 0;
  margin: 0;
  vertical-align: middle;
}
td, th {
  display: table-cell;
  vertical-align: inherit;
}

td elements (or .thumbnail in your case) should be display: table-cell; inside the display:table; element.
Note that line-height value assigned to the parent element also has an effect when using vertical-align: middle; on it's children.
I would not advise using top: 50%; transform: translateY(-50%); as suggest above by others, it's simply not best-practice.


text:
Q: How to run unittest in parallel? I have been looking for a bit and I can not find a way to run unittest's in parallel is there a library that gives you the same output but runs the tests in parallel?

A: The pytest testing framework has a plugin called pytest-xdist that runs tests in parallel.
Note that:

pytest supports running Python unittest-based tests out of the box.


text:
Q: Update Jenkins with selected plugins I have got a update for Jenkins, current version (Jenkins ver. 2.89.3) to (2.107.2). That includes the update on ansible plugin, which i dont want to do it because the latest version of ansible plugin is not compatible to my environment. How to upgrade Jenkins excluding that particular ansible plugin changes
OS: Rhel7
current version:Jenkins ver. 2.89.3

A: In my environment, updating Jenkins application doesn't automatically update your plugins. You'd have to update your plugins in the settings options.
Also, my Jenkins instance is configured using tomcat & nginx reverse proxy.


text:
Q: Rails 2.0.5 with AJAX form error Below code still do not work ajax. How can I fixed it?
Using link_to_remote in my project is being okay but form_remote_tag using ajax is just do as normally and do not work ajax. Please Help me. I am using Rails 2.0.5 and Ruby 1.8.6.
<% form_remote_tag(:url => url_for(:action => :create001), :update => "stantdard1") do %>

                Target

                 <%= text_area_tag :target %>

    <%= submit_tag "save"%>
    <% end %>

A: Solved above error by using below code because Rails can't call ajax even using form_remote_tag. Then need to write ajax code in javaScript.


text:
Q: 2 ROWS FOR AN ITEM IN SQL QUERY RESULTS WHEN EXPECTING 1 ROW I want to query all ACTIVE rows in table A but if in Table B, there is an ACTIVE row for column ITEM where the TRACKING_FL is Y and the LOCATION is MAIN, then I want the value of the tracking_fl, cost, and location from Table B.  There should only be one row in the results per item.
If the values for a row in Table B are not present, then there should be a one row with values from Table A.
The problem is if the criteria pertaining to Table B is true then I get two rows in the results, one with the values from Table B and one from Table A.
Current vs Desired results are outlined below.  Create Table and Insert statements for sample data is outlined below.  Thank you in advance for assistance!
CURRENT CODE:
SELECT
    A.ITEM,
    A.DESCRIPTION,
    CASE WHEN B.LOCATION='MAIN' AND B.ACTIVE_STATUS='A' AND B.TRACKING_FL='Y' THEN B.TRACKING_FL ELSE 'N' END AS TRACKING_FL,
    CASE WHEN B.LOCATION='MAIN' AND B.ACTIVE_STATUS='A' AND B.TRACKING_FL='Y' THEN B.COST ELSE A.PRICE END  AS AMOUNT,
    CASE WHEN B.LOCATION='MAIN' AND B.ACTIVE_STATUS='A' AND B.TRACKING_FL='Y' THEN B.LOCATION  ELSE A.VENDOR END  AS SOURCED
FROM
    TABLE A A
LEFT JOIN
    TABLE B ON A.ITEM = B.ITEM
WHERE
    A.ACTIVE_STATUS= 'A'

CURRENT RESULT:

ITEM
DESCRIPTION
TRACKING_FL
AMOUNT
SOURCED

SO948
LABEL IV 1X3 CHANGE ON WED
N
92.5
ACME

SO948
LABEL IV 1X3 CHANGE ON WED
Y
6.75
MAIN

SO944
LABEL FOR HANDHELD IN LAB ONLY
N
350.2
ACME

SO944
LABEL FOR HANDHELD IN LAB ONLY
Y
8.23
MAIN

SO910
HEADSET W/6 FT CORD
N
25.99
CDW

29965
HCG CC 5 ELECSYS
N
35.39
ACME

EXPECTED RESULT:

ITEM
DESCRIPTION
TRACKING_FL
AMOUNT
SOURCED

SO948
LABEL IV 1X3 CHANGE ON WED
Y
6.75
MAIN

SO944
LABEL FOR HANDHELD IN LAB ONLY
Y
8.23
MAIN

SO910
HEADSET W/6 FT CORD
N
25.99
CDW

29965
HCG CC 5 ELECSYS
N
35.39
ACME

CREATE TABLE and INSERT statements:
CREATE TABLE A (
ITEM    CHAR(32 BYTE)   No      1,
DESCRIPTION CHAR(30 BYTE)   No      2,
VENDOR  CHAR(35 BYTE)   No      3,
PRICE   NUMBER(10,0)    No      4,
ACTIVE_STATUS   CHAR(1 BYTE)    No      5
);

INSERT INTO TABLE A
(ITEM, DESCRIPTION, VENDOR, PRICE, ACTIVE_STATUS)
VALUES
('SO948','LABEL IV 1X3 CHANGE ON WED','ACME',92.5,'A')

INSERT INTO TABLE A
(ITEM, DESCRIPTION, VENDOR, PRICE, ACTIVE_STATUS)
VALUES
('SO944','LABEL FOR HANDHELD IN LAB ONLY','ACME',350.2,'A')

INSERT INTO TABLE A
(ITEM, DESCRIPTION, VENDOR, PRICE, ACTIVE_STATUS)
VALUES
('SO910', 'HEADSET W/6 FT CORD', 'CDW',25.99,'A')

INSERT INTO TABLE A
(ITEM, DESCRIPTION, VENDOR, PRICE, ACTIVE_STATUS)
VALUES
('29965', 'HCG CC 5 ELECSYS','ACME', 35.39, 'A')

INSERT INTO TABLE A
(ITEM, DESCRIPTION, VENDOR, PRICE, ACTIVE_STATUS)
VALUES
('12346', 'HGLOVE SM EXAM', 'ACME', 19.99, 'I')

CREATE TABLE B (
ITEM    CHAR(32 BYTE)   No      1,
TRACKING_FL CHAR(1 BYTE)    No      2,
COST    NUMBER(10,0)    No      3,
LOCATION    CHAR(5 BYTE)    No      4,
ACTIVE_STATUS   CHAR(1 BYTE)    No      5
);

INSERT INTO TABLE B
(ITEM, TRACKING_FL, COST, LOCATION, ACTIVE_STATUS)
VALUES
('SO948'    ,'Y',6.75,'MAIN','A');

INSERT INTO TABLE B
(ITEM, TRACKING_FL, COST, LOCATION, ACTIVE_STATUS)
VALUES
('SO944'    ,'Y',8.23,'MAIN','A');

INSERT INTO TABLE B
(ITEM, TRACKING_FL, COST, LOCATION, ACTIVE_STATUS)
VALUES
('MS1234'    ,'N',2.25,'MAIN','A');

INSERT INTO TABLE B
(ITEM, TRACKING_FL, COST, LOCATION, ACTIVE_STATUS)
VALUES
('MS5398'    ,'Y',9.10,'MAIN','I');

Sample table data:
TABLE A

ITEM
DESCRIPTION
VENDOR
PRICE
ACTIVE_STATUS

SO948
LABEL IV 1X3 CHANGE ON WED
ACME
92.5
A

SO944
LABEL FOR HANDHELD IN LAB ONLY
ACME
350.2
A

SO910
HEADSET W/6 FT CORD
CDW
25.99
A

29965
HCG CC 5 ELECSYS
ACME
35.39
A

12346
HGLOVE SM EXAM
ACME
19.99
I

TABLE B

ITEM
TRACKING_FL
COST
LOCATION
ACTIVE_STATUS

SO948
Y
6.75
MAIN
A

SO944
Y
8.23
MAIN
A

MS1234
N
2.25
MAIN
A

MS5398
Y
9.10
MAIN
I

A: I'm guessing, despite the sample data you shared with us, that each ITEM in TableA has two records in TableB. Working from that assumption, then I believe you want to put your TableB filters in the ON clause of your LEFT OUTER JOIN. Otherwise you will be pulling TableB records that match on the same ITEM but don't fit your criteria. Then you can change from a case expression to a COALESCE()
SELECT A.ITEM,
  A.DESCRIPTION,
  COALESCE(B.TRACKING_FL,'N') AS TRACKING_FL,
  COALESCE(B.COST,A.PRICE)  AS AMOUNT,
  COALESCE(B.LOCATION, A.VENDOR)  AS SOURCED
FROM TABLE A A
  LEFT JOIN TABLE B
    ON A.ITEM = B.ITEM
    AND B.LOCATION='MAIN' AND B.ACTIVE_STATUS='A' AND B.TRACKING_FL='Y'
WHERE A.ACTIVE_STATUS= 'A'


text:
Q: TensorFlow -Ignoring visible gpu device I have a bug
it says that its Ignoring the GPU i installed an nvidia GPU just to run my code but i dont get how this error occurs any ideas? Here's the full error:
2022-05-04 14:15:13.790089: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1892] Ignoring visible gpu device (device: 0, name: GeForce GT 610, pci bus id: 0000:01:00.0, compute capability: 2.1) with Cuda compute capability 2.1. The minimum required Cuda capability is 3.5.
2022-05-04 14:15:13.790450: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Arcomm\AI (Artificial Intelegence) Folder\face_mask_detection\src\face_mask_detection.py", line 4, in
model=load_model("./model2-009.model")
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\saved_model\load.py", line 915, in load_partial
raise FileNotFoundError(
FileNotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ./model2-009.model\variables\variables
You may be trying to load on a different device from the computational device. Consider setting the experimental_io_device option in tf.saved_model.LoadOptions to the io_device such as '/job:localhost'.


text:
Q: Creating URL shortcut for web application hosted on Azure Virtual Machine from on-premise I have a webforms application that is hosted on an Azure VM that is deployed within a virtual network on Azure. The virtual network is subsequently connected to our on-premise servers via VPN connection and we are able to access the form application from 10.101.1.5/forms
How can I create a URL redirect/alias so that when users type /webforms they will be redirected to the application at 10.101.1.5/forms. Would this need to be put in place on the server of the on-premise device or on the Azure VM

A: The alias should be on premise. The rest is just redirecting the request to 10.101.1.5 and this should directly work as both machines are on the same subnet.
Hope this helps!


text:
Q: How can i pass parameter from javascript to generic handler? I called generic handler (ashx) from javascript code as given below;
var xmlHttpReq = createXMLHttpRequest();
            xmlHttpReq.open("GET", "hndlrCars.ashx, false);
            xmlHttpReq.send(null);
            xmlText = xmlHttpReq.responseText;

But i have to pass parameter (dropdown selectedvalue) from .aspx to generic handler's "ProcessRequest" method.How can i do this?

A: You could pass it as a query string parameter:
var value = ...
xmlHttpReq.open('GET', 'hndlrCars.ashx?value=' + encodeURIComponent(value), false);

And inside the handler retrieve it from the request:
public void ProcessRequest(HttpContext context)
{
    string value = context.Request["value"];
    ...
}


text:
Q: Navigation Property Mapping on two different fields I have a squirrely situation, where in some relationships a tables ID field is used as the key reference.  But in other, older implementations, the Name field was used as the relationship mapping.
FileType:
ID | Name |....

FileTypeDetails:
ID | FileTypeId | ....

PostingGroupDetails :
FileType | ....

PostingGroupDetails.FileType has a map to FileType.Name.  FileTypeDetails.FileTypeId maps to FileType.ID.
I am using the Fluent API structure to do the mappings manually but am running into a wall with this relationship mapping.
I though that doing a multi-key mapping might work but am unsure.  Still in the design stage, and about to implement the interface side of the project.
Any ideas on how i make the mapping available to both, until we can consolidate the relationship mapping to one or the other?
EF Implementation:
FileType
I know FileType is currently Optional, but its only a direct correlation to the Table design.  I am flagging it for schema updating, currently in practice it is a required field in order for the entry to be submitted.
ToTable( "FileType" , "Int" );

HasKey( ftd => ftd.ID );
Property( ftd => ftd.ID ).HasColumnName( "ID" )
    .HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );
Property( ftd => ftd.Name).HasColumnName( "Name" )
    .IsOptional();
//Navigation Properties
HasMany( ftd => ftd.FileNames )
    .WithRequired( fn => fn.FileType );
HasMany( ftd => ftd.PostingGroupDetails )
    .WithRequired( pgd => pgd.FileTypeDetails );

FileNames
FileNames.FileTypeID relates to FileType.ID
ToTable( "FileNames" , "Int" );

HasKey( fn => fn.ID );
Property( fn => fn.ID ).HasColumnName( "ID" )
    .HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );
Property( fn => fn.FileTypeID ).HasColumnName( "FileTypeID" )
    .IsRequired();
//Navigation Properties
HasRequired( fn => fn.FileType )
    .WithMany( ftd => ftd.FileNames )
    .HasForeignKey( fn => fn.FileTypeID );

PostingGroupDetails
PostingGroupDetails.FileType relates to FileType.Name
ToTable( "PostingGroupDetails " , "Int" );

HasKey( pgd => pgd.ID );
Property( pgd => pgd.ID ).HasColumnName( "ID" )
    .HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );
//Required Properties
Property( pgd => pgd.FileType ).HasColumnName( "FileType" )
    .IsRequired();

//Navigation Properties
HasRequired( pgd => pgd.FileTypeDetails )
    .WithMany( ftd => ftd.PostingGroupDetails );

Any ideas would be greatly appreciated.  Refactoring the Database structure is not an option right now, but it is on the plate to be done.

A: Entity Framework allows for differences between the database model and the class model (or conceptual model). You can define primary keys in the conceptual model that don't exist, or aren't even constrained as unique, in the data model.
So you can (and have to) choose which fields you want to mark as PK in the conceptual model. You can only define associations to PKs that are defined in the conceptual model and there can only be one PK per entity. So for FileType you must either take ID or Name and then you can define an association with FileTypeDetails or PostingGroupDetails. For the other associations you know exist you'll have to write join queries. As in
from x in X
join y from Y on x.Name equals y.Name
select ...


text:
Q: Explain brute force algorithm I have a brute force algorithm, but never fully understood it.  I have a vague grasp of some of the things that go on, but every time I try to follow what happens exactly, I get lost (for example, the index variable is a little confusing).  Any offers on how to make the algorithm more efficient are also welcome.
Note - I already have the algorithm, and it compiles and works.  Please don't accuse me of trying to use this for malicious intent, because I haven't used it for that purpose, and I never plan to.  I just want to know how it works.
public class BruteForceTest
{
    public String username = new String();
    public static String password = "ZZZZZ";
    public static char[] charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    private static char[] currentGuess = new char[1];

public static void bruteForce()
    {
        String attempt = new String();
        Date start = new Date();
        while (true)
        {
            if (attempt.equals(password))
            {
                Date end = new Date();
                System.out.println("Password: " + attempt + "\nTotal time to crack: " + ((end.getTime() - start.getTime()) / 1000) + " seconds." + "\n");
                break;
            }
            attempt = in.toString();
            // System.out.println("Tried: " + attempt);
            in.increment();
        }
    }

    public BruteForceTest()
    {
        Arrays.fill(currentGuess, charset[0]);
    }

    public void increment()
    {
        int index = currentGuess.length - 1;
        while (index >= 0)
        {
            if (currentGuess[index] == charset[charset.length - 1])
            {
                if (index == 0)
                {
                    currentGuess = new char[currentGuess.length + 1];
                    Arrays.fill(currentGuess, charset[0]);
                    break;
                }
                else
                {
                    currentGuess[index] = charset[0];
                    index--;
                }
            }
            else
            {
                currentGuess[index] = charset[Arrays.binarySearch(charset, currentGuess[index]) + 1];
                break;
            }
        }
    }

    public String toString()
    {
        return String.valueOf(currentGuess);
    }
}

A: Brute forcing is a heuristic technique that means, essentially, you're going to try to analyze every possible scenario by taking advantage of how much faster a computer is than a human brain.  For example, you're not trying to deductively figure out the password or the next best move in a Chess game; you just test every possible situation and use the right one (or the best one according to some metric, depending on what the brute force algorithm is meant to accomplish).
Your code simply goes through all the possible values that could be held for a password and checks to see whether it has found it or not.  If it doesn't, it moves on to the next possible combination until it does.
It's also a demonstration of a worst-case scenario, since the password, being defined as ZZZZZ, will be the last thing the algorithm attempts as a solution (assuming the maximum password length is defined as five characters.)
Also, as far as you being worried that people think you're using this algorithm for malicious purposes, I wouldn't be too concerned.  Hardly any computer systems would actually be vulnerable to this kind of attack, and you would be locked out long before you ever actually happened upon a password.


text:
Q: Jquery, line in callback function doesnt wait execution I want to create a nice animation where a paragraph fade, change the content, unfade, change again and so on. the thing is the line where I set the paragraph content got executed before the fade-unfading things finished.
function displayAnim(x){
    let textBox = document.getElementById("resultBoxText");
    fadeO(textBox,x,0);
}
function fadeO(elem,x,i){
    $("#resultBoxText").fadeIn("2000",next(elem,x,i));
}

function next(elem,x,i){
    elem.innerHTML = result[x][i]; //this line got executed well, but it executed 5 times already even before the first unfade happens
    let nextI = i+1;
    if(nextI >= 6){
        $("#resultBoxText").fadeOut("2000",show(x));
        return;
    }else{
        $("#resultBoxText").fadeOut("2000",fadeO(elem,x,nextI));
    }
}

function show(x){
    let textBox = document.getElementById("resultBoxText");
    textBox.innerHTML = result[x][6] //it reach this line already. this line is supossed to be executed after the fades occur 5 times
}

what am I doing wrong?
thanks (^_^)


text:
Q: Explanation of Header Pixel in GIMP created C Header File of an XPM image In GIMP, you're able to save an image as a C header file. I did so with an XPM file, which looks like the image below:

If I were to save the XPM image as a C header file, GIMP will output this C header file.
In order to process each pixel of the given image data, the header pixel is called repeatedly. What I don't understand is what the header pixel does to process the data in the first place.
#define HEADER_PIXEL(data,pixel) {\
pixel[0] = (((data[0] - 33) << 2) | ((data[1] - 33) >> 4)); \
pixel[1] = ((((data[1] - 33) & 0xF) << 4) | ((data[2] - 33) >> 2)); \
pixel[2] = ((((data[2] - 33) & 0x3) << 6) | ((data[3] - 33))); \
data += 4; \
}

When I saw it in use in another person's code, they stated the byte order was in the wrong order and rearranged it themselves. They used it like this:
char *pixel, *data = header_data;
int i = width * height;
*processed_data = pixel = malloc(i * 4 + 1);
while(i-- > 0) {
    pixel[0] = ((((data[2] - 33) & 0x3) << 6) | ((data[3] - 33)));
    pixel[1] = ((((data[1] - 33) & 0xF) << 4) | ((data[2] - 33) >> 2));
    pixel[2] = (((data[0] - 33) << 2) | ((data[1] - 33) >> 4));
    pixel[3] = 0;
    data += 4;
    pixel += 4;
}

But that didn't really help me understand what is going on with all the bit shifting and bitwise or's and "why minus 33?" and so forth. If anyone can give an explanation on what is going on to process to the image data in the header, that would be much appreciated.
Thanks in advance!

A: Each pixel is represented by 3 bytes.  These pixels are defined as a character array, named header_data.
The problem is that not every byte is a printable character that could exist in that header file.
This is solved by only using the printable characters 33 through 97.  That gives 6 bits of information, so every four characters will give 24 bits, which can represent all permutations of 3 bytes.


text:
Q: Automatic focusing if the new window in x11 When I create a new window using x11 and XCreateSimpleWindow, I observe that the keyboard focus automatically goes onto this new window. Is there any method to prevent this auto-focusing ?

A: This is a function of your window manager.  Changing this behaviour varies from one WM to another.  Most, if not all, will behave as you describe with new windows.  If you are just wanting to do this with a specific new window that you are creating, you could try setting the type to something that wouldn't normally get focus (like _NET_WM_WINDOW_TYPE_TOOLTIP) but then you may get no decorations or anything either.  You could also look at what window currently has the keyboard focus before mapping, and then change it back after you map it.  There may be other solutions, depending on exactly what you are looking to do.


text:
Q: Compilation errors when I try to run ng serve ERROR in ./node_modules/@angular/platform-browser/fesm5/platform-browser.js 2011:15-24
"export 'ɵAPP_ROOT' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 2794:4-16
"export 'ɵLOCALE_DATA' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 2796:8-20
"export 'ɵLOCALE_DATA' was not found in '@angular/core'
ERROR in ./node_modules/@angular/platform-browser/fesm5/platform-browser.js 1876:23-38
"export 'ɵ_sanitizeStyle' was not found in '@angular/core'
ERROR in ./node_modules/@angular/forms/fesm5/forms.js 2010:28-43
"export 'ɵlooseIdentical' was not found in '@angular/core'
ERROR in ./node_modules/@angular/forms/fesm5/forms.js 1745:28-43
"export 'ɵlooseIdentical' was not found in '@angular/core'
ERROR in ./node_modules/@angular/forms/fesm5/forms.js 2352:12-27
"export 'ɵlooseIdentical' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 5393:12-27
"export 'ɵlooseIdentical' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 3293:8-23
"export 'ɵɵallocHostVars' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 4536:8-17
"export 'ɵɵstyling' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 3294:8-17
"export 'ɵɵstyling' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 4540:8-22
"export 'ɵɵstylingApply' was not found in '@angular/core'
ERROR in ./node_modules/@angular/common/fesm5/common.js 3298:8-22
"export 'ɵɵstylingApply' was not found in '@angular/core'


text:
Q: Delete index dataframe python import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('/OneDrive/Desktop/UNI/Angew_SYS1/Projekt/2012_gwr_sprengelerg.csv', sep = ';', encoding='cp1252')

I have this big dataframe and i want to delete the index (0-2991).
with df1.reset_index(drop=True, inplace=True) nothing changes
and with df.style.hide_index() it removes the index but in the next step I where I use
dataframe = pd.DataFrame(columns=['stimm', "stimm2"])

dataframe["stimm"] = df.loc[df['ptname'] == 'SPÖ', 'stimmen']

dataframe["stimm2"] = df.loc[df['ptname'] == 'FPÖ', 'stimmen']

print(dataframe)

AttributeError: 'Styler' object has no attribute 'loc'

Does anyone know what to do?

A: dataframe["stimm"] = df.loc[df['ptname'] == 'SPÖ', 'stimmen']
dataframe["stimm2"] = df.loc[df['ptname'] == 'FPÖ', 'stimmen']

print(dataframe)

in my new dataframe I have columns "stimm" and "stimm2". The problem is that in "stimm2" are NaNs, because in "stimm" it took already all the index from this
dataframe["stimm"] = df.loc[df['ptname'] == 'SPÖ', 'stimmen']

But there isnt the "ptname" "FPÖ", in those index. So it gives me out the NaNs


text:
Q: undefined reference in g++ (on code which compiled before) I am trying to compile an example from a library called largenet2, using g++. I have compiled this code before on this system, but for some reason it won't do it now:
g++ -L/usr/local/lib/ -llargenet2-0.3 -O2 vm.cpp -o shazam

It produces "undefined reference" errors like:
vm.cpp:(.text.startup+0xc2): undefined reference to `largenet::Graph::nodes()'

(I know this must be some silly flag or something, but googling so far produced nothing to help me....)
Thanks :)


text:
Q: Accessing a XAMPP mysql via Python I'm attempting to use mysql after only having worked with sqlite in the past.
I've installed XAMPP on Linux (ubuntu) and have mysql up and running fine (seems like that with phpMyadmin at least). However, I'm having trouble getting the MySQLdb (the python lib) working {installed this using apt}.
to be exact:

>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost",db="opfine")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 170, in __init_
  ...
    super(Connection, self).__init__(*args, **kwargs2)

OperationalError: (2002, "Can't connect to local MySQL server through
  socket '/var
      /run/mysqld/mysqld.sock' (2)")

I'm guessing

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock

means its expecting some sort of local installation (i.e. not within XAMPP), but I can't figure out how to go about modding this to get it to work with the XAMMP flavor of mysql.
Help is much appreciated!

A: For the record (and thanks to a pointer from Igancio), I found that the below works (terrible I didn't think of this before):
db=MySQLdb.connect(
   user="root"
  ,passwd=""
  ,db="my_db"
  ,unix_socket="/opt/lampp/var/mysql/mysql.sock")

A: It means that you didn't start the MySQL server, or it's configured to not use a domain socket.

A: Have the same issue using and look for your SQL configuration file my.cnf.
# The following options will be passed to all MySQL clients
[client]
#password   = your_password
port        = 3306
socket      = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

and use socket as parameter:
mysql://read:read@localhost/phonehome?unix_socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

In my case:
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://read:read@localhost/phonehome?unix_socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'


text:
Q: How to give individual value of check box column in where condition I have stored multiple values of check box in single datebase column.
how can i give individual value of check box column in where condition.
I want to select only Friday batch .I want sql query to select batch name having day Friday

A: Use like to get an exact string from column
SELECT * FROM `batchinfo` WHERE day like '%Friday%';


text:
Q: Ports for NAT'ed Windows share Simple question: I have a NATed Linux at home that hosts a couple of samba shares.
What Ports should I forward from the router to the Linux box so as to be able to access those shares from the internet with windows explorer (a la "\my.dyndns.org\shares\xxx" style)?
I want the minimum number of port openings that I should do in the router config to have read/write functionality.
EDIT: Client machine is a Vista one

A: 445 for tcp
Contrary to the original answer here, there's no reason to allow 137-139 which should be blocked.
However, I strongly recommend you do not do this. I don't think leaving a samba share internet-accessible is a good idea.
Please please please set up a secure solution such as an ssh server, so that you can scp/sftp data back and forth.
P.s. http://support.microsoft.com/kb/832017 seems to be a good reference of ports required by windows servers and http://www.petri.co.il/whats_port_445_in_w2k_xp_2003.htm explains the above a little more in depth.

A: *

*TCP 139, "NetBIOS Session" – SMB wrapped in NetBIOS for compatibility

*TCP 445, SMB – the preferred method, SMB directly over TCP

*ICMP Echo (Ping) – used by Windows to check whether the machine is up.

"NetBIOS Name Service" is TCP/UDP 137, and "NetBIOS Datagram" is UDP 138, but you do not need any of these to connect to shares. These days it is only necessary for "network browsing", which only works within a LAN anyway.

A: OK here is a guide that could make my grandma do it in 5 mins. Worked without a glitch


text:
Q: Is it possible to do old school 2d blitting on modern GPU? It looks like GL has become mainstream for all gaming platforms (even handheld!)
This has pushed the deployment of modern GPU chipsets to large numbers of consumers.
This is amazing.
With the modern GPU systems out there now, is it possible to do generic old-school graphics
programming (aka - blit from X rect to Y rect using VRAM)? (Think Amiga) Or are the operations centered
around vertex and pixel shaders?
Is this accessable from GL?  OpenGL ES?
Rendering a textured quad is OK, but it would require double buffering and a re-render of the entire scene. Was seeing if I could avoid this.

A: Check for glBlitFramebuffer routine (Framebuffer Object). You need an updated driver.
Keep in mind you can still use the default framebuffer, but I think it will be more funny using framebuffer objects.
Keep your sprite in separate frambuffers (maybe rendered using OpenGL), and set them as read (using glReadBuffers) and blit them on the draw framebuffer (using glDrawBuffers). It's quite simple and fast.

A: Well, you can use libSDL and get a pointer to the screen framebuffer and do whatever you want with the pixels.
Or you cand do all your drawing to a memory buffer, load to a GL texture and draw textured quads which probably it's faster because of hardware acceleration.

A: It may be possible on some embedded systems to get a framebuffer pointer and write to it directly, but these days you're better off using OpenGL|ES and rendering a texture.  It will be more portable, and probably faster.
You could create a buffer in main memory, do all the bit twiddling you want, and then render it as a texture.  You can DMA your texture data to VRAM for speed, and then render it in a quad, which is equivalent to a blit, but doesn't use any CPU cycles and runs as fast as the GPU can process.
It's amazing what you can do with shaders and programmable pipelines these days.

A: If you're drawing textured quads, with which you can easily simulate "old school" blitting, then indeed the pixels are copied from video memory by the GPU. Also note that while bitmap operations are possible in OpenGL, they can be painfully slow because the 3D path is optimized on consumer grade video cards, whereas 2D paths may not be.

A: Also, glCopyPixels seems to do the trick if you have the environment set correctly.

A: On Windows you can use the low level bitmap copying functions, which accurate match the old description without any OpenGL, etc.
BOOL BitBlt(
  _In_ HDC   hdcDest,
  _In_ int   nXDest,
  _In_ int   nYDest,
  _In_ int   nWidth,
  _In_ int   nHeight,
  _In_ HDC   hdcSrc,
  _In_ int   nXSrc,
  _In_ int   nYSrc,
  _In_ DWORD dwRop
);

https://msdn.microsoft.com/en-us/library/dd183370%28v=vs.85%29.aspx


text:
Q: How to fetch all database records with a blob image in php I am fetching from mysql database student information and it is printed well in array wraped in json encode , but in the student records when i include image i get nothing on the screen where what i need is to get all records with an image of each record . please help me .
The results which come out when photo is not include in sql query
My code is as follow when i include picture in sql query which gives nothing on the screen :
   public function StudentsOfParent($mobile){

 $stmt = $this->conn->prepare("SELECT
                         a.id,
                         a.name,
                         a.mobile,
                         c.id as sutdentId,
                         c.user_id,
                         c.full_name,
                         c.school,
                         c.level,
                         c.year,
                         c.photo,
                         d.id as busId,
                         d.bus_name as plate_no,
                         e.id as DriverId,
                         e.driverphone_number,
                         e.driver_fullname
                         from users a
                         join students c
                         on a.id = c.user_id
                         join buses d
                         on c.id = d.student_id
                         join drivers e
                         on e.id = d.driver_id where a.mobile= ?");

    $stmt->bind_param("i", $mobile);
    if ($stmt->execute()) {

   $result = $stmt->get_result();

    $usersArr = array();
    while ($user = $result->fetch_assoc()){
                $usersArr[] = $user;
     }
   $stmt->close();
   // echo json_encode($usersArr);
    return $usersArr;

  } else {
return NULL;
  }
}

To access the above function i use the following php file :
               <?php
  include './DbHandler.php';
 $db = new DbHandler();
 // json response array
 $response = array("error" => FALSE);
  if (isset($_POST['mobile'])){
    $mobile = $_POST['mobile'];
   $usersArr = $db->StudentsOfParent($mobile);
     if ($usersArr != false) {
   $response["error"]= FALSE;
   $response["user"] = $usersArr;
   echo json_encode($response);

        }
       else {
       // user is not found with the credentials
       $response["error"] = TRUE;
       $response["error_msg"] = "Sorry we could not find you !";
         echo json_encode($response);
     }
    }
        else {
    // required post params is missing
   $response["error"] = TRUE;
   $response["error_msg"] = "Required parameter is missing!";
   echo json_encode($response);
   }
      ?>

A: With this solution ,i used the following function and I put BLOB data into an array
then i wrap/envelop that array to Json_encode  ,finally i reach to my target of
displaying image BLOB from MySQL . what i am required now is to decode this json array in android.
We can even decode this image on web with :  echo '
';

This is the working code :
                 public function StudentsOfParent($mobile){

 $stmt = $this->conn->prepare("SELECT
                         a.id,
                         a.name,
                         a.mobile,
                         c.id as sutdentId,
                         c.user_id,
                         c.full_name,
                         c.school,
                         c.level,
                         c.year,
                         c.photo,
                         d.id as busId,
                         d.bus_name as plate_no,
                         e.id as DriverId,
                         e.driverphone_number,
                         e.driver_fullname
                         from users a
                         join students c
                         on a.id = c.user_id
                         join buses d
                         on c.id = d.student_id
                         join drivers e
                         on e.id = d.driver_id where a.mobile= ?");

    $stmt->bind_param("i", $mobile);
    if ($stmt->execute()) {

   $result = $stmt->get_result();

    $usersArr = array();
    while ($user = $result->fetch_assoc()){

    $usersArr[] = $user['id'];
    $usersArr[] = $user['name'];
    $usersArr[] = $user['mobile'];
    $usersArr[] = $user['sutdentId'];
    $usersArr[] = $user['user_id'];
    $usersArr[] = $user['full_name'];
    $usersArr[] = $user['school'];
    $usersArr[] = $user['level'];
    $usersArr[] = $user['year'];
    $usersArr[] = base64_encode($user['photo']);
    $usersArr[] = $user['busId'];
    $usersArr[] = $user['plate_no'];
    $usersArr[] = $user['DriverId'];
    $usersArr[] = $user['driverphone_number'];
    $usersArr[] = $user['driver_fullname'];
   // echo '
';
  }
   $stmt->close();
   // echo json_encode($usersArr);
    return $usersArr;

  } else {
return NULL;
  }
}


text:
Q: Google Cloud Stackdriver Debug Agent: unable to set breakpoint in v8 I'm trying to set up Stackdriver debugger in node using the @google-cloud/debug-agent npm package. Seeing the following error when setting a snapshot breakpoint:
Unable to set breakpoint in v8

The debug agent is enabled for this version; however no request logs are appearing in the Stackdriver debug console. The panel shows startup logs only. Also, none of the logpoints are logging to the console.
Using app engine, node 10.16.0 and @google-cloud/debug-agent v4.0.1.
I have the following in app.js:
require('@google-cloud/debug-agent').start({ allowExpressions: true });

And here's what I've added to package.json:
"dependencies": {
    "@google-cloud/debug-agent": "^4.0.1",
    ...
"devDependencies": {
    "webpack-node-externals": "^1.7.2",
    ...

Since I was having an issue loading dependencies in Webpack, I added this line to the server webpack config:
import nodeExternals from 'webpack-node-externals';

config = {
    externals: [nodeExternals()],
    ...
}


text:
Q: How is copy paste possible? I was wondering after using computer for a long times it feels like copy paste was fundamental feature but I know it is not. So the question is how does this really work?
I thought of all ideas how this could have been implemented but I get stuck every time I come up with the different file formats like gif, jpg, txt, png, mp3, mp4, JSON, YML etc.  and the further you go the complex it gets like shortcuts ,links and then there's directories. Like how it copies images that are in the search result in chrome whereas sometimes you can't copy something due to restriction also you can't select something then you can't copy it whereas sometimes even if you can't select in hierarchy the children are copied so how is it implemented.
But when someone asks me how does copy paste work generally I reply like: When something is copied then it puts the copied item to memory and when pasting it to somewhere the OS finds out the location to where it should be copied and replicates all the file to binary and copies it.
Which might not be true so can you explain how does it exactly work. Also it would be helpful to know how the code was written for copy paste.

A: The first thing you need to realize is that "copy and paste" as well as "drag and drop" are a form of IPC (Inter-process communication) since the data is being transferred from one application to another. This mechanism is usually provided by the same subsystem or service which is responsible for managing the graphical user interface.
This subsystem provides a mechanism for "source" and "destination" applications to negotiate about the format of the data that should be transferred and if they "agree" on some common format then the data can be transferred.
An example to illustrate the concept:

*

*User selects the text in the web-browser and presses Ctrl+C.

*Browser tells the windowing system that it has some data available for copying. Note that no data is copied at this step.

*User opens a text editor and presses Ctrl+V.

*Text editor tells the windowing system to provide it the contents on the clipboard in plain-text format.

*Windowing system tells the browser to provide its shared data in plain-text format.

*Browser converts its data from HTML (or something else) to plain-text and transfers it to the text editor via windowing system. Note that this conversion is not always possible (depending on the formats and applications), hence you sometimes can't paste the copied data.
Technical details

*

*On Windows this functionality is provided via Clipboard API as Ken White mentioned.

*On Linux (and probably everywhere else) the clipboard functionality is not strictly speaking a part of the OS and is provided by the Window Server/Manager (which is really just a service process) via a windowing system protocol such as X protocol or Wayland.


text:
Q: How to plot arrows to show my buy and sell data points on TradingView using Pine Editor I have a list of datapoints (epoch time, trade price executed) generated from python e.g.
buy_orders = [[1626377856, 31004.32], [1626394565, 33041.95], [1626575616, 32218.59]],
and I would like to display this data on Trading View as small green arrows.
Is there a way to do it?
Using Pine Editor I can't seem to find a way to input custom data points.

A: You can save all timestamps and prices in an array. Then you can compare the time of each bar with array timestamps and whichever falls in between can be plotted there. Example below
//@version=5
indicator(title="Plot Trades",overlay=true)
var timestamps=array.new<int>()
var prices=array.new<float>()
array.push(timestamps,1626377856)
array.push(prices,31004.32)
array.push(timestamps,1626394565)
array.push(prices,33041.95)
array.push(timestamps,1626575616)
array.push(prices,32218.59)
plotIndex=-1
var prvtime=0
for i=0 to array.size(timestamps)-1
    if time/1000>array.get(timestamps,i) and prvtime<array.get(timestamps,i)
        plotIndex:=i
prvtime:=time/1000
plotshape(plotIndex>-1?array.get(prices,plotIndex):na,location=location.absolute,style=shape.xcross,size=size.normal)


text:
Q: Php not setting cookie ?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Login extends Controller

{

function index()

{

    $data['main'] ='';

    $data['error'] = '';

    if($this->input->post('username'))

    {

        $username = $this->input->post('username');

        $password = $this->input->post('password');

        $config = $this->maincore->get_config();

        if($username == $config['admin_username'] && md5($password) == $config['admin_password']){

        $value = $username.".".md5($password);

        $time = 9000;

        if($this->input->post('remember')) {

        $time =  time()+3600*24*5;

        }

    setcookie("feeder_login", $value, $time, '/');

    echo '<meta http-equiv="refresh" content="0;url='.$this->config->site_url().'">';

    exit;

I cleared my cookies in chrome and firefox. After my script running. No new cookies are at at all.
I know the script is working as it redirects me to the main page after running.

A: When setting cookies you can not output anything before that. I am pretty sure you've outputting something with "echo()" before setcookie().
If you have an empty character before your

<?php
setcookie("test", "this is a cookie");
?>

and it should really work.


text:
Q: Core Data: constraints changes required migration My old ManagedObject model looks like below, with constraints: [trackURL]
@objc(TrackDownloadInfo)
public class TrackDownloadInfo: NSManagedObject {

    @NSManaged public var trackURL: String
    @NSManaged public var downloadState: Int16
    @NSManaged public var id: Int64
    @NSManaged public var type: Int16

}

I just changed constraints: [id,type] without any model version, this causes a migration error:

Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={sourceURL=file:///var/mobile/Containers/Data/Application/FA440C2E-63EF-4533-94EB-4EA721A645A9/Library/Application%20Support/MyApp.sqlite, reason=Cannot migrate store in-place: constraint violation during attempted migration, destinationURL=file:///var/mobile/Containers/Data/Application/FA440C2E-63EF-4533-94EB-4EA721A645A9/Library/Application%20Support/MyApp.sqlite, NSUnderlyingError=0x2816da820 {Error Domain=NSCocoaErrorDomain Code=134111 "(null)" UserInfo={_NSCoreDataOptimisticLockingFailureConflictsKey=( "" ), NSUnderlyingException=Constraint violation, reason=constraint violation during attempted migration, NSExceptionOmitCallstacks=true}}}, ["NSUnderlyingError": Error Domain=NSCocoaErrorDomain Code=134111 "(null)" UserInfo={_NSCoreDataOptimisticLockingFailureConflictsKey=( "" ), NSUnderlyingException=Constraint violation, reason=constraint v

I know it's due to duplicate entries existing in the table with the same id and type but trackURL is different.
I want to delete both entries to migrate it. I didn't fine any way to do this.


text:
Q: MVC action doesn't get hit by a jquery ajax call I have the following Knockout.js code:
this.submitRequest = function () {
           var url = '@Url.Action("GetDetails", "BrowseItems")';

           $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: ko.toJSON(self.searchRequest),
                success: function (data) { }
            });
        };

This ajax call is supposed to hit a GetDetails Action inside a BrowseItems Controller and it does work for my partner, but not for me. The exact same code. I even went so far as blast my whole project and reload it from TFS to make sure that there are no code quirks. So, I know that I have the same code as my partner, yet it works for him, but not for me. This seems to me like I have to set some sort of Visual Studio environment setting. Can anyone help me out with this?

A: First off how are you testing for whether it is getting hit or not? Debugging? because if so that can be a problem as if you are running through IIS and using the IIS pages and debugging through visual studios local server you will never have visual studio detect a bug on IIS. However lets say you simply are clicking run (debug) which it sounds like. The next thing I would check then is your Global.asax file which has your routes setup. If you dont see something like {controller}/{action} that could possibly be causing a problem. A last suggestion is that instead of wrapping the @Url in ' ' wrap it in " ".


text:
Q: The difference between 'in a good mood' and 'in a good spirits'? What is the difference between 'in a good mood' and 'in a good spirits'?
I see those in the same book.

A: "In a good mood" and "in good spirits" (note: not in "A" good spirits which is incorrect) are basically the same. They both mean - being positive, upbeat, optimistic.

A: Firstly In a Good Spirits would not work as a sentence, Your using A Good as a non-plural phrase, then mixing in a plural phrase "Spirits", So it would be In a Good Spirit.
But yes they would work with a similar meaning, but Good Spirit usually represents when your up for something or your extreme liking of something, like when people say "I have lots of school spirit!" They mean they really like their school while Good Mood simply means your not sad, unhappy, mad, Etc.


text:
Q: What is an approximation for Poisson binomial distribution? I am looking for an approximation for Poisson binomial distribution:
The Poisson binomial distribution is the discrete probability distribution of a sum of $n$ independent Bernoulli trials. you can find its pdf in http://en.wikipedia.org/wiki/Poisson_binomial_distribution
In addition, you can find 2 methods for it in the mentioned link. But when I use the second method (using Fourier Transform), the result would be an imaginary number.
I also wanted to use approximations in the following paper
http://statistics.stanford.edu/~ckirby/techreports/ONR/SOL%20ONR%20467.pdf
but the approximations are not clear to me. I would be grateful if somebody explains to me:
1) why do I get imaginary number using the second method ( Fourier transform)?
2) and also for example, how are the probabilities in Table 2 in the paper calculated?

A: 1) Post the script/code/etc. you used, there is an error in it that perhaps readers can help you with: I whipped up the example in my CAS and it gets proper answer within the precision set.
2) The examples in that paper use multiples for each Pn, i.e., in its first example with comparisons in table 2, we have Pn of [.02,.04,.06,.08,.10], but there are 5 each accounted for, so you need to apply the calculation to the list of probabilities consisting of five repetitions of each value. Same with later examples. The result tables then show the true value and the various approximations that S(actual expected successes)<= s for some number of s successes, so you need to sum from 0 to s in your calculations to compare your results.
As previous posters stated, the Wikipedia DFT form is not an approximation, it is exact (modulo the capability of your computing system). It will take some serious cycles with large arguments - the form lends itself to using DFT tricks to speed calculations, but if you just implement it "as is" in say a CAS, you're not gaining much efficiency if any over the recursive form sans call stack space.

A: Your second link does not work, so I am not sure whether you have seen that, but Le Cam's Theorem works quite well for small $p_i$ and large $n$.


text:
Q: Salesforce login: SAML to oAuth fails giving error invalid_grant I am performing Salesforce login for custom domain, where I have SSO provider which returns SAML and my mobile app consumes Salesforce REST API which consuming oAuth token.
For conversion we are using SAML-Assertion
We are allowing users to log in into webview into SSO- Okta and this is redirecting user to Salesforce returning SAML response in browser.
We are sending this saml response to "https://login.salesforce.com/services/oauth2/token" for getting access token which is returning error {
  "error": "invalid_grant",
  "error_uri": "https://na34.salesforce.com/setup/secur/SAMLValidationPage.apexp",
  "error_description": "invalid assertion"
}
My code for hitting Salesforce request is
final HttpClient httpclient = new DefaultHttpClient();
        final HttpPost post = new HttpPost("https://login.salesforce.com/services/oauth2/token");
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

    String samlResponse = "[encoded data, 5984 characters]";

    samlResponse = base64URLencode(samlResponse);

            //samlResponse = new String(Base64.decode(samlResponse));
    //samlResponse= URLEncoder.encode(samlResponse);
    //String assertion_type = URLEncoder.encode("urn:ietf:params:oauth:grant-type:saml2-bearer");
    String assertion_type= URLEncoder.encode("urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser") ;
    String RequestBody
            = "grant_type=assertion&"
            + "assertion_type=" + assertion_type
            + "&assertion=" + samlResponse
            + "&format=json&client_id=3MVG9Y6d_Btp4xp5mgy7hBfhCbLJvklGIyWd8HTugZxdapc3XwF_5KjfVVlmRHrjudskiG6ynkj9u4Qyha7oQ";

    post.setEntity(new StringEntity(RequestBody));
    HttpResponse response = httpclient.execute(post);

    System.out.println("  execute of API " + EntityUtils.toString(response.getEntity()));


text:
Q: Buttons in Javascript not working after some js changes in html There is a following problem with JS and jquery. During one of the events happening on the page:
task = $("#id").html();
$("#video_id").html(task);
$("#id").html("");

After that, the buttons from #id doesn't work in #video_id.
I've tried to send the data from #video_id back to the old place and process the events there
task = $("#video_id").html();
$("#id").html(task);
$("#video_id").html("");

But after that stopped working all buttons inside the #id.
How to make the elements within the task correctly processed when transferred to #video_id?

A: If you're binding the events to the buttons with jquery you would need to bind the events during the copy process for this to work.
Or use the $(document).on() method...

<button class="two">test</button>

$(document).on('click', '.two', function(){
    alert("test");
    var test = $('#one').html();
    $('#three').html(test);
});

http://jsfiddle.net/5EwuX/7/
This will bind the event to new elements dynamically added to the DOM.


text:
Q: Let the plane V be defined by $ax + by + cz + d = 0$; with $a, b, c, d \in \mathbb{R}$ and the vector $(a; b; c)$ a unit vector. I am battling to get my mind around some of the concepts involving vectors in $3$-space. This question asks me whether the following statements are True or False:
(A) The line $(a; b; c)$ is parallel to $V$
(B) The distance of the plane from the origin is $|d|$
For (A) I don't think I have enough to work with here. I know that if a line is parallel to a plane then it's direction vector must be perpendicular to the planes normal vector... I honestly do not know how to go about proving this and perhaps I am over thinking this.
For (B) I have said this is false as the distance between the plane from the origin is not $|d|$ and is given by the formula:
$$d=\frac{|Ax+By+Cz+D|}{|A^2+B^2+C^2|}$$
I would really appreciate any input on this.
Thanks!

A: For part (A) your reasoning is correct. A line with direction vector $\mathbf{v}$ is parallel to a plane with normal vector $\mathbf{n}$ if and only if $\mathbf{v}$ is orthogonal to $\mathbf{n}$, that is, if and only if $\mathbf{v}\cdot\mathbf{n} = 0$. In this case the direction vector of the line is the same as the normal vector of the plane and so they cannot be parallel since $\mathbf{v}\cdot\mathbf{n} = \mathbf{n}\cdot\mathbf{n} = 1 \neq 0$.
For part (B) you may use the following argument. Let $\mathbf{u}$ be any point in the plane. Then the distance from the origin to $\mathbf{u}$ is $\|\mathbf{u}\|$. Your goal is to find the minimum value of $\|\mathbf{u}\|$. By the Cauchy-Schwarz inequality we have that
$$
|d| = |\mathbf{n}\cdot\mathbf{u}| \leq \|\mathbf{n}\|\cdot\|\mathbf{u}\| = \|\mathbf{u}\|
$$
since $\mathbf{n}$ is a unit vector. Therefore the minimum distance of the plane from the origin is bounded below by $|d|$. The last step is to show that there exists a vector in the plane whose norm is $|d|$. In this case such a vector is given by $-d\mathbf{n}$ since
$$
\mathbf{n}\cdot(-d\mathbf{n}) + d = -d\mathbf{n}\cdot\mathbf{n} +d = -d  +d = 0
$$
and $\|-d\mathbf{n}\| = |d|\|\mathbf{n}\| = |d|$.


text:
Q: iOS blocks and sychronicity I have a question about blocks and synchronicity in my app. Here is the scenario:
I have a NetworkManager which uses AFHTTPRequestOperationManager (AFNetworking 2.0) to make calls to the server. I have a ContentStore class singleton, which provides content for the app. Any class in the app can ask the content store for content, and it passes a block to receive that content. If the ContentStore has the content in memory or in an archive it passes it to the block from the class asking for content. If it doesn't it makes a request to the NetworkManager, and passes a block to the NetworkManager and this block calls the block from the original class when the content arrives from the server. So far this is all good and works well.
The issue is sometimes a class can call the ContentStore for content when a request has already been made for that content, but a reply hasn't been received yet. In this case two requests go to the server for the same content, which doesn't actually cause a problem, but its inefficient.
I came up with a system that does the following: if there is a request is underway to the server for content, the ContentStore saves all the blocks passed to it in an array, when the reply is received from the server the ContentStore loops through the array of blocks and passes the content to each block.
This works well, but I wonder if there is a possible glitch. When a class calls the ContentStore for content and a request is underway, is it possible for a block to be added to the array while the downloadCompletionBlock from the code below is looping through that same array?
Thanks to anyone who takes the time to understand and answer my question. If you need more information please let me know.
@interface ContentStore()
@property (nonatomic, strong) NSDictionary *downloadDictionary;
@property (nonatomic, strong) NSMutableArray *downloadBlocksForRequest;
@property (nonatomic, strong) NetworkManger *networkManager;
@end

@implementation ContentStore

- (void) downloadWithCompletionBlock:(void (^)(NSDictionary *))completionBlock
{

    if (_downloadDictionary) {
        completionBlock(_downloadDictionary);
        return;
    } else {
        _downloadDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:[self downloadArchivePath]];
        if (_downloadDictionary) {
            completionBlock(_downloadDictionary);
            return;
        } else if (_downloadBlocksForRequest) {
            [_downloadBlocksForRequest addObject:completionBlock];
            return;
        } else {
            _downloadBlocksForRequest = [[NSMutableArray alloc]init];
            [_downloadBlocksForRequest addObject:completionBlock];
        }
    }

    void (^downloadCompletionBlock)(NSDictionary *) = ^(NSDictionary *downloadDictionary)
    {
        // do other work necessary

        [NSKeyedArchiver archiveRootObject:downloadDictionary toFile:[self downloadArchivePath]];
        [self setDownloadDictionary:downloadDictionary];

        for (int i=0; i<_facesBlocksForRequest.count; i++) {
            void (^complBlock)(NSDictionary *) = [_facesBlocksForRequest objectAtIndex:i];
            complBlock(downloadDictionary);

        }
        _downloadBlocksForRequest = nil;

    };

    [_networkManager downloadWithCompletionBlock:downloadCompletionBlock];

}

A: NSMutableArray, like most (if not all) mutable containers in iOS, is not thread-safe. So your concern is justified, and this code might introduce a very hard-to-catch bug. You might want to synchronize access to it by doing
@synchronized(_downloadBlocksForRequest) {
     // enumerate _downloadBlocksForRequest, or add an object to it, etc.
}

A: One solution is what BlackRider said, use some kind of cross-thread synchronization to protect accesses to the shared array.
The other solution is to do both operations on the array (adding to the array and handling received content) on the same thread (or serial queue). That would probably require that the "ask for content" operation dispatch to this thread (or queue). This should be no problem in your case, since the method is already asynchronous.


text:
Q: Beginner: Outputting php varibles inside html elements as values I have a declared html file which is then used as an include statement inside a php file.
<?php
 $social_width = "50";
 $social_height = "50";
?>

and
<img src="instagram.png" width="<?php echo $social_width; ?>" height="<?php echo $social_height; ?>" style="padding-left:400px;">

When I debug, that is to say, echo out the variables they do have the right set values. I tried using single and double quotes, escaping quotes but did not find the solution yet.

A: You can include variables in double-quoted strings. This means that you could write your code like this:
<?php
$social_width = "50";
$social_height = "50";
echo "

      ";
?>

Note that this only works on "double-quoted" strings. In 'single-quoted' strings the variables will not be parsed.

A: I don't know exactly what you are doing wrong. But my  best guess is that you may be including the HTML file before declaring your variables. (That is including at the top). This will probably not work
Here is my sample code which works fine.
<?PHP
 $social_width = "50";
 $social_height = "50";

 include('1.html');
?>

But I hope this helps


text:
Q: Using R rvest to scrape a page for number of comments I'm trying to scrape a webpage with R package rvest to get the number of comments left on the article. The page uses disqus forum, and disqus returns the number of comments dynamically.
For example for this webpage, below the header there is a line that shows the number of comments.

The problem is, this seems to be updated dynamically by disqus at the beginning of page loading. If you pay close attention to the page when it just opened, it will show "0 comments", but will soon update to "10 comments" (or more by the time you see this).
When I inspected the element, it is a span with class "entry-comment". When I use rvest to scrape it though, I get the value "0 comments" even though in the element inspector in my browser it shows "10 comments".
Is there a way to solve this using rvest? I can imagine a solution with RSelenium but I want to avoid that for various reasons.


text:
Q: EC2 won't accept RDS incoming data without ALL TCP 0.0.0.0/0 This appears to be a case of the opposite of the common condition. My EC2 instance won't accept incoming RDS (MySQL) data without opening ALL TCP to 0.0.0.0/0.

*

*If in EC2 security group I allow ALL TCP 0.0.0.0/0, then the database works and site loads.

*If I remove ALL TCP 0.0.0.0/0 entry from EC2 security group, but still have Inbound 3306 (MySQL) open to 0.0.0.0/0, the site won't load due to database connection timeout.
CentOS 6/MySQL
Both in same region

A: I've fixed this issue it appears. In the EC2 Security Groups, I selected ALL TCP from the drop down list. In the address field, I entered the ID of the Database Security Group which was assigned only to my RDS instance. FYI, the RDS Security Group only had one port open 3306 (MySQL).
Amazon states that adding a security group to another security group will give all computers associated with the first security group access to whatever ports/services you assign.


text:
Q: CSS: Right align a vertically rotated text I can't seem to align a vertically rotated div all the way to the right side of the page: http://jsfiddle.net/F23W2/2/
HTML:

Vertical Text

CSS:
.vertical {
    position: relative;
    background-color: #DDDDDD;
    padding: 10px;
    border-radius: 5px 5px 0 0;
    float: right;
    -moz-transform: rotate(270deg);  /* FF3.5+ */
    -o-transform: rotate(270deg);  /* Opera 10.5 */
    -webkit-transform: rotate(-90deg);  /* Saf3.1+, Chrome */
}

*

*There is unwanted margin created between right page border and the div.

*Top part of rotated div gets cropped.

Although I can use negative margins to work around, I was wondering if a cleaner solution exists.

A: Change the origin of the rotation transform via transform-origin: 100% 100%;

body {
  padding: 0;
  margin: 0;
}

.vertical {
  position: relative;
  background-color: #DDDDDD;
  padding: 10px;
  border-radius: 5px 5px 0 0;
  float: right;
  -moz-transform: rotate(270deg);
  /* FF3.5+ */
  -o-transform: rotate(270deg);
  /* Opera 10.5 */
  -webkit-transform: rotate(-90deg);
  /* Saf3.1+, Chrome */
  -moz-transform-origin: 100% 100%;
  -o-transform-origin: 100% 100%;
  -webkit-transform-origin: 100% 100%;
}

Vertical Text

New Fiddle


text:
Q: How to disable previous date using HTML5 datetime-local input? I would simply like to prevent users from entering or disable the previous dates in input datetime-local , is there a way to do this?
Here is what I have done, unfortunately nothing happens on this code:

<input type="datetime-local" class="form-control col-md-6" name="book" required>

A: try this

var today = new Date().toISOString().slice(0, 16);

document.getElementsByName("book")[0].min = today;
<input type="datetime-local" class="form-control col-md-6" name="book" required>

A:

              {{ __('adminstaticword.timestart') }}:*
              <input type="datetime-local" class="form-control" name="time_start" id="time_start" placeholder="Enter time_start" required min="{{date('Y-m-d')}}"  value="{{ old('time_start') }}" >


text:
Q: Exception starting filter springSecurityFilterChain I am getting this when I start the tomcat. I have placed the spring2.5.6.jar in my classpath.

SEVERE: Exception starting filter springSecurityFilterChain
java.lang.ClassNotFoundException: org.springframework.web.filter.DelegatingFilterProxy
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:207)
    at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:302)
    at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:78)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3666)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4258)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:448)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)

What can I do?

A: As far as I can recall, in Spring 2.5.x this class was either in the full spring.jar, or in the spring-web.jar.
Check whether you have the class inside your spring2.5.6.jar, and if not add spring-web2.5.6.jar to your classpath.

A:
i have placed the spring2.5.6.jar in my classpath

This phrase is very ambiguous. The "classpath" is merely an abstract term which identifies the collection of all local disk file system paths wherein Java has to scan for classes and JAR files during compiletime or runtime. Your current and previous questions and your comments on this question doesn't give me the impression that you properly understand what exactly the classpath is.
In this particular case, you need to ensure that the JAR file is placed in one of those paths which are (by default) covered by the runtime classpath. The webapp's /WEB-INF/lib folder is one of them. You just have to drop a copy of the JAR in that folder. Absolutely nothing more needs to be done. Even not fiddling with Build Path properties in an IDE, which would possibly make things worse. Undo it if necessary. Just dropping the JAR in /WEB-INF/lib folder of the IDE project is sufficient, really.


text:
Q: Validate lineitems and throw error if the lineitem values dont match On the OpportunityLineItem, I have 2 custom lookup fields and 2 text fields. So if I have like 5 line items added, and if the 2 lookup fields match on any 2 lineitems, I need to make sure the other 2 text fields match as well. Below is the code-
public static void validatelineItems(Map<Id,OpportunityLineItem> mapOpptyLineItem){

    List<string> addLoc;

    for(id oli : mapOpptyLineItem.keyset()) {

        if(mapOpptyLineItem.get(oli).lookup_fld1__c != null && mapOpptyLineItem.get(oli).lookup_fld2__c != null) {
            String cpe = String.valueOf(mapOpptyLineItem.get(oli).lookup_fld1__c) + String.valueOf(mapOpptyLineItem.get(oli).lookup_fld2__c);

            if(addLoc.contains(cpe)) {
                hasduplicates = true; //This tells that there are lineitems with the same lookup values.
            }

            addLoc.add(cpe);

            //Now we need to loop through the map to check if the text field value matches and am not sure how to do that.
        }
    }
}

Ex:
fields         - Lookupfld1 Lookupfld2 textfld1 txtfld2
Record1 values -  id1         id2        t1       t2
Record2 values -  id1         id2        t1       t4

so in the above example, both the lookup field ids have matched but the text fld2 didnt match, so it should throw the error.

A: Maps and Sets are your friend whenever you want to perform pretty much any comparison.
The general approach here is:

*

*Determine what you want your map key to be, and what you want the value to be

*Make the key, and check to see if it exists in the map already

*If it doesn't, then put the key into the map along with the value

*If it does, then grab the value from the map and compare it against the value you currently have

You can use SObjects as the key of a map (and this is a fantastic way to quickly perform complex comparisons), you just need to be very careful to never make a change to the SObject instance that you use as a key after you put it into the map.
I'd suggest making a Map<OpportunityLineItem, OpportunityLineItem> here. The OLI key would just contain your two lookup fields (and probably also the OpportunityId), and the OLI that you store would only contain your two text fields. That'd end up looking something like this
Map<OpportunityLineItem, OpportunityLineItem> oliKeyToOLITarget = new Map<OpportunityLineItem, OpportunityLineItem>();

for(OpportunityLineItem oli :myOLIs){
    // Create the key object
    OpportunityLineItem oliKey = new OpportunityLineItem(
        My_Lookup_1__c = oli.My_Lookup_1__c,
        My_Lookup_2__c = oli.My_Lookup_2__c
    );

    // Create the target value object
    OpportunityLineItem oliValue = new OpportunityLineItem(
        My_Field_1__c = oli.My_Field_1__c,
        My_Field_2__c = oli.My_Field_2__c
    );

    // Check to see if the key exists in the map and, if it does, if the value matches
    if(oliKeyToOLITarget.containsKey(oliKey) && oliKeyToOLITarget.get(oliKey) != oliValue){
        // The key matches, but the value doesn't
        // emit an error, then "continue;" to skip to the next loop iteration
    }

    // Now that oliKey is being put into the map as a key, this instance of OLI should
    //   never be modified.
    // It's ok to create a new OLI instance and store it in the same variable
    //   (using the `new` keyword is the most sure way to get a completely new and
    //    independent instance)
    // It's ok to overwrite the map value at this point, because this is either the first time
    //   this key is being used, or the new value is the same as the old value
    oliKeyToOLITarget.put(oliKey, oliValue);
}


text:
Q: LINQ Distinct not working as expected I have the following simple class
public class Person : IEquatable<Person>
{
    public bool Equals(Person other)
    {
        return Name.Equals(other.Name, StringComparison.InvariantCultureIgnoreCase);
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }

    public Person(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
}

Now I am creating an array of persons, calling distinct on them and pass the default Equality Comparer, which is the one implemented by IEquatable<Person>
var persons = new[] {new Person("foo"), new Person("Foo"), new Person("bar"), new Person("Bar")};
persons.Distinct(EqualityComparer<Person>.Default);

When I inspect the distincted persons, I am expecting an IEnumerable<Person> containing foo, bar. However the contents are foo, Foo, bar, Bar
When I initialize the List with foo, foo, bar, bar the result is as expected. So it seems to me as if StringComparison.InvariantCultureIgnoreCase in the Person.Equals method is ignored.
Has anyone an idea?

A: You need to make GetHashCode() get a case-*in*sensitive Hash Code at the moment, it will be a different hash code for upper and lower case Name's.
For example:
public override int GetHashCode()
{
    return Name.ToUpperInvariant().GetHashCode();
}

A: Your GetHashCode() will return different hash codes for objects who should be considered identical.


text:
Q: Adding Array of UIButtons in iOS I would like to add UIButton using for loop. Each button would have a different action.
My code is:
NSArray *methods = [[NSArray alloc]initWithObjects:@"1",@"2", @"3", @"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15", nil];
int x=0;
for (int t=0;t<=14;t++) {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector([methods[t]]) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"" forState:UIControlStateNormal];
    button.frame = CGRectMake(275, x+8, 28, 16);
    [button setBackgroundColor:[UIColor colorWithRed: 10.0/255.0f green:100.0/255.0f blue:150.0/255.0f alpha:1.0f]];
    button.layer.cornerRadius = 10;
    [button setBackgroundImage:[UIImage imageNamed:@"Plus"] forState:UIControlStateNormal];
    [segmentedView1 addSubview:button];
    [self.view addSubview:segmentedView1];
    x+=20;
}

Stuck with an error:
"Expected identifier" in the line  [button addTarget:self action:@selector([methods[t]])
Also,how do i make outlets for such buttons added programatically?
Any solution?
Thank you

A: I would advise to assign same selector for all the buttons. Pointer to the button will be send to this selector and you can recognize which button was pressed using .tag property for example.
for (int t=0;t<=14;t++) {
   ...
   [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
   button.tag = i;
}

- (void)buttonPressed:(id)sender {
   if (((UIButton *)sender).tag == 1) {
      ...
   }
   ...
}

Also move [self.view addSubview:segmentedView1]; outside of your loop.

A: NSString *selectorName = methods[t];
SEL method = NSSelectorFromString(selectorName);

[button addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];

don't forget, you have to implement all these selectors and if you keep methods in array it's potentially pretty risky. I would suggest to use one action for all buttons and handle it via tag property inside your action.
If not, try to wrap:
if ([self respondsToSelector:method]) {
    [button addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
}

A: @selector expects a method, not an object
you have to do like
- (void)onClick:(UIBUtton*)sender {
    if(sender.tag == 1) {
        // ....
    }
}

button.tag = i;
[button addTarget:self action:@selector(onClick)


text:
Q: NSAttributedString / NSTextTab Alignment Issue GOAL:
I'm attempting to use NSAttributedStrings (in conjunction with NSTextTabs) to create the following layout:
[ Title           # ]  <-- Useable in NSTableViews, NSMenuItems, etc.
[ Another Title   # ]
[ T3              # ]

ATTEMPTED SOLUTION:
The code I'm attempting is:
NSMutableParagraphStyle *tabStyle = [[NSMutableParagraphStyle alloc] init];
[tabStyle setTabStops: [NSArray array]];
[tabStyle addTabStop: [[NSTextTab alloc] initWithType: NSRightTabStopType location: 200.0]];
[attrString appendAttributedString: [[NSMutableAttributedString alloc] initWithString: @"\t"]];
[attrString addAttribute: NSParagraphStyleAttributeName value: tabStyle range: NSMakeRange(0, [attrString length])];
[attrString appendAttributedString: [[NSMutableAttributedString alloc] initWithString: @"1"]];

Where attrString is an NSMutableAttributeString, currently set to the "Title".
However, using this code (which I would assume would produce the desired output), produces the following:

FURTHER INFORMATION:
When I remove the references to NSTextTabs, like so:
[attrString appendAttributedString: [[NSMutableAttributedString alloc] initWithString: @"\t"]];
[attrString appendAttributedString: [[NSMutableAttributedString alloc] initWithString: @"1"]];

I get the expected output of uneven tabbing.

BOTTOM LINE:
Why is the NSAttributedString seemingly ignoring the NSParagraphStyle/NSTextTabs?
What can I do to fix this?

A: Found the issue, by making an NSTextView in IB and placing the AttributedString into it.

Apparently, the layout needs to be "Scrolls" (was "Truncates") in order to produce the desired effect.


text:
Q: Error on trying to override POST method with PUT (Method Not Allowed) I am experiencing a "Method Not Allowed" issue when trying to override my POST request with PUT (for updating information in my blog). I already installed method override for koa.
HTML:

<form action="/messages/edit/<%= message.id %>?_method=PUT" method="POST">
  Message title:
  <input required value="<%= message.title %>" type="text" id="title" name="title" required>
  Message snippet:
  <input required value="<%= message.snippet %>" type="text" id="snippet" name="snippet" required>
  Message body:
  <input required value="<%= message.body %>" type="text" id="body" name="body" required>
  <button>Update</button>
</form>

My routs are the following:
  //edit message
  router.get('/messages/edit/:id', async (ctx, next) => {
    const id = ctx.params.id;
    const result = await MessageModel.findById(id)
    await  ctx.render('edit', {
      title: 'Messages',
      message: result
     })
    });

The code above runs well, but after I click on submit button, "Method Not Allowed" issue occurs instead of running this:
  //update edited message
  router.put('/messages/edit/:id', async (ctx, next) => {
      MessageModel.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new:true}, (err:any, result:any) => {
      })
    return ctx.redirect('/');
});

Please share your thoughts on this issue.
Thank you

A: Make sure you add the following to your app.js (index.js) file.
app.use(methodOverride('_method'));

A: You can't set the form method to PUT, it's either GET or POST.
to send a PUT request you can use AJAX, via (for instance) the Fetch API
EDIT: my bad, you used the "tunneling" concept mentioned in that solution.
per this documentation, maybe try with
<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="_method" value="PUT">


text:
Q: Would the values inside request be mixed up in callback? I am new to Node.js, and I have been reading questions and answers related with this issue, but still not very sure if I fully understand the concept in my case.
Suggested Code
router.post('/test123', function(req, res) {
someAsyncFunction1(parameter1, function(result1) {
  someAsyncFunction2(parameter2, function(result2) {
    someAsyncFunction3(parameter3, function(result3) {
       var theVariable1 = req.body.something1;
       var theVariable2 = req.body.something2;
    )}
  )}
});

Question
I assume there will be multiple (can be 10+, 100+, or whatever) requests to one certain place (for example, ajax request to /test123, as shown above) at the same time with some variables (something1 and something2). According to this, it would be impossible that one user's theVariable1 and theVariable2 are mixed up with (i.e, overwritten by) the other user's req.body.something1 and req.body.something2. I am wondering if this is true when there are multiple callbacks (three like the above, or ten, just in case).
And, I also consider using res.locals to save some data from callbacks (instead of using theVariable1 and theVariable2, but is it good idea to do so given that the data will not be overwritten due to multiple simultaneous requests from clients?

A: Each request an Node.js/Express server gets generated a new req object.
So in the line router.post('/test123', function(req, res), the req object that's being passed in as an argument is unique to that HTTP connection.
You don't have to worry about multiple functions or callbacks. In a traditional application, if I have two objects cat and dog that I can pass to the listen function, I would get back meow and bark. Even though there's only one listen function. That's sort of how you can view an Express app. Even though you have all these get and post functions, every user's request is passed to them as a unique entity.


text:
Q: Is there any way to locate this button (if it is a button) and click on it? I'm trying to click on some buttons of an online game consecutively. Taking a look at the game could be helpful.
Here's a part of the main html relating to the buttons:

1
 #⬅Each of this lines are a button.

2

3

4

The best I've got so far:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located

browser = webdriver.Firefox()
browser.get('http://zzzscore.com/1to50/en/')

wave_info = [[25, "//div[contains(@style, 'opacity')]"], [50, "//div[contains(@style, 'opacity')]"]]

n = 1
for wave in wave_info:
    grid_elements = browser.find_elements_by_xpath(wave[1])
    while n <= wave[0]:
        for item in grid_elements:
            if int(item.text) == n:
                item.click()
                n += 1

The code above works well, but after clicking on 27 buttons (and sometimes 28 buttons) it shows the following traceback:
Traceback (most recent call last):
  File "C:\Users\Parsa\Desktop\python\2.py", line 18, in <module>
    if int(item.text) == n:
ValueError: invalid literal for int() with base 10: ''

There is a relevant question but I didn't understand it well.
Your early response in this regard would be highly appreciated.

A: Error
The error you are receiving is being thrown at the final stage of the game when the boxes/buttons start disappearing. Once a box disappears calling item.text will return None which cannot be converted to an int.
Solution
import time
from selenium.common.exceptions import StaleElementReferenceException

wave_info = [[25, "//div[contains(@style, 'opacity')]"], [50, "//div[contains(@class, 'second')]"]]
time.sleep(2)
n = 1
for wave in wave_info:
    time.sleep(.1)
    grid_elements = browser.find_elements_by_xpath(wave[1])
    while n <= wave[0]:
        for item in grid_elements:
            try:
                if int(item.text) == n:
                    item.click()
                    n += 1
            except ValueError:
                continue
            except StaleElementReferenceException:
                break

Explanation
Time is imported and time.sleep(2) is called to allow the page time to fully load before we begin interacting with it. The time.sleep(.1) at the beginning of the loop allows for the grid elements to fully load in-between the first and second wave(the transition between the first 25 and last 25 elements). All the elements that we are meant to click in the game share the same style, and this is taken advantage of in the solution above. All of the elements are found and saved in one line grid_elements = browser.find_elements_by_xpath(wave[1]). The elements are then looped through and are clicked when their value matches the number we are searching for. This minimizes the amount of clicks we actually have to do to 50 compared to clicking every element and hoping you have clicked the right one. This comparison takes place in a try except block incase a ValueError is thrown meaning that the item.text returned None. The other except terminates the inner for loop after the 50th element has been clicked. Because the page changes and the elements cease to exist after you click the 50th element, a StaleElementReferenceException is thrown when you attempt to click one of these elements. When the error is thrown we know the game is over because the page has changed meaning we can break the inner for loop. The outer two loops will automatically end because n will equal 51 and the entire wave_info array will have been looped through. If either error is thrown then the code will not be halted.

A: There is a more elegant way to do so:
x = range(1, 51)
for number in x:
    element = browser.find_element_by_xpath('//div[text()= "' + str(number) + '"]')
    element.click()


text:
Q: boost thread while all thread not completed print something need to know that
boost::thread_group tgroup;

loop 10 times
tgroup.create_thread( boost::bind( &c , 2, 2, ) )

<==
tgroup.join_all()

What can i do at the <== location above to continuously print the number of threads who have completed there jobs

A: You can use an atomic counter: See it Live On Coliru
#include <boost/thread/thread.hpp>
#include <boost/atomic.hpp>

static boost::atomic_int running_count(20);

static void worker(boost::chrono::milliseconds effort)
{
    boost::this_thread::sleep_for(effort);
    --running_count;
}

int main()
{
    boost::thread_group tg;

    for (int i = 0, count = running_count; i < count; ++i) // count protects against data race!
        tg.create_thread(boost::bind(worker, boost::chrono::milliseconds(i*50)));

    while (running_count > 0)
    {
        std::cout << "Monitoring threads: " << running_count << " running\n";
        boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
    }

    tg.join_all();
}

Example output:
Monitoring threads: 19 running
Monitoring threads: 17 running
Monitoring threads: 15 running
Monitoring threads: 13 running
Monitoring threads: 11 running
Monitoring threads: 9 running
Monitoring threads: 7 running
Monitoring threads: 5 running
Monitoring threads: 3 running
Monitoring threads: 1 running

Another way would be to use a semaphore

A: The easiest way would be to print thread id at the end of job "c":
void c()
{
//some code here
some_safe_print << boost::this_thread::get_id();
}

That way, when thread will finish, the last instruction would be to print it's id.