id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23532000
|
Uncaught TypeError: Cannot read property 'options' of null
And my javascript function:
<script language="JavaScript" type="text/javascript">
function appendlistbox(){
var select = document.getElementById("listboxstock");
select.options[select.options.length] = new Option("myobject", "index");
}
</script>
And this is my HTML:
<button type="button" id="btnaddstock" class="btn btn-default" onclick="appendlistbox()">Tambahkan Bahan</button>
<label>Bahan Yang Dibutuhkan :</label>
<select name="listboxstock" size="5" class="form-control">
</select>
I dont have any idea about the error...
A: You should access select by name property, using document.getElementsByName method.
document.getElementsByName return a NodeList, so you have to access your select using its index: var select = document.getElementsByName("listboxstock")[0];
Final solution.
function appendlistbox(){
var select = document.getElementsByName("listboxstock")[0];
select.options[select.options.length] = new Option("myobject", "index");
}
<button type="button" id="btnaddstock" class="btn btn-default" onclick="appendlistbox()">Tambahkan Bahan</button>
<label>Bahan Yang Dibutuhkan :</label>
<select name="listboxstock" size="5" class="form-control">
</select>
A: Your problem is in this line:
var select = document.getElementById("listboxstock");
The select does not have the id "listboxstock" (that is the "name" attribute, not the id). So, you could change it to:
<select name="listboxstock" id="listboxstock" size="5" class="form-control">
A: Your select tag needs the property id
select name="listboxstock" id="listboxstock" size="5" class="form-control">
A: You are assigning the "name" attribute listboxstock to your select control, but you are not assigning the "id" attribute. And since you are using document.getElementById, your element cannot be found (and thus the Uncaught TypeError: Cannot read property 'options' of null error. Either assign the id, or use getElementsByName:
By name:
<script language="JavaScript" type="text/javascript">
function appendlistbox(){
var select = document.getElementsByName("listboxstock")[0];
select.options[select.options.length] = new Option("myobject", "index");
}
</script>
<button type="button" id="btnaddstock" class="btn btn-default" onclick="appendlistbox()">Tambahkan Bahan</button>
<label>Bahan Yang Dibutuhkan :</label>
<select name="listboxstock" size="5" class="form-control">
</select>
By Id:
<script language="JavaScript" type="text/javascript">
function appendlistbox(){
var select = document.getElementById("listboxstock");
select.options[select.options.length] = new Option("myobject", "index");
}
</script>
<button type="button" id="btnaddstock" class="btn btn-default" onclick="appendlistbox()">Tambahkan Bahan</button>
<label>Bahan Yang Dibutuhkan :</label>
<select id="listboxstock" name="listboxstock" size="5" class="form-control">
</select>
A: <select name="listboxstock" size="5" class="form-control"></select>
replace above line with the following line
<select id="listboxstock" size="5" class="form-control"></select>
| |
doc_23532001
|
def number_group(number):
if number > 0:
return "Positive"
elif number < 0:
return "Negative"
else:
"Zero"
print(number_group(10)) #Should be Positive
print(number_group(-5)) #Should be Negative
print(number_group(0)) #Should be Zero
A: Don't forget the return statement:
def number_group(number):
if number > 0:
return "Positive"
elif number < 0:
return "Negative"
else:
return "Zero"
print(number_group(10)) #Should be Positive
print(number_group(-5)) #Should be Negative
print(number_group(0)) #Should be Zero
A: you forgot to add return in the last line
# you wrote "zero"
# you should use
else:
return "Zero"
| |
doc_23532002
|
My current code is not working.
using UnityEngine;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public InputField Field;
public void Start ()
{
Field.onValueChanged.AddListener(delegate{ApplyCurrencyFormat();});
}
public void ApplyCurrencyFormat ()
{
Field.textComponent.text = "$" + Field.text + ".00";
}
}
I can show "$" + Field.text + ".00"; in the console but I can't change the output text.
A: Instead of using this hard coded
Field.textComponent.text = "$" + Field.text + ".00";
which assumes the value is a valid integer value I would rather actually try to parse it and also react to incorrect inputs. The biggest challenge here I guess is that you want to manipulate the same text value you are currently also typing on. This might lead to unexpected behavior from a user perspective.
private void Start()
{
Field.onValueChanged.AddListener(ApplyCurrencyFormat);
Field.text = 0f.ToString("C");
}
private void ApplyCurrencyFormat(string newValue)
{
// remove whitespace and currency symbols like '$' or '€' depending on the culture
var str = newValue.Trim().Replace(CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol, "");
// if string is empty use 0.00 $
if (string.IsNullOrEmpty(str))
{
Field.text = 0f.ToString("C");
return;
}
// remove anything that is not a 0-9 '.' or '-'
Regex.Replace(str, "[^0-9-" + CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator + "]", "");
// check if a . is present
var match = new Regex(CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator, RegexOptions.Compiled).Match(str);
// get anything before the first .
var beforeHead = str.Substring(0, str.IndexOf(match.Value, StringComparison.Ordinal));
if (!string.IsNullOrEmpty(beforeHead) && beforeHead[0] == '-')
{
beforeHead = '-' + Regex.Replace(beforeHead, @"[^0-9]", "");
}
else
{
beforeHead = Regex.Replace(beforeHead, @"[^0-9]", "");
}
// get anythin after the .
var afterHead = Regex.Replace(str.Substring(beforeHead.Length + 1), @"[^0-9]", "");
// combine to a new float format string
var validFloatNumber = beforeHead + match.Value + afterHead;
// if empty again use 0.00 $
if (string.IsNullOrEmpty(validFloatNumber))
{
Field.text = 0f.ToString("C");
return;
}
// try to parse to float value
if (float.TryParse(validFloatNumber, out var asFloat))
{
var formattedString = asFloat.ToString("C");
if (Mathf.Approximately(asFloat, 0f) && beforeHead[0] == '-')
{
// re add the - in case of 0 otherwise you could never
// start tying with a -
formattedString = "-" + formattedString;
}
Field.text = formattedString;
}
else
{
Field.text = 0f.ToString("C");
}
}
Note this is still not perfect and has some hickups (e.g. when entering the first number) but I hope the idea gets clear.
A: This is the solution I came up with its a little bit simpler I guess but does the same
private void Start()
{
inputField.onValueChanged.AddListener(delegate {ApplyCurrencyFormat();});
}
//Get only the characters needed to parse
//Parse the string to float
//Put the `$` again before the (float) priceValue
//Set the input field with the correct format
private void ApplyCurrencyFormat()
{
if (!string.IsNullOrEmpty(inputField.text))
{
string priceOnly = inputField.text.Replace("$", "");
float priceValue = float.Parse(priceOnly);
string newPrice = $"${priceValue:F}";
inputField.text = newPrice;
}
}
Also, you might need to configure your input field's content type like this so users can only enter valid characters.
content type config
| |
doc_23532003
|
/* platform.service.js */
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class PlatformService {
constructor(
@Inject(PLATFORM_ID) private platformId: Object
) {
this.platformId; // this is coming out undefined
}
isBrowser() {
return isPlatformBrowser(this.platformId);
}
isServer() {
return isPlatformServer(this.platformId);
}
}
I am creating a BaseComponent for common handling of my route binded components.
/* base.component.ts */
import { Component, OnInit, Inject } from '@angular/core';
import { InjectorHolderService } from '@core/services/util/injector-holder.service';
import { PlatformService } from '@core/services/util/platform.service';
@Component({
selector: 'app-base',
template: '',
})
export class BaseComponent implements OnInit {
protected platformService: PlatformService;
constructor() {
this.platformService = InjectorHolderService.injector.get(PlatformService);
console.log(this.platformService);
}
}
Since this component will be inherited by many components, I didn't want to pass the PlatformService through super(). So I decided to go with creating an Injector.
/* app.module.ts */
import { InjectorHolderService } from '@core/services/util/injector-holder.service';
import { PlatformService } from '@core/services/util/platform.service';
@NgModule({ ... })
export class AppModule {
constructor() {
InjectorHolderService.injector = Injector.create({
providers: [
{
provide: PlatformService,
useClass: PlatformService,
deps: [], // I think i need to put something here, but not sure.
}
]
});
}
}
And a service which can hold all the injected module for future use.
/* injector-holder.service.ts */
import { Injectable, Injector } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class InjectorHolderService {
static injector: Injector;
}
But @Inject(PLATFORM_ID) private platformId: Object is giving out undefined, because of which I am not able to detect the platform.
What am I missing here? or If there is a better approach to achieve the above functionality.
Please let me know if you guys need to see any other file.
A: I am not sure whether the following approach is good or bad, currently, it is the only thing working for me. Would love to hear any new approach to it.
Since PlatformService needed @Inject(PLATFORM_ID) which is provided only from AppModule, the new Injector I created was not able to find any value for @Inject(PLATFORM_ID) and hence undefined.
So, instead of using class PlatformService in Injector, now I am using PlatformService's instantiated object and hence was able to access everything fine in BaseComponent.
Modified my AppModule like following:
/* app.module.ts */
import { InjectorHolderService } from '@core/services/util/injector-holder.service';
import { PlatformService } from '@core/services/util/platform.service';
@NgModule({ ... })
export class AppModule {
constructor(
private platformService: PlatformService,
) {
InjectorHolderService.injector = Injector.create({
providers: [
{
provide: PlatformService,
useValue: this.platformService, // notice the change of key, using value not class
deps: [],
}
]
});
}
}
Will try to add a minimal repo to recreate this issue and share with you guys, If anyone wants to explore more.
| |
doc_23532004
|
Each of them can be developper AND/OR manager AND/OR commercial
No other role will be created in the futur.
To optimise my database, Should I create one table with the following boolean fields :
is_developper
is_manager
is_commercial
Or should a create another table "roles" and a N-N table to join them ?
| |
doc_23532005
|
hello
*
*Block sites through SNI filtering in Korea.
(HTTPS site block)
*I can't tell Korean customers to use vpn.
server status
*
*1 IP and 1 site exist
*Apache,php in use
My certificate is...
https://example.com (blocked)
https://example.net (Not blocked, redirect to example.com)
question
Can the SNI header be changed by force on the server?
(If you go to aaa.com
Forces the SNI field to be changed to aaa.net)
Is it possible?
(I'm a beginner. Sorry.)
| |
doc_23532006
|
I have a form where I type a keyword into a textbox that search among those .txt files when I click the button called "search".
For every match the entire line surrounding the keyword is then written into the richtextbox preceded by the fullpath of the related txt file.
I would like to know if there's a way to make that fullpath a link that could be simply clicked, to reach the related .txt file.
| |
doc_23532007
|
Router.onBeforeAction(function() {
var self;
self = this;
authToken = Session.get('authToken');
if (!authToken) {
this.redirect('login');
this.next();
} else {
Meteor.call('validateAuthToken', authToken, function (error, result)) {
if (result) {
self.next();
} else {
self.redirect('login');
self.next();
}
}
}
});
I need to validate an authentication token stored in Session by invoking a server call. But this method always throws an exception when I am executing it. And I found out the reason is because the onBeforeAction call is terminated before the validateAuthToken call returns. And thus the self.next() won't take action. So I wonder what can I do to prevent the onBeforeAction call from stopping until the validateAuthToken returns the validated result and then proceed?
I've tried a different implementation by wait on a session variable, but it seems the ready state is never set to true
Router.onBeforeAction(function() {
var authToken;
authToken = Session.get('authToken');
if (!authToken) {
this.redirect('login');
this.next();
} else {
Meteor.call('validateAuthToken', authToken, function (error, result) {
if (!error) {
Session.set("tokenValidated", result);
}
});
this.wait(Meteor.subscribe('token', Session.get('tokenValidated')));
if (this.ready()) {
if (!Session.get("tokenValidated")) {
this.redirect('login');
this.next();
} else {
this.next();
}
}
}
});
A: EDIT : After working with this problem for a little bit I came up with a working example (without the infinite loop). You can use the following code:
Util = {};
// We need to store the dep, ready flag, and data for each call
Util.d_waitOns = {};
// This function returns a handle with a reactive ready function, which
// is what waitOn expects. waitOn will complete when the reactive function
// returns true.
Util.waitOnServer = function(name) {
// This prevents the waitOnServer call from being called multiple times
// and the resulting infinite loop.
if (this.d_waitOns[name] !== undefined &&
this.d_waitOns[name].ready === true) {
return;
}
else {
this.d_waitOns[name] = {};
}
var self = this;
// We need to store the dependency and the ready flag.
this.d_waitOns[name].dep = new Deps.Dependency();
this.d_waitOns[name].ready = false;
// Perform the actual async call.
Meteor.call(name, function(err, or) {
// The call has complete, so set the ready flag, notify the reactive
// function that we are ready, and store the data.
self.d_waitOns[name].ready = true;
self.d_waitOns[name].dep.changed();
self.d_waitOns[name].data = (err || or);
});
// The reactive handle that we are returning.
var handle = {
ready: function() {
self.d_waitOns[name].dep.depend();
return self.d_waitOns[name].ready;
}
};
return handle;
}
// Retrieve the data that we stored in the async callback.
Util.getResponse = function(name) {
return this.d_waitOns[name].data;
}
Which is called from waitOn like so:
Router.route("/test", {
name: "test",
action: function() {
console.log("The data is ", Util.getResponse("testWaitOn"));
},
waitOn: function() {
return Util.waitOnServer("testWaitOn");
}
})
I wrote a blog post with a more in depth explanation, which you can find here:
http://www.curtismlarson.com/blog/2015/05/04/meteor-ironrouter-waitOn-server/
A: You can also use this code snippet from https://github.com/iron-meteor/iron-router/issues/426
Ready = new Blaze.ReactiveVar(false);
Router.route('feed',{
waitOn: function () {
Meteor.call('getInstagramUserFeed', function(error, result) {
if(!error) Ready.set(result)
});
return [
function () { return Ready.get(); }
];
},
action: function () {
if (this.ready()) this.render('feed')
else this.render('LoadingMany');
}
});
| |
doc_23532008
|
One spec details that single quotes are not allowed, and the other has a script which is essential to the banner. Without the script, there is no point serving the banner in the first place.
So the question is, is there a way to write this script using only double quotes?
<script>
document.write('<script src="' + (window.API_URL || 'http://example.com/' + Math.random()) + '"><\/script>');
</script>
A: Can't you just escape the double quotes that you don't want to terminate the string? \" evaluates to the literal character ".
document.write("<script src=\"" + (window.API_URL || "http://example.com/" + Math.random()) + "\"><\/script>');
| |
doc_23532009
|
public class BenchmarkRunner {
@Test
public static void main(String argv[]) throws Exception
{
org.openjdk.jmh.Main.main(argv);
}
}
It doesnt matter if I annotate the class or method:
@Warmup(iterations = 5, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 5, timeUnit = TimeUnit.MILLISECONDS)
@Fork(value = 3)
@BenchmarkMode(Mode.AverageTime)
public class MyBenchmark {
@Benchmark
public void testMethod()
{
testHashFinderMethod_1();
}
private void testHashFinderMethod_1()
{
HashFinder hashFinder_1 = new HashFinder("TeSt",'A','z');
hashFinder_1.findHash("");
}
}
A: The problem was that I was running the benchmark from the tests folder using the jUnit @test annotation. Moved it and ran it from the src folder and it works.
| |
doc_23532010
|
But, it is unchecked when set to false.
So, 0 and false behaved the same in version 12, appearing as unchecked, but differently in version 13.
In this example, workOrderDtiConstraint.ESCALATED is the field used. When set to 0, the box is checked, when set to false, it is unchecked.
<ng-container matColumnDef="escalated">
<mat-header-cell *matHeaderCellDef>Escalated</mat-header-cell>
<mat-cell class="checkBox" *matCellDef="let workOrderDtiConstraint, let i = index">
<mat-checkbox color="primary"
[checked]="workOrderDtiConstraint.ESCALATED">
</mat-checkbox>
</mat-cell>
</ng-container>
Any ideas?
Thanks
A: You can use a helper function like this:
getBoolean(value) {
switch (value) {
case true:
case "true":
case "True":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
And your code would be like this:
<ng-container matColumnDef="escalated">
<mat-header-cell *matHeaderCellDef>Escalated</mat-header-cell>
<mat-cell class="checkBox" *matCellDef="let workOrderDtiConstraint, let i = index">
<mat-checkbox color="primary"
[checked]="getBoolean(workOrderDtiConstraint.ESCALATED)">
</mat-checkbox>
</mat-cell>
</ng-container>
| |
doc_23532011
|
The main problem I am looking into now is one of the add-ins is saving the path incorrectly, it is saving it as such: C:\David\\File.txt
The part of the application that deals with file io tries to ensure the file exists prior to doing stuff with a File.Exists(path) call. This call is returning true even for the above example. Can anyone explain why this might be?
The issue I am facing is, beyond one module saving the path incorrectly, certain modules that interact with the file are accepting that incorrect path and working fine while others see it and crash. Although currently I am going to fix this by getting the path saved correctly, I'd like to understand what is going on here.
A: You have a false premise: that C:\David\\File.txt is an invalid path. Multiple backslashes are accepted fine in Windows. Try notepad C:\David\\File.txt in a command prompt as an experiment--it should work.
For more info, see this other SO q/a that reaffirms this. Any number of backslashes are fine, and this can be used as a "easy" way to combine paths without worrying about the number of backslashes. For example, the user can provide C:\David or C:\David\ and you can add \test.txt without worrying which input the user provided. However, Path.Combine is the real way to do this in C#.
Edit: To remove your extra \'s easily before passing the path into the other program, try splitting the path into the drive and folder names and combining it back together into a path. Like this:
string path = Path.Combine(pathWithManyBackslashes.Split('\\'));
Because Split doesn't create new entries when the delimiter repeats, you get rid of them. For example, C:\David\\File.txt => [C:, David, File.txt].
| |
doc_23532012
|
The problem is that i dont know how big content inside that element will be, sometimes it will be long content, sometimes small, that is minor problem..
This is screenshoot what i need to make
Now when someone click on ACTION i need this
Can this be done by boostrap JS, or need some custom JS and css
Here if similar solution but just on smaller screens
http://www.bootply.com/103653
Here what i have for now, but i have problem to add opacity to content on clik on action
CSS
#accordion {
position: fixed;
bottom: 30px;
border-radius:none !important;
padding-left:0px;
padding-right:0px;
z-index:1030;
}
.opacity{
background: none repeat scroll 0 0 rgba(0, 0, 0, 0.8);
height: 100%;
left: 0;
position: fixed;
text-align: center;
top: 0;
width: 100%;
z-index: 999;
}
HTML
<div class="opacity"></div>
<div class="panel-group col-md-12 col-sm-12 col-xs-12" id="accordion">
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h4 class="panel-title text-center"><a class="pull-right" data-toggle="collapse" data-parent="#accordion" href="#collapseOne"> ACTION </a> <br>
<a class="pull-right" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo"> ACTION2 </a></h4>
</div>
<div id="collapseOne" class="panel-collapse collapse">
HERE GOES THE CONTENT
</div>
<div id="collapseTwo" class="panel-collapse collapse">
Lorem Ipsum је једноставно модел текста који се користи у штампарској и словослагачкој индустрији. Lorem ipsum је био стандард за модел текста још од 1500. године, када је непознати штампар узео кутију са словима и сложио их како би направио узорак књиге. Не само што је овај модел опстао пет векова, него је чак почео да се користи и у електронским медијима, непроменивши се. Популаризован је шездесетих година двадесетог века заједно са листовима летерсета који су садржали Lorem Ipsum пасусе, а данас са софтверским пакетом за прелом као што је Aldus PageMaker који је садржао Lorem Ipsum верзије.
</div>
</div>
</div>
<footer class="container-fluid" role="contentinfo">
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="navbar-inner navbar-content-center"> Copyright </div>
</nav>
</footer>
And here is full example on fiddle
http://jsfiddle.net/k4xt4g40/\
I got problem with opacity, how to add when collapse is visble and when dont remove?
Got something like this
http://jsfiddle.net/k4xt4g40/2/
Only problem is that it it must stay display block when another action is clicked?
A: You could use bootstrap for the stylizing and custom jquery scripts to implement the page disable and the menu expand features.
check out this fiddle Navbar
The navbar closed automatically becos of an error in the css class name you used in the bottom nav bar,
rename like below in the button
data-target=".navbar-collapse" to data-target=".navbar-collapse-bottom"
and
<div class="navbar-collapse-bottom collapse">
hope this solves your problem
| |
doc_23532013
|
I have a GWTP web app that runs perfectly fine in dev mode either from eclipse or from the command prompt running mvn gwt:run.
Now i try to deploy it to Tomcat 7 locally. I ran gwt:compile and copied the zip file (after renaming it to .war) to the webapps folder. The app is listed in Tomcat's manager gui. But when i try to navigate to localhost:8080/appname or localhost:8080/appname/Project.html, i only get an 404 error. What did i miss?
For completeness, here is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>testproject</groupId>
<artifactId>testme-gwtp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>GWTP Basic</name>
<description>Basic GWTP application</description>
<properties>
<!-- client -->
<gwt.version>2.6.0</gwt.version>
<gwtp.version>1.2.1</gwtp.version>
<gin.version>2.1.2</gin.version>
<!-- server -->
<guice.version>3.0</guice.version>
<!-- testing -->
<junit.version>4.7</junit.version>
<jukito.version>1.4</jukito.version>
<!-- maven -->
<gwt-maven-plugin.version>2.6.0</gwt-maven-plugin.version>
<maven-surefire-plugin.version>2.6</maven-surefire-plugin.version>
<maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
<maven-resources-plugin.version>2.5</maven-resources-plugin.version>
<maven-processor-plugin.version>2.0.5</maven-processor-plugin.version>
<maven-build-helper-plugin.version>1.7</maven-build-helper-plugin.version>
<target.jdk>1.7</target.jdk>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
</properties>
<build>
<outputDirectory>${webappDirectory}/WEB-INF/classes</outputDirectory>
<plugins>
<!-- JUnit Testing - skip *.GwtTest cases -->
<!-- 'mvn test' - runs the Jukito tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/*GwtTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!-- GWT -->
<!-- 'mvn gwt:run' - runs development mode -->
<!-- 'mvn gwt:debug' - runs debug mode -->
<!-- 'mvn gwt:compile' - compiles gwt -->
<!-- 'mvn integration-test' - runs the gwt tests (*GwtTest.java) -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<version>${gwt.version}</version>
<configuration>
<!-- With multiple tests use GwtTestSuite.java for speed -->
<includes>**/*GwtTest.java</includes>
<extraJvmArgs>-Xss1024K -Xmx1024M -XX:MaxPermSize=256M</extraJvmArgs>
<copyWebapp>true</copyWebapp>
<hostedWebapp>${webappDirectory}</hostedWebapp>
<runTarget>Project.html</runTarget>
<modules>
<module>testproject.Project</module>
</modules>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Google Web Toolkit -->
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>${gwt.version}</version>
</dependency>
<!-- GWT-Platform -->
<dependency>
<groupId>com.gwtplatform</groupId>
<artifactId>gwtp-all</artifactId>
<version>${gwtp.version}</version>
</dependency>
<!-- DI -->
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>com.google.inject.extensions</groupId>
<artifactId>guice-servlet</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>com.google.inject.extensions</groupId>
<artifactId>guice-assistedinject</artifactId>
<version>${guice.version}</version>
</dependency>
<dependency>
<groupId>com.google.gwt.inject</groupId>
<artifactId>gin</artifactId>
<version>${gin.version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jukito</groupId>
<artifactId>jukito</artifactId>
<version>${jukito.version}</version>
<scope>test</scope>
</dependency>
<!-- Hibernate -->
<!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<!-- hSQLDB -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.2</version>
</dependency>
<!-- add slf4j interfaces to classpath -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- GWT-Log -->
<dependency>
<groupId>com.allen-sauer.gwt.log</groupId>
<artifactId>gwt-log</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
Thanks :)
A: It seems that your gwt-maven-plugin goals is not bound to any maven phases. Try something like this:
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>compile</goal>
<goal>test</goal>
</goals>
</execution>
</executions>
A: I addition to get it running, you need to do as Vadim told, but also this must be added to pom.xml:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.codehaus.mojo</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<versionRange>[2.4.0,)</versionRange>
<goals>
<goal>resources</goal>
<goal>compile</goal>
<goal>i18n</goal>
<goal>generateAsync</goal>
<goal>test</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
If you specify the phase for compile as <phase>prepare-package</phase>, it is perfomed as the last step before packaging when calling mvn package.
| |
doc_23532014
|
Following : https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/sagemaker_workforce
it working fine
main.tf
resource "aws_sagemaker_workforce" "workforce" {
workforce_name = "workforce"
cognito_config {
client_id = aws_cognito_user_pool_client.congnito_client.id
user_pool = aws_cognito_user_pool_domain.domain.user_pool_id
}
}
resource "aws_cognito_user_pool" "user_pool" {
name = "sagemaker-cognito-userpool"
}
resource "aws_cognito_user_pool_client" "congnito_client" {
name = "congnito-client"
generate_secret = true
user_pool_id = aws_cognito_user_pool.user_pool.id
}
resource "aws_cognito_user_group" "user_group" {
name = "user-group"
user_pool_id = aws_cognito_user_pool.user_pool.id
}
resource "aws_cognito_user_pool_domain" "domain" {
domain = "sagemaker-user-pool-ocr-domain"
user_pool_id = aws_cognito_user_pool.user_pool.id
}
resource "aws_sagemaker_workteam" "workteam" {
workteam_name = "worker-team"
workforce_name = aws_sagemaker_workforce.workforce.id
description = "worker-team"
member_definition {
cognito_member_definition {
client_id = aws_cognito_user_pool_client.congnito_client.id
user_pool = aws_cognito_user_pool_domain.domain.user_pool_id
user_group = aws_cognito_user_group.user_group.id
}
}
}
resource "aws_sagemaker_human_task_ui" "template" {
human_task_ui_name = "human-task-ui-template"
ui_template {
content = file("${path.module}/sagemaker-human-task-ui-template.html")
}
}
resource "aws_sagemaker_flow_definition" "definition" {
flow_definition_name = "flow-definition"
role_arn = var.aws_iam_role
human_loop_config {
human_task_ui_arn = aws_sagemaker_human_task_ui.template.arn
task_availability_lifetime_in_seconds = 1
task_count = 1
task_description = "Task description"
task_title = "Please review the Key Value Pairs in this document"
workteam_arn = aws_sagemaker_workteam.workteam.arn
}
output_config {
s3_output_path = "s3://${var.s3_output_path}"
}
}
it's creating the cognito user pool with callback urls. These callback urls is coming from aws_sagemaker_workforce.workforce.subdomain and getting set in cognito automatically which is what i want.
But i also want to set config in cognito userpool like
allowed_oauth_flows = ["code", "implicit"]
allowed_oauth_scopes = ["email", "openid", "profile"]
now when i add above two line we need to add callbackurl also which i dont want.
i tried
allowed_oauth_flows = ["code", "implicit"]
allowed_oauth_scopes = ["email", "openid", "profile"]
callback_urls = [aws_sagemaker_workforce.workforce.subdomain]
which is giving error :
Cycle: module.sagemaker.aws_cognito_user_pool_client.congnito_client, module.sagemaker.aws_sagemaker_workforce.workforce
as both resource are dependent on each other, i want to pass those two line but it forces me to add callback url also.
here is the final main.tf which is failing with that three line
resource "aws_sagemaker_workforce" "workforce" {
workforce_name = "workforce"
cognito_config {
client_id = aws_cognito_user_pool_client.congnito_client.id
user_pool = aws_cognito_user_pool_domain.domain.user_pool_id
}
}
resource "aws_cognito_user_pool" "user_pool" {
name = "sagemaker-cognito-userpool"
}
resource "aws_cognito_user_pool_client" "congnito_client" {
name = "congnito-client"
generate_secret = true
user_pool_id = aws_cognito_user_pool.user_pool.id
explicit_auth_flows = ["ALLOW_REFRESH_TOKEN_AUTH", "ALLOW_USER_PASSWORD_AUTH", "ALLOW_CUSTOM_AUTH", "ALLOW_USER_SRP_AUTH"]
allowed_oauth_flows_user_pool_client = true
supported_identity_providers = ["COGNITO"]
allowed_oauth_flows = ["code", "implicit"]
allowed_oauth_scopes = ["email", "openid", "profile"]
callback_urls = [aws_sagemaker_workforce.workforce.subdomain]
}
resource "aws_cognito_user_group" "user_group" {
name = "user-group"
user_pool_id = aws_cognito_user_pool.user_pool.id
}
resource "aws_cognito_user_pool_domain" "domain" {
domain = "sagemaker-user-pool-ocr-domain"
user_pool_id = aws_cognito_user_pool.user_pool.id
}
resource "aws_sagemaker_workteam" "workteam" {
workteam_name = "worker-team"
workforce_name = aws_sagemaker_workforce.workforce.id
description = "worker-team"
member_definition {
cognito_member_definition {
client_id = aws_cognito_user_pool_client.congnito_client.id
user_pool = aws_cognito_user_pool_domain.domain.user_pool_id
user_group = aws_cognito_user_group.user_group.id
}
}
}
resource "aws_sagemaker_human_task_ui" "template" {
human_task_ui_name = "human-task-ui-template"
ui_template {
content = file("${path.module}/sagemaker-human-task-ui-template.html")
}
}
resource "aws_sagemaker_flow_definition" "definition" {
flow_definition_name = "flow-definition"
role_arn = var.aws_iam_role
human_loop_config {
human_task_ui_arn = aws_sagemaker_human_task_ui.template.arn
task_availability_lifetime_in_seconds = 1
task_count = 1
task_description = "Task description"
task_title = "Please review the Key Value Pairs in this document"
workteam_arn = aws_sagemaker_workteam.workteam.arn
}
output_config {
s3_output_path = "s3://${var.s3_output_path}"
}
}
A: You do not need to specify the callback URL for the workforce. It is sufficient to specify the following in order to create the aws_cognito_user_pool_client resource:
callback_urls = [
"https://${aws_cognito_user_pool_domain.domain>.cloudfront_distribution_arn}",
]
Then you reference the user pool client in your workforce definition:
resource "aws_sagemaker_workforce" "..." {
workforce_name = "..."
cognito_config {
client_id = aws_cognito_user_pool_client.<client_name>.id
user_pool = aws_cognito_user_pool_domain.<domain_name>.user_pool_id
}
}
Existence of the callback URLs can be proven after applying the terraform configuration by running aws cognito-idp describe-user-pool-client --user-pool-id <pool_id> --client-id <client_id>:
"UserPoolClient": {
...
"CallbackURLs": [
"https://____.cloudfront.net",
"https://____.labeling.eu-central-1.sagemaker.aws/oauth2/idpresponse"
],
"LogoutURLs": [
"https://____.labeling.eu-central-1.sagemaker.aws/logout"
],
It seems as terraform itself does not do anything special on workforce creation (see https://github.com/hashicorp/terraform-provider-aws/blob/main/internal/service/sagemaker/workforce.go). So the callback urls seem to be added by AWS SageMaker itself.
This means that you have to instruct terraform to ignore changes on those attributes in the aws_cognito_user_pool_client configuration:
lifecycle {
ignore_changes = [
callback_urls, logout_urls
]
}
| |
doc_23532015
|
Any help is greatly appreciated.
Thanks!!
NSPredicate *parentPredicate1 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"1"];
}];
NSPredicate *parentPredicate2 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"2"];
}];
NSPredicate *parentPredicate3 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"3"];
}];
NSPredicate *parentPredicate4 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"4"];
}];
NSPredicate *parentPredicate5 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"5"];
}];
NSPredicate *parentPredicate6 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"6"];
}];
NSPredicate *parentPredicate7 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"7"];
}];
NSPredicate *parentPredicate8 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"8"];
}];
NSPredicate *parentPredicate9 = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:@"9"];
}];
childID_1 = [parentArray filteredArrayUsingPredicate:parentPredicate1];
childID_2 = [parentArray filteredArrayUsingPredicate:parentPredicate2];
childID_3 = [parentArray filteredArrayUsingPredicate:parentPredicate3];
childID_4 = [parentArray filteredArrayUsingPredicate:parentPredicate4];
childID_5 = [parentArray filteredArrayUsingPredicate:parentPredicate5];
childID_6 = [parentArray filteredArrayUsingPredicate:parentPredicate6];
childID_7 = [parentArray filteredArrayUsingPredicate:parentPredicate7];
childID_8 = [parentArray filteredArrayUsingPredicate:parentPredicate8];
childID_9 = [parentArray filteredArrayUsingPredicate:parentPredicate9];
_allArrays = [[ NSMutableArray alloc] initWithObjects:childID_1, childID_2, childID_3, childID_4, childID_5, childID_6, childID_7, childID_8, childID_9, nil];
}
A: Use a loop
NSMutableArray *childObjects = [NSMutableArray array];
for (NSUInteger i = 1; i < N; i++)
{
NSPredicate *parentPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSString *value = [@(i) stringValue];
return [evaluatedObject[@"parent_id"] isEqual:value];
}];
[childObjects addObject:[parentArray filteredArrayUsingPredicate:parentPredicate]];
}
A: block can use local variable so you can put them into a loop
_allArrays = [[ NSMutableArray alloc] init];
for (int i = 0; i < 10; i++)
{
NSPredicate *parentPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject,
NSDictionary *bindings)
{
return [evaluatedObject[@"parent_id"] isEqual:[NSString stringWithFormat:@"%d", i]];
}];
[_allArrays addObject:[[parentArray filteredArrayUsingPredicate:parentPredicate]]];
}
| |
doc_23532016
|
I am using c# as programing language and .net framework 3.5.
Thanks.
A: This article on MSDN Forum shows how to read and write image data in MS ACCESS.
You will have to use Image data type for the photo field. While inserting convert the data into byte array and pass as parameters.
A: something like this should help
var oleDbConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\sample.accdb");
var oleDbCommand = oleDbConnection.CreateCommand();
oleDbCommand.CommandText = "insert into Table1 (Name, Photo) values (@name, @photo)";
oleDbCommand.Parameters.AddWithValue("@name", "MyName");
byte[] yourPhoto = GetYourPhotoFromSomewhere();
oleDbCommand.Parameters.AddWithValue("@photo", yourPhoto);
using (oleDbConnection)
{
oleDbConnection.Open();
oleDbCommand.ExecuteNonQuery();
}
| |
doc_23532017
|
Delete button works but add doesn't, how to debug this guys?
private void FillDataGrids()
{
formLoaded = false;
voziloBindingSource.DataSource = r.DohvatiSvaVozila();
djelatnikBindingSource.DataSource = r.DohvatiSveDjelatnike();
formLoaded = true;
}
I don't know what code to post, because everything else is set up through properties... I already have one DataGridView ("djelatnik") set up with bindingnavigator and the 2 functionalities work fine (add/delete)
A: It turns out my BindingNavigator's AddNewItem property was set wrong.
Once I set it to default name everything worked fine
| |
doc_23532018
|
$(document).ready(function(){...});
but I am not sure about the most reliable approach in plain js.
Clearly
window.onload = ...
is not proper solution, because it would overwrite previous declaration.
What I am trying to do is to insert an iframe into a div after the page is loaded, but maybe there are actually better ways of doing it. My plan is to do something like:
window.onload = function(divId){
var div = document.getElementById(divId);
div.innerHTML = "<iframe src='someUrl' .. >";
}
EDIT:
Apologies for not including all necessary details.
The script is not for my website - the idea is to show a part of my site (a form) on external web sites. The priority is to minimize the effort someone has to put to use my code. That is why I would like to keep everything in js file and absolutely nothing in <script> - except of <script src="http://my.website/code.js" />. If I change URL of an iframe or I would like to add some features, I would like to update the code on all other web sites without asking them to make any changes.
My approach might be wrong - any suggestions are very welcome.
A: //For modern browsers:
document.addEventListener( "DOMContentLoaded", someFunction, false );
//For IE:
document.attachEvent( "onreadystatechange", someFunction);
`attachEvent` and `addEventListener` allow you to register more than one event listener for a particular target.
See:
https://developer.mozilla.org/en/DOM/element.addEventListener
Also definitly worth looking at how jQuery does it:
http://code.jquery.com/jquery-1.7.js Search for bindReady.
A: Use window.addEventListener and the events load or DOMContentLoaded:
window.addEventListener('DOMContentLoaded',function(){alert("first handler");});
window.addEventListener('DOMContentLoaded',function(){alert("second handler");});
object.addEventListener('event',callback) will insert an event listener into a queue for that specific object event. See https://developer.mozilla.org/en/DOM/element.addEventListener for further information.
For IE5-8 use window.attachEvent('event',callback), see http://msdn.microsoft.com/en-us/library/ms536343%28VS.85%29.aspx. You can build yourself a little helper function:
function addEventHandler(object,szEvent,cbCallback){
if(typeof(szEvent) !== 'string' || typeof(cbCallback) !== 'function')
return false;
if(!!object.addEventListener){ // for IE9+
return object.addEventListener(szEvent,cbCallback);
}
if(!!object.attachEvent){ // for IE <=8
return object.attachEvent(szEvent,cbCallback);
}
return false;
}
addEventHandler(window,'load',function(){alert("first handler");});
addEventHandler(window,'load',function(){alert("second handler");});
Note that DOMContentLoaded isn't defined in IE lesser 9. If you don't know your recipient's browser use the event load.
A: Just put your script include at the very end of the document, immediately before or after the ending </body> tag, e.g.:
(content)
(content)
<script src="http://my.website/code.js"></script>
</body>
</html>
All of the markup above the script will be accessible via the usual DOM methods (reference). Obviously, not all ancillary resources (images and such) will be fully loaded yet, but presumably that's why you want to avoid the window load event (it happens so late).
The only real purpose of ready-style events is if you don't control where the script gets included (e.g., libraries) or you need to have something execute prior to the page load and something else after the page load, and you want to avoid having two HTTP requests (e.g., for two different scripts, one before load and one after).
| |
doc_23532019
|
Here are the matrices:
Matrix A : Score attempt in a football match
John Mike Luc
2010 20 30 25
2011 13 22 18
2012 10 20 14
Matrix B : Number of Games
John Mike Luc
2010 10 15 12
2011 5 8 7
2012 2 8 3
The following code works perfectly
a <- Score_Attempts
b <- Num_Of_Games
matplot(a, b, type = "l", xlab = "Score attempt", ylab = "Number of game")
legend("bottomright", legend = colnames(a), col = seq_len(a), pch = 1, cex = 0.7)
Something seems not right with the ggplot equivalent. Assist me getting this one right too, Thanks!
data <- data.frame(ScoreAttempt = as.vector(a),
NumOfGame = as.vector(b))
ggplot(data, mapping = aes(x = ScoreAttempt, y = NumOfGame ))
labs(x="Score attempt", y= "Number of game") +
geom_line(size = 2)
A: First off, your labs() and geom_line() are not connected to the ggplot() due to a missing + sign.
Tried to replicate your code as follows
a <- matrix( c(20,30,25,13,22,18,10,20,14), ncol=3, byrow=TRUE )
dimnames(a) <- list( 2010:2012, c("John","Mike","Luc") )
b <- matrix( c(10,15,12,5,8,7,2,8,3), ncol=3, byrow=TRUE )
dimnames(b) <- list( 2010:2012, c("John","Mike","Luc") )
matplot(a, b, type = "l", xlab = "Score attempt", ylab = "Number of game")
legend("bottomright", legend = colnames(a), col = seq_len(a), pch = 1, cex = 0.7)
to create this
Assuming the above picture is correct, you need to some additional data to recreate it via ggplot2
data <- data.frame( Individual=rep(c("John","Mike","Luc"),each=3),
Year=rep(2010:2012,3),
ScoreAttempt = as.vector(a),
NumOfGame = as.vector(b) )
ggplot(data, mapping = aes(x = ScoreAttempt, y = NumOfGame, color=Individual, group=Individual ) ) +
labs(x="Score attempt", y= "Number of game") +
geom_line(size = 2)
to get this
Now you just need to fine tune all of the scaling to get what you want.
| |
doc_23532020
|
import os
import sys
sys.path.append('/usr/bin/python')
vs
os.environ['PYTHONPATH'] = '/usr/bin/python'
I am running a script as a cron job and want to set PYTHONPATH environ variable to '/usr/bin/python' for the script to be run. What is the correct way of of the two mentioned in the snippet above?
A: Updating sys.path.append() will change the paths that the current script searches for modules/packages. Updating os.environ[] will only affect subprocesses, if you pass them the environment.
These only affect the directories that are searched for modules/packages, as /usr/bin/python is usually the python executable neither would have any effect.
If you are trying to specify a version of python to use to execute the script then use a shebang at the top of the script:
#!/usr/bin/python
Make sure the script is set executable chmod +x script and then execute it directly via cron.
| |
doc_23532021
|
The application runs fine in-memory using docker, but I can't manage to change to MySQL.
I did some research, and managed to write this docker-compose.yml:
version: '3.3'
services:
#service 1: definition of mysql database
db:
image: mysql:latest
container_name: mysql-db2
environment:
- MYSQL_ROOT_PASSWORD=sa
- MYSQL_USER=password
ports:
- "3306:3306"
#service 2: definition of phpMyAdmin
phpmyadmin:
image: phpmyadmin/phpmyadmin:latest
container_name: my-php-myadmin
ports:
- "8082:80"
restart: always
depends_on:
- db
environment:
SPRING_DATASOURCE_USERNAME: sa
SPRING_DATASOURCE_PASSWORD: password
#service 3: definition of the spring-boot app
customerservice:
image: mysqldockerapp
container_name: mysql-docker-app
build:
context: .
dockerfile: Dockerfile
ports:
- "8084:8084"
depends_on:
- db
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://mysql-db2:3306/customer?createDatabaseIfNotExist=true
SPRING_DATASOURCE_USERNAME: sa
SPRING_DATASOURCE_PASSWORD: password
And these are my application.properties
server.port=8084
spring.application.name=customer-service
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://mysql-db2:3306/customer?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=UTC
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.hibernate.ddl-auto=update
spring.datasource.initialization-mode=never
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.hibernate.SQL=DEBUG
And my dockerfile
FROM openjdk:16-alpine3.13
MAINTAINER krzysztof.com
EXPOSE 8084
COPY target/myapp.jar myapp.jar
ENTRYPOINT ["java","-jar","/myapp.jar"]
The containers build correctly, but the app exits and I get:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
But the MySQL container is running, so I would appreciate any tips where should I look for possible reasons.
| |
doc_23532022
|
It doesn't seem to want to paste into a text field in google chrome however.
display dialog "What is the list? (Artist, Song Title, Artist, Song Title)" default answer "Frank Sinatra, My Way, Elvis, Blue Christmas"
set user_input to text returned of result
set {myTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {","}}
set myList to text items of user_input -- Gives list {"2", "69", "12"}
set AppleScript's text item delimiters to myTID -- It's considered good practice to return the TID's to their original state
repeat with myItem in myList -- Loop through the items in the list
tell application "System Events"
set the clipboard to myItem
keystroke "v" using {command down}
keystroke tab
end tell
delay 1
end repeat
display dialog "Job Done"
return
A: Your paste command is done on your script, not on other application (Chrome in your case). you must tell which process should receive the keystroke. Something like :
tell application "System Events"
tell process "Chrome"
Set the clipboard to myItem
keystroke "v" using {command down}
keystroke tab
end tell
end tell
| |
doc_23532023
|
The the original xml is here and This is an example of each story.
<news:NewsResult>
<news:Title>Essex Police/Fire</news:Title>
<news:Url>http://www.gloucestertimes.com/local/x2118804357/Essex-Police-Fire</news:Url>
<news:Source>Gloucester Daily Times</news:Source>
<news:Snippet>ESSEX — An attempt to serve a summons to a Piper Lane resident was thwarted at 2:25 p.m. Monday when police discovered that the person no longer lives at that address. Alarms were set off in error on Belcher Street at 3:12 p.m. Monday, on Main Street at ...</news:Snippet>
So far I have code like this:
def xml2Var(xmlin)
#Parse received XML with Nokogiri
doc = Nokogiri::XML(xmlin)
#Remove namespaces
doc.remove_namespaces!
#print dat ish?
# p p doc
#extract values.
title = doc.xpath("//Title")
snippet = doc.xpath("//Snippet")
url = doc.xpath("//Url")
source = doc.xpath("//Source")
I want to put these values into an array for each story. Then, add each story into a stories array so that I can then display it in my Rails app.
I kind-of managed to do this, but then could not display each story, and each story's attributes. I think my use of Xpath is wrong?
A: To put the stories into arrays you would do something like:
doc.css("NewsResult").map{|nr| [nr.at('Title'),nr.at('Snippet'),nr.at('Url'),nr.at('Source')].map(&:text)}
A: Given four arrays of values, as you have, you could interleave them like so:
titles = %w[t1 t2 t3 t4]
snippets = %w[n1 n2 n3 n4]
urls = %w[u1 u2 u3 u4]
sources = %w[s1 s2 s3 s4]
pp titles.zip(snippets,urls,sources)
#=> [["t1", "n1", "u1", "s1"],
#=> ["t2", "n2", "u2", "s2"],
#=> ["t3", "n3", "u3", "s3"],
#=> ["t4", "n4", "u4", "s4"]]
However, this might be dangerous. If there aren't the exact same number in each array—if one array is missing a source, for example—then they're going to wind up mis-associated:
titles = %w[t1 t2 t3 t4]
snippets = %w[n1 n2 n3 n4]
urls = %w[u1 u2 u3 u4]
sources = %w[s1 s3 s4]
pp titles.zip(snippets,urls,sources)
#=> [["t1", "n1", "u1", "s1"],
#=> ["t2", "n2", "u2", "s3"],
#=> ["t3", "n3", "u3", "s4"],
#=> ["t4", "n4", "u4", nil]]
Better to do what @pguardiario suggests: find each news result and then map that to its component pieces. Written more tersely:
parts = %w[Title Snippet Url Source]
all = doc.css("NewsResult").map{ |nr| parts.map{ |part| nr.at(part).text } }
This will give you an array of four-valued arrays, where [0] is the title's text, [1] is the snippet's, and so on:
all.each do |title,snippet,url,source|
puts "Title: #{title} @ #{url} came from #{source}"
end
If you want a more usable construct, I'd personally create a Hash, so that I am not accessing values by magic index:
results = doc.css("NewsResult").map do |result|
Hash[ parts.map{ |part| [part.downcase.to_sym, result.at(part).text] } ]
end
#…later…
results.each do |result|
puts "Title: #{result[:title]} @ #{result[:url]} came from #{result[:source]}"
end
| |
doc_23532024
|
For example:
-------------------
MainClass
-------------------
-------------------
+Main()
______
+Othermethod()
______________
-------------------
Should I keep the line under the othermethod() or I should remove it and keep it only under the main method?
A: The static operations of a class, whether main() or other should be underlined. Non static operations should not be underlined:
If you'd make shortcuts on this notation, only showing some of the static methods as static, your model would be confusing, and could lead to errors in the implementation.
If you're using ASCII art, the underlining is very cumbersome and confusing. In this case, you should prefer the {static} adornment, in textual form:
,---------------------------------.
|MainClass |
|---------------------------------|
|... |
|+{static} main() |
|+otherNonStaticOperation() |
|+{static} otherStaticOperation() |
`---------------------------------'
By the way, plantuml can generate both, graphic and ascii art, for the same model:
@startuml
skinparam style strictuml
skinparam classAttributeIconSize 0
class MainClass {
...
+{static} main()
+otherNonStaticOperation()
+{static} otherStaticOperation()
}
@enduml
| |
doc_23532025
|
i have a adjacency matrix "adj(2d vectors)" + i have a char vector in name color and i have a int glist
i'm having a problem with the following function
for(list<int>::iterator it = glist.begin(); it != glist.end(); it++)
{
int x =0;
for(int i=0;i<adj.at(*it).size();i++){
if(color.at(adj.at(*it).at(i)) == 'w')
x++;
}
if(x == 0)
{
it = glist.erase(it);
}
}
what i want from this function is to test if the neghbors of each elemnt in glist hase neighbors with white color (i.e the color of the neighbor in the color vector == "w" if it doesn't then deltet the element from the glist
but when i compile an error of list iterator not incrementable shows up
any help will be appreciated
A: Your logic skips an item of the list when you erase an item.
Say you have:
1 5 15 222
in your list. Let's say you end deleting 5 from the list. The lines:
if(x == 0)
{
it = glist.erase(it);
}
will make it point to 15. And you do ++it in the for line, which makes it point to 222. That means you skipped processing 15.
If you end up deleting 222, the lines:
if(x == 0)
{
it = glist.erase(it);
}
will make it point to glist.end(). When you do ++it on that, you will see undefined behavior.
Change your logic to update it by using:
if(x == 0)
{
it = glist.erase(it);
}
else
{
++it;
}
and change the for line to:
for(list<int>::iterator it = glist.begin(); it != glist.end(); /* it++ /*)
// ^^^^ Don't need.
| |
doc_23532026
|
const handleSignUp = () => {
auth
.createUserWithEmailAndPassword(email, password)
.then(userCredentials => {
console.log(userCredentials.user.uid)
const user = userCredentials.user;
console.log('Registered with:', user.email);
setDoc(doc(db, "users", "LA"), {
name: "Los Angeles",
// state: "CA",
// country: "USA"
});
})
.catch(error => alert(error.message))
}
The Firebase module is here
if it need any changes of any dependency or any version
please suggest as firebase version is 9.6.11,while firestore is of 3.4.14
// Import the functions you need from the SDKs you need
// import firebase from "firebase";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/database"
// import { getFirestore } from "@firebase/firestore";
import { getFirestore } from 'firebase/firestore'
// import { getFirestore } from 'firebase/firestore/lite'
const firebaseConfig = {
apiKey: ........................
authDomain: ........................
projectId: ........................
storageBucket: ........................
messagingSenderId: ........................
appId: ........................
};
// Initialize Firebase
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
} else {
app = firebase.app()
}
export const auth = firebase.auth()
// export const db = firebase.firestore();
export const db = getFirestore(app)
A: The error indicates that you are calling setDoc() function to something that is not a DocumentReference or a CollectionReference.
You may try to get the details from the console log as to which variable reference it is hitting the above error and understand why what you are calling it on is not a valid CollectionReference or DocumentReference. Please read through the helpful documentation for Collection Reference
The function setDoc() ,writes to the document referred to by the specified DocumentReference. If the document does not yet exist, it will be created. If you provide merge or mergeFields, the provided data can be merged into an existing document.The result of this write will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.
Also check and verify that you are to call the firebase admin sdk rather than the client SDK and see if that works.
A: It's an AngularFire version issue, basically if you're using Angular 12, with Firebase 9 you need @angular/fire@^7.0
The compatibility table on the firebase page is key: https://github.com/angular/angularfire#angular-and-firebase-versions
I struggled with this issue for hours ?days? and it was because I had angularfire 7.4 (even 7.2 didn't work).
| |
doc_23532027
|
I need the emoji actually to show itself like an emoji.
What I did to make the emoji in PyCharm:
<a:currency_symbol:832506821675057173>
Code:
@commands.command(pass_context=True, aliases=['bal'])
async def balance(self, ctx):
id = str(ctx.message.author.id)
embed = discord.Embed(title="CatsyBot Economy", description=f"{ctx.message.author}'s Balance", colour=discord.Colour.blue())
embed.add_field(name="Bank", value="{} <a:currency_symbol:832506821675057173>".format(amounts[id]))
if id in amounts:
await ctx.send(embed=embed)
else:
await ctx.send(embed="You do not have an account")
A: If emoji is not animated, just write:
<currency_symbol:832506821675057173>
Code:
@commands.command(pass_context=True, aliases=['bal'])
async def balance(self, ctx):
id = str(ctx.message.author.id)
embed = discord.Embed(title="CatsyBot Economy", description=f"{ctx.message.author}'s Balance", colour=discord.Colour.blue())
embed.add_field(name="Bank", value="{} <currency_symbol:832506821675057173>".format(amounts[id]))
if id in amounts:
await ctx.send(embed=embed)
else:
await ctx.send(embed="You do not have an account")
| |
doc_23532028
|
I'm using now the last nusoap (should be compatible with php 5.3.18) and translating the code from SoapClient to nusoap_client.
This code use SoapClient and works perfectly
$s_WSPROTOCOL = 'https';
$s_WSHOSTNAME = 'xxxxxxxx.yyyyyy.tdl';
$s_WSPORT = '';
$s_WSPATHNAME = 'webservices/service.asp?WSDL';
$s_WSTIPOOP = 'MyFunction';
$parameters['Username'] = '999';
$parameters['Login'] = 'Master';
$parameters['Password'] = 'universe';
$parameters['IdServ'] = '5';
$parameters['IdCard'] = '555';
$parameters['Controllo'] = '';
echo $s_WSTIPOOP."<br />";
echo $s_WSPROTOCOL."://".$s_WSHOSTNAME.$s_WSPORT."/".$s_WSPATHNAME."<br /><br /><br />";
try
{
$SOAP = new SoapClient($s_WSPROTOCOL."://".$s_WSHOSTNAME.$s_WSPORT."/".$s_WSPATHNAME, array('trace' => 1));
$result = $SOAP->__soapCall($s_WSTIPOOP, array("parameters" => $parameters), null);
foreach ($result as $key => $value)
{
echo "<b>".$key."</b><br />";
print_r($value);
echo "<br />";
}
}
catch (SoapFault $e)
{
echo "<b>".$e->faultstring."</b>";
}
This code in nusoap returns
[faultcode] => soap:Client
[faultstring] => Server did not recognize the value of HTTP Header SOAPAction: .
[detail] =>
here the code
require("nusoap/lib/nusoap.php");
error_reporting(E_ALL ^ E_NOTICE);
$ERROR_MSG = '';
$s_WSPROTOCOL = 'https';
$s_WSHOSTNAME = 'xxxxxxxx.yyyyyy.tdl';
$s_WSPORT = '';
$s_WSPATHNAME = 'webservices/service.asp?WSDL';
$s_WSTIPOOP = 'MyFunction';
$parameters['Username'] = '999';
$parameters['Login'] = 'Master';
$parameters['Password'] = 'universe';
$parameters['IdServ'] = '5';
$parameters['IdCard'] = '555';
$parameters['Controllo'] = '';
echo $s_WSTIPOOP."<br />";
echo $s_WSPROTOCOL."://".$s_WSHOSTNAME.$s_WSPORT."/".$s_WSPATHNAME."<br /><br /><br />";
$client = new nusoap_client($s_WSPROTOCOL."://".$s_WSHOSTNAME.$s_WSPORT."/".$s_WSPATHNAME);
$result = $client->call($s_WSTIPOOP, $parameters, '');
if ($client->fault) {
echo '<h2>Fault (Expect - The request contains an invalid SOAP body)</h2><pre>'; print_r($result); echo '</pre>';
} else {
$err = $client->getError();
if ($err) {
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
echo '<h2>Result</h2><pre>'; print_r($result); echo '</pre>';
}
}
where is the mistake? I'm reading the code from nusoap source, trying with different arguments without success
A: I have to set $wsdl parameter to true in order to work
$client = new nusoap_client($s_WSPROTOCOL."://".$s_WSHOSTNAME.$s_WSPORT."/".$s_WSPATHNAME, true);
A: Error is here
$result = $client->call($s_WSTIPOOP, $parameters, '');
From where $client is comming?
I think you forgot to create the object for nusoap_client class
$client = new nusoap_client();
After Your Edit
send the parameters as you are sending them in your first example,
$result = $client->call($s_WSTIPOOP, array("parameters" => $parameters), '');
A: This helped.
Wrong namespace.
If you are upgrading an old webservice, the owner may have kept the same old one, do not update it.
| |
doc_23532029
|
But for some case if second app's main activity launches another activity and it finish the main activity then how I can send result to first app's main activity from second app's another activity?
A: Let's assume that you have three activities - A in the first app and B and C in the second app.
I see two possible scenarios:
*
*Chaining the result - A starts for result B starts for result C. The result from C is delivered to B, B delivers it as a result to A.
*Using Intents directly - don't start B for result, but use explicit Intents to return the result to A. This means you should set A's launch mode to singleTop and use appropriate flags to make sure you won't end up with multiple instances of the activity. You can also fire Intents not directly to A, but to a BroadcastReceiver that will handle them accordingly.
| |
doc_23532030
|
The scenario: I've got a text box, with fancy typeahead. Beside that, I have a button to append the newly found value into a second field. I use the second field to drive a repeat control showing all values chosen to date. Code below
The result: To test this, type 'ab' in the field, and select any choice, then click on the 'add' link. The repeat shows (, abcd) as you would expect. Test 2, repeat that process twice. The repeat will show (, abcd, ab, abcd). For some reason, the 'ab' is being added into the second field. The third test - type ab, choose a choice, add. Type 'bc', choose a choice, add. Type cd, but instead of choosing a choice, click the save button. The repeat then shows (, abcd, bc, abce, cd). I can't explain that at all.
The workaround: To get this to work properly, I can change the link's refresh type from partial to full. I have no idea why this makes it work, but it does. I don't know if I really want to do that, but I will if I have to. This is on a fairly complex form and I'd rather not do a full refresh unless I have to.
The code: Here's a cut-down xpage that demonstrates the problem:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" xmlns:xc="http://www.ibm.com/xsp/custom">
<xp:this.data>
<xp:dominoDocument var="document1" formName="Test">
</xp:dominoDocument>
</xp:this.data>
<xp:panel id="mainPanel">
<xp:button value="Save" id="button1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete">
<xp:this.action>
<xp:saveDocument var="document1"></xp:saveDocument>
</xp:this.action>
</xp:eventHandler>
</xp:button>
<xp:inputText id="objName1" value="#{document1.objName}">
<xp:typeAhead mode="full" minChars="2" valueMarkup="true"
var="searchValue" id="typeAhead1">
<xp:this.valueList><![CDATA[#{javascript: //In here I usually do some searching to find a result set, but for the purposes of a test, let's just do an array
var mapResults:java.util.TreeMap = new java.util.TreeMap();
mapResults.put("abcd", "abcd");
mapResults.put("abce", "abce");
mapResults.put("abcf", "abcf");
mapResults.put("abcg", "abcg");
mapResults.put("abch", "abch");
mapResults.put("abci", "abci");
//Now format the results
var returnList = "<ul>";
//All results are in the TreeMap and are sorted. Now add them to the output
var iter:Iterator = mapResults.entrySet().iterator();
while (iter.hasNext()) {
var nextEntry = iter.next();
returnList += "<li>" + nextEntry.getValue() +"</li>";
}
//Lastly, close off the UL tag and return
returnList += "</ul>";
return returnList;}]]></xp:this.valueList>
</xp:typeAhead>
</xp:inputText>
<xp:link escape="true" text="Add Another Object" id="link1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="partial" id="eventHandler1" refreshId="mainPanel">
<xp:this.action><![CDATA[#{javascript:var currentVals = document1.getItemValueArray("addObjName");
//check for null value in first item in array - happens
//if we clear the array from the 'cross' buttons in the repeat
if (currentVals[0] == null) {
currentVals = new Array("");
}
//get the value from the object name field and whack it on the end
var newValue = getComponent("objName1").getValue();
//Put the value into a test field so we can prove that the value wasn't added below
document1.replaceItemValue("test1", newValue);
//Now add it to the field - where is the search text coming from?
currentVals.push(newValue);
document1.replaceItemValue("addObjName", currentVals);
getComponent("objName1").setValue("");
}]]></xp:this.action>
</xp:eventHandler>
</xp:link>
<xp:repeat id="repeat1" rows="30" var="rowData" indexVar="index"
repeatControls="false">
<xp:this.value><![CDATA[#{javascript:document1.getItemValueArray("addObjName")}]]></xp:this.value>
<xp:panel tagName="div">
<xp:link escape="true" id="link2" title="Remove from list">
<xp:image url="/vwicn081.gif" id="image1">
<xp:eventHandler event="onclick" submit="true"
refreshMode="partial" refreshId="mainPanel" id="eventHandler2">
<xp:this.action><![CDATA[#{javascript://remove an entry (string) from a list of strings (thanks to Mark Leusink)
Array.prototype.removeEntry = function( entry:String ) {
if ( @IsNotMember(entry, this)) {
return this;
}
var res = @Trim( @Replace(this, entry, "") );
return (typeof res == "string" ? (res.length==0 ? [] : [res]) : res);
}
var oldArray:Array = document1.getItemValueArray("addObjName");
var myArray = oldArray.removeEntry(oldArray[index]);
document1.replaceItemValue("addObjName", myArray);
}]]></xp:this.action>
</xp:eventHandler>
</xp:image>
</xp:link>
<xp:text escape="true" id="computedField1" value="#{javascript:rowData}">
</xp:text>
</xp:panel>
</xp:repeat>
<xp:text escape="true" id="computedField2">
<xp:this.value><![CDATA[#{javascript:"and here is what was added in the link:"}]]></xp:this.value>
</xp:text>
<xp:text escape="true" id="computedField3" value="#{document1.test1}">
</xp:text>
</xp:panel>
</xp:view>
Any takers? Is there a logical explanation for this, or should I just use my work-around and stop being a pedant?
UPDATE
Using the XPage above, I can also replicate the following scenario:
Step 1: Type 'abc' in the field, select 'abcd from the choices, click on the 'add' link. All good.
Step 2: Type 'ab' then wait, then type 'c', then choose 'abce'. Add again. This adds ab, abc, abce.
Step 3: Type ab then wait, then type c, then don't choose a choice, but hit Save instead. This adds ab, abc - even though the link has not been clicked to add the value to the second field.
Step 4: Type ab, wait, type c, choose 'abcf' and click Add. Only abcf is added this time.
I'm trying to reconcile this against Sven's answer below. Partial update works, so I know he's right. In step 2 above, I'm thinking that the typeahead code is executing twice, each time triggering the onClick event for the link, and lastly the onClick event for the link is running. Similar thing in Step 3 - the link isn't being clicked at all in that example, but the onClick code is still running. In step 4, after the save, typeahead is executing twice, but this time it isn't executing the onClick code.
Now I think I get it, even if I don't like it. As Sven says, The $$xspsubmitid identifies the element which submitted the data to the server - in the last submit action. So in this case it remembers the previous submit state and repeats that - so when you are doing it immediately after a plain save, you don't get any extra code, but when you are doing it after an event in the link, it submits the page in the same way that the link did - complete with onClick code.
There's probably a reason why doing this is a good thing, but my head hurts and the problem is solved! Thanks Sven!
A: It is your typeahead which updates the value of your field / your array. When typing a second or more characters in the input box, the current data in your input box is sent to the server and this updates the value in the document. When clicking onto the link, the value is added again.
EDIT:
You can fix this by changing the mode of the typeahead to "partial"
EDIT 2:
The difference between the refresh modes of a typeahed is how the data are sent to the server: In case of a full refresh, the data are sent with a POST request, in case of a partial refresh, the data are sent as a GET request.
Let's have a look at the different HTTP requests:
1.) Partial mode
2.) Full mode
As you can see in the two picutrures, in full mode there are more "fields" sent to the server. The interessting one is the $$xspsubmitid: Currently it is empty. But as soon we click the link, the field is filled with the id of the link:
The $$xspsubmitid identifies the element which submitted the data to the server. In this case the link, and the server processes the code of the link.
And now comes the problem with the typeahead in full mode:
As you can see, the $$xspsubmitid is always added to the POST request, and that's why the server executes the click event of the link for each typeahead request.
| |
doc_23532031
|
import argparse
parser = argparse.ArgumentParser(allow_abbrev=True)
parser.add_argument('-data', default=True, type=bool, help='uses the history file')
args = parser.parse_args(sys.argv[1:])
From the command line, I typed: python myscript.py -data False
Also variations with single & double quotes around False. When I examine the contents of the args namespace, args.data is always True.
So I changed the argument definition from bool to str, with a string "True" default as shown below:
parser.add_argument('-data', default="True", type=str, help='uses the history file')
I then added some massaging of the args to get the boolean value I really wanted:
if re.search("f", args.data, re.I):
args.data = False
else:
args.data = True
This workaround does work. Is there a better way to do this?
A: def my_bool(s):
return s != 'False'
parser.add_argument('-data',default=True,type=my_bool)
A: If an argument is meant to be a boolean, you should simply use store_true or store_false, so that the presence of the option itself would result in a True or False value, and the absence of the option would result in a False or True value, respectively.
From argparse's documentation:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)
A: You can use the store_false or store_true parameter to add_argument (see the argparse documentation). For example, if you want the default to be True then you could add an argument with action='store_false':
parser.add_argument('--no-data', action='store_false', help="don't use the history file")
Then args.no_data will be False if you run python command.py --no-data and True if you run python command.py without the --no-data argument.
| |
doc_23532032
|
Now, by default, we see one line per commit - the first line of the commit message. However, some of us write multi-line commit messages in which the first line doesn't say much.
Is it possible to somehow get git to print content from additional lines, in the TODO editor? I don't mind the exact format, I just need to distinguish the different commits to know what I'm doing.
A: Unfortunately, I do not think it is possible.
The only way you can customize the rebase output is through rebase.instructionFormat configuration, like this:
git config rebase.instructionFormat "..."
I tried with the option %B to return the subject with the body too, but the rebase operation fails with the following error:
error: invalid line 5: second line
error: invalid line 7: third line
error: invalid line 8: forth line
BUG: builtin/rebase.c:353: unusable todo list
Aborted (core dumped)
it seems like git considers the lines after the first one as executable code.
I checked on the git log documentation, but among the --format options I did not see anything that could replace the line feed with something else, or simply ignore it.
At this point, you could clone your repo, run git filter-branch to replace line feeds with spaces for example, and eventually run git rebase -i.
git filter-branch --msg-filter "xargs echo"
The interactive rebase does not consider the "third column", basically what you choose to log for a certain commit, so at the end you could copy and paste the output of the interactive rebase on the second repo (the one you filter-branched) inside the editor of your main repo.
Anyway, I just found a question similar to yours.
EDIT:
if you want another tool to take care of formatting the new commit message you can always create a script, like this one to replace line feed with \n
#!/bin/bash
cat | sed ':a;N;$!ba;s/\n/\\n/g'
and call it inside --msg-filter option
git filter-branch --msg-filter "cat | $(pwd)/script.sh"
EDIT: I almost forgot that filter-branch recreates each commit that matches with the filter specified, so, before editing you should replace the commits column of the interactive rebase output in the cloned repo with the real commits in the main repo. It is getting more tedious than I imagined. Let's go back to simple things: we can simulate an interactive rebase without actually calling it. The script can be improved but I think the direction is the right one:
#!/bin/bash
for commit in $(git rev-list $1..HEAD | tac)
do
git log -n 1 $commit --format="pick %h %B" | xargs echo
done;
you call it like this
./script HEAD~3
and you obtain the interactive rebase output (kind of, without comments)
pick 483ac92 first commit
pick bb739b7 second commit
pick 59f2bf0 very long commit with multiline
A:
However, some of us write multi-line commit messages in which the first line doesn't say much.
Next to the line there is the abbreviated revision hash. Given you're using vim or compatible just enter command: exclamation mark git space show space hash and hit enter:
:!git show 1234abcd
You will then see the subject line of the commit which does not say much to you, then the commit message.
In case the body of the commit message is not enough this will also display the paths that are changed and the diff of the changes.
If you're using a different editor, check the documentation on how to execute a shell command while in the editor. While rebasing interactively the working directory is the root of the working tree of the git repository current interactive rebase was initiated from.
Other tooling exists, for example you may want to open gitk in another window to guide your interactive rebase. Press g to enter a revision and jump to it.
See also A Note About Git Commit Messages (by Tim Pope; Apr 2008).
Hint: Consider to use the interactive rebase to reword those commit messages their subject lines do not say much to you until they do first.
| |
doc_23532033
|
The problem arises when I'm trying to work with the html below.
<tr>
<td>
<table class="EPSBResultGrid" cellspacing="0" rules="cols" border="1" style="border-color:DarkGray;border-collapse:collapse;">
<tbody><tr class="EPSBResultGridHeader">
<th scope="col">Cred</th><th scope="col">Description</th><th scope="col">Effective</th><th scope="col">Expiration</th><th scope="col">Restricted To</th>
</tr><tr class="EPSBResultGridHeader">
<td colspan="9" style="border-width:1px;border-style:solid;font-weight:bold;">Do Not Print (00)</td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_CRED_CODE">RANK1</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_CRED_DESC">Rank I</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EFF_DATE_txtDateYYYY">2000<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EFF_DATE_txtDateYYYY" value="2000"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl03$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl03_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl03_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl03_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridHeader">
<td colspan="9" style="border-width:1px;border-style:solid;font-weight:bold;">Cert Issued (30)</td>
</tr><tr class="EPSBResultGridAlternatingItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_CRED_CODE">G20</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_CRED_DESC">Middle School Teaching Field: Social Studies</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EFF_DATE_txtDateYYYY">1995<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EFF_DATE_txtDateYYYY" value="1995"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl05$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl05_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl05_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl05_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_CRED_CODE">G71</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_CRED_DESC">Middle School Teaching Field: Mathematics</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EFF_DATE_txtDateYYYY">1995<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EFF_DATE_txtDateYYYY" value="1995"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl06$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl06_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl06_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl06_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridAlternatingItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_CRED_CODE">PCS</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_CRED_DESC">Provisional Certificate For Guidance Counselor, Secondary Grades 5-12</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateMM">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateMM" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EFF_DATE_txtDateYYYY">2016<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EFF_DATE_txtDateYYYY" value="2016"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl07$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl07_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl07_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl07_ORG_NAME"></span></td>
</tr><tr class="EPSBResultGridItem">
<td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_CRED_CODE">PMBF</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_CRED_DESC">Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateMM">07<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateMM" value="07"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateDD">01<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateDD" value="01"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EFF_DATE_txtDateYYYY">2015<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EFF_DATE_txtDateYYYY" value="2015"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl01" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl02" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl03" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl04" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl04" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><nobr><span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateMM">06<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateMM" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateMM" value="06"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateDD">30<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateDD" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateDD" value="30"></span>-<span class="" id="ctl00$ContentPlaceHolder1$ctl00$ctl08$EXP_DATE_txtDateYYYY">2020<input type="hidden" id="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateYYYY" name="ctl00_ContentPlaceHolder1_ctl00_ctl08_EXP_DATE_txtDateYYYY" value="2020"></span></nobr><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl06" style="color:Red;display:none;">You must enter a day.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl07" style="color:Red;display:none;">You must enter a month.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl08" style="color:Red;display:none;">You must enter a year.</span><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl09" evaluationfunction="cb_verifydate_ctl00_ContentPlaceHolder1_ctl00_ctl08_ctl09" style="color:Red;visibility:hidden;">Invalid Date.</span></td><td><span id="ctl00_ContentPlaceHolder1_ctl00_ctl08_ORG_NAME"></span></td>
</tr>
</tbody></table><br><span><span>Note: Suspended and revoked credentials are shown with red text with a strike through line.</span></span>
</td>
</tr>
The the info (class="EPSBResultGridItem" & class="EPSBResultGridAlternatingItem") below the headers (class="EPSBResultHeader") are not nested underneath them and as a result I've been having trouble finding a way to make sure that the information under each header is grouped with the correct header.
This is my code:
count = 0
header = tree.xpath(
'.//table/tr[@class="EPSBResultGridHeader"]')
difference = 10 - len(header)
for i in range(0, difference):
header.append('')
for license_row in header:
count = count + 1
try:
header_data = license_row.xpath(".//text()")
header_data = clean(header_data)
nested_data = license_row.xpath(".//following-sibling::tr//text()")
nested_data = clean(nested_data)
print count, header_data
print count, nested_data
except AttributeError:
header_data = ''
# Append licensure data
if count == 1:
lheader1.append(header_data)
lheader_info1(nested_data)
if count == 2:
lheader2.append(header_data)
lheader_info2(nested_data)
if count == 3:
lheader3.append(header_data)
lheader_info3(nested_data)
if count == 4:
lheader4.append(header_data)
lheader_info4(nested_data)
if count == 5:
lheader5.append(header_data)
lheader_info5(nested_data)
My end goal is to have an output like this:
>>>print lheader_info2
['RANK1', 'Rank I', '07-01-2018', '06-30-2021']
>>>print lheader_info3
['G20', 'Middle School Teaching Field: Social Studies----', 'G30', 'Middle School Teaching Field: English And Communications----', 'ILE2', 'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II', '07-01-2017', '06-30-2021', 'ILM2', 'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II', '07-01-2017', '06-30-2021', 'ILV2', 'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II', '07-01-2018', '06-30-2021', 'PMBF', 'Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)', '07-01-2016', '06-30-2021']
I'm using lxml but I've also used BeautifulSoup if that seems like a better way to do it.
A: I would locate every subheader and iterate over the next tr siblings breaking the loop once another header is met, or reached the end of the table:
from collections import defaultdict
from pprint import pprint
import requests
from bs4 import BeautifulSoup
url = "https://wd.kyepsb.net/EPSB.WebApps/KECI/view_data.aspx?id=37161"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
data = defaultdict(list)
table = soup.find("table", class_="EPSBResultGrid")
for header in table.select("tr.EPSBResultGridHeader")[1:]:
header_name = header.get_text(strip=True)
for row in header.find_next_siblings("tr"):
if "EPSBResultGridHeader" in row.get("class", []):
break
data[header_name].append(row.td.get_text(strip=True))
pprint(dict(data))
Prints:
{'Cert Issued (30)': ['G20', 'G30', 'ILE2', 'ILM2', 'ILV2', 'PMBF'],
'Do Not Print (00)': ['RANK1'],
'History (97)': ['ILE2', 'ILM2', 'ILV2', 'RANK1']}
The [1:] slice here is to skip the initial top-level table header.
A: using lxml
def pair():
tree = html.fromstring(requests.get(url).content)
# get table and iterate over the trs
iter_trs = tree.cssselect("table.EPSBResultGrid")[0].iter("tr")
# skip the initial tr
next(iter_trs)
# first EPSBResultGridHeader
start = next(iter_trs).xpath("td//text()")[0]
nodes, tmp = {}, []
# iterate over the rest of the nodes
for node in iter_trs:
# if we find another EPSBResultGridHeader, yield what we have and start again.
if node.get("class") == "EPSBResultGridHeader":
nodes[start] = tmp
start, tmp = node.xpath("td//text()")[0], []
else:
tmp.append([td.xpath("normalize-space(.)").replace(ur"\xa0", "") for td in node.xpath("./td")])
return nodes
Which would give you:
{'Cert Issued (30)': [[u'G20',
u'Middle School Teaching Field: Social Studies',
u'--',
u'--',
u''],
[u'G30',
u'Middle School Teaching Field: English And Communications',
u'--',
u'--',
u''],
[u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2017',
u'06-30-2021',
u''],
[u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2017',
u'06-30-2021',
u''],
[u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2018',
u'06-30-2021',
u''],
[u'PMBF',
u'Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)',
u'07-01-2016',
u'06-30-2021',
u'']],
'Do Not Print (00)': [[u'RANK1',
u'Rank I',
u'07-01-2018',
u'06-30-2021',
u'']],
'History (97)': [[u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2012',
u'06-30-2017',
u''],
[u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2012',
u'06-30-2017',
u''],
[u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2013',
u'06-30-2018',
u''],
[u'RANK1', u'Rank I', u'12-15-1995', u'06-30-2018', u'']]}
If you want flat lists use extend tmp.extend(td.xpath("normalize-space(.)").replace(u"\xa0", "") for td in node.xpath("./td")):
{'Cert Issued (30)': [u'G20',
u'Middle School Teaching Field: Social Studies',
u'--',
u'--',
u'',
u'G30',
u'Middle School Teaching Field: English And Communications',
u'--',
u'--',
u'',
u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2017',
u'06-30-2021',
u'',
u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2017',
u'06-30-2021',
u'',
u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2018',
u'06-30-2021',
u'',
u'PMBF',
u'Provisional Certificate For Teaching In The Middle Grades 5-8 (And For Other Assignments As Identified By Kentucky Program Of Studies)',
u'07-01-2016',
u'06-30-2021',
u''],
'Do Not Print (00)': [u'RANK1', u'Rank I', u'07-01-2018', u'06-30-2021', u''],
'History (97)': [u'ILE2',
u'Professional Certificate For Instructional Leadership -- Early Elementary School Principal, Grades K-4; Level II',
u'07-01-2012',
u'06-30-2017',
u'',
u'ILM2',
u'Professional Certificate For Instructional Leadership--Middle Grade School Principal, Grades 5-8; Level II',
u'07-01-2012',
u'06-30-2017',
u'',
u'ILV2',
u'Professional Certificate For Instructional Leadership--Supervisor Of Instruction, Grades K-12; Level II',
u'07-01-2013',
u'06-30-2018',
u'',
u'RANK1',
u'Rank I',
u'12-15-1995',
u'06-30-2018',
u'']}
| |
doc_23532034
|
Here's a small example of the input:
{
"type": "FeatureCollection",
"features": [
{
"id": 16683828,
"properties": {
"facility": "hallway"
},
"type": "Feature",
"geometry": {
"type": "Path",
"coordinates": [
[
0,
379.64,
289.412
],
[
3,
379.629,
289.768,
379.346,
290.059,
378.986,
290.066
],
[
1,
373.156,
290.066
],
[
1,
373.156,
298.5
],
[
1,
373.156,
299.469
],
[
4
]
]
}
}
]
}
Here's roughly what I'd like to transform this into:
{
"type": "FeatureCollection",
"features": [
{
"properties": {
"facility": "hallway",
"id": 16683828
},
"type": "Feature",
"geometry": {
"type": "LineString",
"properties": {
"curves": [
{
"coordinate_position": 1,
"control_points": [379.629, 289.768, 379.346, 290.059]
}
]
},
"coordinates": [
[
379.64,
289.412
],
[
378.986,
290.066
],
[
373.156,
290.066
],
[
373.156,
298.5
],
[
373.156,
299.469
]
]
}
}
]
}
The part that's tripping me up is using conditionals inside of a larger jq formatting expression. For each feature, I'm trying to check if geometry.type == "Path", and if so, strip the first item from each coordinate (I don't need it), and then move all but the last two items from the coordinate into a object in a properties.curves array, noting the position within the "coordinates" array, and the extra data. If the geometry.type != "Path", I just want to copy the geometry item to my output.
Here's the script I have so far, including the incorrect conditional logic beginning at geometry: {:
cat input.json | jq '. |
{
type: .type,
features: [
.features[] | {
type: .type,
properties: {
display_name: .properties.display_name,
id: .id
}
geometry: {
if .geometry.type == "Path" then
type: "LineString"
else
type: .geometry.type
end
}
}
]
}'
Of course what's not working here is the conditional directly inside an object. My best guess is that I need to use more jq pipes but I just haven't been able to figure out how to wrangle it into the correct format.
A: *
*Many would suggest writing "jq ... FILE" instead of 'cat FILE | jq ...'
*You don't need the initial '. |'
*Here is a variant of your jq filter that produces the results shown below:
{
type: .type,
features: [
.features[] | {
type: .type,
properties: {
display_name: .properties.facility,
id: .id
},
geometry: {
type: (if .geometry.type == "Path" then "LineString"
else .geometry.type
end)
}
}
]
}
Output:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"display_name": "hallway",
"id": 16683828
},
"geometry": {
"type": "LineString"
}
}
]
}
| |
doc_23532035
|
Now I understand what break and labels do but I can't wrap my head around why the value ends up being 55 at the end?
Ok so the for loop with var i will loop 4 times then at 5 it breaks out to label:outermost and same with j so the first iteration i = 4 and j = 4 and num = 2. I guess this part confuses me.. at what point does the code stop. My first instinct if I were to code this from scratch is to have an outside variable and set the condition on that. But with the below code I don't get where the control structure lies and the final value. Appreciate any help or to be pointed in the right direction, thanks.
var num = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
num++;
}
}
alert(num);
A: This nested loop is emulating an odometer. i is the 10's digit, j is the 1's digit. Every time the 1's digit changes, num is incremented; at the start of each iteration, num contains the odometer's value.
The loop stops when both i and j are 5. At that point, the odometer would read 55, and that's what is in num.
A: When i was 0 to 4, the innermost loop is executed 50 times. When i = 5, the innermost loop is executed just 5 times until it reached i==5 && j==5 and jumped out. So it's total of 55 times.
| |
doc_23532036
|
Goal:
Add script to my Ruby app which can read a local JSON file, parse it to a Ruby hash, and access the properties within it.
System: CentOS 7
File: Locally saved /tmp/valid.json file:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
(That object borrowed from Wikipedia's article on JSON in an attempt to make sure that my problem isn't invalid JSON.)
Code:
require 'json'
data = File.read("/tmp/valid.json")
$evm.log(:info, data) #writes to log file, where I can see content of my JSON file
$evm.log(:info, "is data a hash ? ")
$evm.log(:info, data.is_a?(Hash).to_s) # prints false
$evm.log(:info, "is data a string? ")
$evm.log(:info, data.is_a?(String).to_s) # prints true
$evm.log(:info, "can I parse data?")
valid_ob = JSON.parse(data)
$evm.log(:info, "just parsed it, now print it")
$evm.log(:info, valid_ob)
That last line prints:
NoMethodError: undefined method `gsub' for #<Hash:0x0000000020951f
a8>
Why can't Ruby parse this string?
A: Have you tried printing the object normally, instead of using "$evm.log"? JSON.parse returns a hash, and it seems as though your logger is attempting to run a non-existent gsub method on it.
A: The problem is something in whatever you have assigned to $evm. The error message:
NoMethodError: undefined method `gsub' for #<Hash:>
indicates that when you call
$evm.log(:info, valid_ob)
the log method is attempting to call gsub on valid_ob. Most likely, log is meant to accept only strings and does no type checking on the object it receives.
If you need a simple, interactive way to run this Ruby code without using this $evm object, just run irb in your console and start typing in your Ruby code for parsing the JSON data:
require 'json'
=> true
data = File.read('/tmp/valid.json')
data.class
=> String
hash = JSON.parse(data)
hash.class
=> Hash
hash
=> {"firstName"=>"John", "lastName"=>"Smith", "isAlive"=>true, "age"=>27, "address"=>{"streetAddress"=>"21 2nd Street", "city"=>"New York", "state"=>"NY", "postalCode"=>"10021-3100"}, "phoneNumbers"=>[{"type"=>"home", "number"=>"212 555-1234"}, {"type"=>"office", "number"=>"646 555-4567"}], "children"=>[], "spouse"=>nil}
| |
doc_23532037
|
Thanks!
A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="112dp"
android:layout_toRightOf="@+id/textView2"
android:background="@drawable/ic_launcher"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="asdsadsaddsadsadasdasdadasd" />
</RelativeLayout>
so I tried this for you, and layout expands or shrinks the as size of textview
A: All you need to do is the following:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="asdsadsaddsadsadasdasdadasd" />
| |
doc_23532038
|
Sub py_launcher_8()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Long
errorCode = wsh.Run("C:/Users/belose/PycharmProjects/week2/venv/Scripts/python.exe" & " " & "C:\Users\belose\PycharmProjects\week2\VGM\VGM_eval.py", windowStyle, waitOnReturn)
If errorCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
End Sub
Then I had to move to another PC, where python is located in anaconda environment: C:\Users\belose\AppData\Local\Continuum\anaconda3\python.exe
Sub py_launcher_8()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Long
errorCode = wsh.Run("C:\Users\belose\AppData\Local\Continuum\anaconda3\python.exe" & " " & "C:\Users\belose\PycharmProjects\DRM\venv\VGM\VGM_eval.py", windowStyle, waitOnReturn)
If errorCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
End Sub
The VBA now doesn't start the python script and returns error code 1.
The python script itself is OK.
What could be the reason?
A: I would suggest you to write a test.py script with print ("Hello World..!!") and run it to check the if the problem is due to path of python.exe or execution of python script.
if it is running then you should check your python script and if not then you should verify the python.exe path.
To Locate the python path you may use the following steps:
*
*From the Start Menu open the Anaconda Prompt.
*If you want the location of a Python interpreter for a conda environment other than
the root conda environment, run activate environment-name.
*Run where python.
| |
doc_23532039
|
Content-Type:text/html
I would like to use it to host CSS and JS script files. Is it possible to have the browser ignore the content type and load the file as CSS or JS when using:
<link rel="stylesheet" href="css/main.css">
A: Is there no way you can override the content type from the file itself? E.g. if you put this in a php file the content-type should be altered:
<?php header('Content-type: text/css') ?>
You probably aren't using php, but perhaps something like that is possible on your web server.
In any case you should be able to use JS-files with a text/html content-type anyway. Now stylesheets ... I guess you could load them into your html dynamically if there really is no other way.
Using jQuery because I'm lazy:
<style id="dynamic-css"></style>
<script>
$('#dynamic-css').load('css/main.css');
</script>
| |
doc_23532040
|
<div id="parent" style=height:"100%">
<div id="mainbody"></div>
<div id="footer"></div>
</div>
I want the footer div to be pinned at the bottom of the screen, and mainbody top be on top. There may be a lot of vertical content in mainbody, so I want the scroll bar to only show in the mainbody div. Here is a crudely drawn example:
https://imgur.com/a/lNyOZme
How can I achieve this?
A: Assigning a height to the bottom div won't always guarantee you that it'll be placed at the bottom. I'd recommend to simply make use of position property in css. The code below will work with any height you'll assign to your parent container -
#footer{
position: absolute;
bottom: 0px;
}
P.S. - In case the main body is not that big that it doesn't occupy the whole screen and you still want your footer to be at bottom, assign this height: 100vh to your parent container and use the same above code. It should look like this:
#parent{
height: 100vh;
}
#footer{
position: absolute;
bottom: 0px;
}
A: You can achieve this layout pretty easily with flexbox and a bit of height calculations.
body {
margin: 0;
}
main {
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
}
section {
background: ivory;
padding: 2rem;
overflow-y: scroll;
height: calc(100% - 50px);
}
footer {
height: 50px;
background: royalblue;
color: white;
padding: 1rem;
}
footer p {
text-align: center;
}
<main>
<section>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut vitae mauris commodo velit cursus maximus. Vivamus congue, massa sit amet egestas tempus, nisl arcu vestibulum diam, auctor porta ligula ligula aliquam dolor. Aliquam tincidunt ligula id arcu eleifend, ut viverra neque faucibus. Sed a augue arcu. Sed mattis neque sit amet elit maximus, eget suscipit felis tristique. Sed in tincidunt ipsum. Nulla lectus magna, eleifend eget risus vel, blandit euismod leo. Vivamus egestas, libero sit amet vulputate volutpat, justo massa venenatis libero, quis consectetur ante erat vitae magna. Nullam dictum luctus purus non porta. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p>
<p>
Nullam vehicula ullamcorper convallis. Nunc non metus scelerisque, fringilla nisl nec, vulputate libero. Fusce mattis, enim in laoreet pretium, sapien nisi pellentesque felis, non pellentesque felis justo non est. Duis mollis euismod diam, vitae suscipit orci laoreet eu. Ut pulvinar iaculis massa ut mollis. Nunc a elementum velit. Nam porttitor turpis sit amet enim tempor cursus. Duis tempus lectus nibh, quis luctus neque euismod vel. Vivamus porta sem sed ante ultricies, a pretium mi fringilla. Sed interdum elit mi, a scelerisque quam accumsan eu. Phasellus non nulla fringilla, ultrices magna ut, accumsan orci. Curabitur bibendum nisi quis felis eleifend, ut feugiat mauris elementum. Pellentesque tempor eu sem vestibulum laoreet. Etiam ut vestibulum est, eu placerat tellus. Vivamus ac feugiat metus. In hac habitasse platea dictumst.
</p>
<p>
Suspendisse in urna ac erat vestibulum porttitor eget et massa. Integer faucibus ligula sem, eu consectetur leo pellentesque in. Phasellus faucibus turpis non turpis rhoncus ornare. Maecenas nec feugiat erat. Maecenas nec velit tempus, blandit tellus ac, ullamcorper nisi. Etiam ullamcorper nisi id hendrerit tristique. Nullam neque tellus, tincidunt sed congue quis, finibus non nunc. Aliquam vel mauris ante. Aliquam erat volutpat. Integer condimentum, odio in tincidunt sagittis, felis nulla auctor dolor, a malesuada magna nibh quis lectus.
</p>
<p>
Phasellus condimentum augue sit amet erat scelerisque cursus. Sed eget egestas leo, eu placerat eros. Suspendisse potenti. Maecenas varius vestibulum libero, a ullamcorper nisl convallis vel. Donec a ligula id nibh porttitor consequat. Quisque sodales, diam eget finibus dignissim, dui libero fermentum arcu, eget finibus felis orci eu erat. Nullam eleifend sem vitae nulla convallis varius. Suspendisse posuere neque pulvinar consequat faucibus. Mauris quis mauris eu turpis feugiat vestibulum. Etiam laoreet quam ipsum, mollis iaculis neque laoreet et. Quisque volutpat nisl ut sapien tempus, sed vestibulum mauris pharetra. Cras lacinia in arcu eget vestibulum. Maecenas non suscipit velit.
<p>
Praesent convallis fringilla mauris ut tincidunt. Vivamus aliquet ac magna at vehicula. Proin sapien lacus, malesuada id risus vitae, faucibus eleifend sem. Vestibulum nibh elit, dignissim nec augue a, finibus tempus mauris. Donec sed pharetra elit, a imperdiet ipsum. Nullam et est sed risus rutrum finibus. Suspendisse sit amet sem ut quam dignissim rutrum in in odio. Aliquam a lorem orci. Pellentesque varius faucibus ultricies. Cras et pulvinar diam. Praesent id pretium tellus. Donec nec turpis massa. Vivamus ac diam pharetra, accumsan elit vel, efficitur dui. Duis sollicitudin orci nisl, sed gravida urna sagittis vitae.</p>
</section>
<footer>
<p>
footer content
</p>
</footer>
</main>
| |
doc_23532041
|
I am clicking upload button and then we select a file that need to be uploaded.Then the upload button is changed to change and name of selected file is displayed next to it.But if we are having a big file name i want to limit the file name characters to about 50.How to achieve this ?
<div class="span5">
<div class="fileupload fileupload-new"
data-provides="fileupload">
<span class="btn btn-file" id="uploadRef"> <span class="fileupload-new">Upload
Referral Script</span> <span class="fileupload-exists">Change</span>
<form:input type="file" path="refuploadScript"
onchange="return checkFileExists();" />
</span> <span class="fileupload-preview"></span>
<a href="#"
class="close fileupload-exists" data-dismiss="fileupload"
style="float: none">x</a>
</div>
</div>
A: For doing this, first hide the default file name display span.
Then process the file name and display it separately.
So, to hide the default :
<span class="fileupload-preview" style="display: none;"></span>
on form input change , call the following script function
function truncatefile() // calling a function on change or select
{
var fup = document.getElementById('patientupload'); //store file by ID
var file = fup.files[0]; // store value of file
var filePath = fup.value;
var name;
if(filePath=="")
{
document.getElementById('fname').innerHTML = '';
}
else
{
name=filePath.replace(/^.*[\\\/]/, '');
var ext = filePath.substring(filePath.lastIndexOf('.') + 1);//getting file extension
var fileName = name.substring(0,name.length-4); // storing 0th position till extension begining
var fileNameNew="";
if(fileName.length > 30)
{
var fileNameFst=fileName.substring(0,24); //firstpart of file
var fileNameLst=fileName.substring(fileName.length-5,fileName.length); //last part of file
fileNameNew=fileNameFst+ "...." + fileNameLst+"."+ext; //combine all parts
}
else
{
fileNameNew=fileName+"."+ext; //if length less than 30
}
document.getElementById('fname').innerHTML = fileNameNew;
}
| |
doc_23532042
|
Data at begining
Next, I have to create new feature isMale by using where()
This feature should show gender by value(0 and 1), if gender is "female" than isMale equals to 0, and analogical gender="male" than isMale=1
And this feature should swap my "Gender" or just concatenate to my dataset
I don't get how to use where() method for creating feature
A: you don't need np.where. since you're assigning boolean value, just check if Gender= Male is True or False, then convert True/False to int will get you 0 and 1
df['isMale'] = df['Gender'].eq('Male').astype(int)
A: To replace your gender column:
import numpy as np
import pandas as pd
df['Gender'] = np.where(df['Gender'] == "Male", 1, 0)
To add a new column:
import numpy as np
import pandas as pd
df['isMale'] = np.where(df['Gender'] == "Male", 1, 0)
A: Use assign and then the np.where
import numpy as np
import pandas as pd
...
df = df.assign(
isMale=np.where(df['Gender'] == 'Female', 0, 1)
)
| |
doc_23532043
|
1>I have successfully made chunks of 10 secs with one m3u8 file by this command-
ffmpeg -i song.mp3 -c:a aac -b:a 64k -vn -hls_time 10 -hls_list_size 0 abc.m3u8
2>Tried this command also
MP4Box -dash 10000 -frag 1000 -rap -segment-name myDash -subsegs-per-sidx 5 -url-template test.mp4
But not able to make .m4s chunks with one init.mp4.
A: Now,I can make .m4s segments and one init.mp4 by using below command.
MP4Box -dash 10000 -out video.mpd -dash-profile live -segment-name mv_ -rap video.mp4
REFERENCE: Calculate .m4s segment file suffix in HTML5 video streaming when user seeks to another time
| |
doc_23532044
|
You see the problem arises when I try to pass the range of values under "Products". Right now I'm having to pass the arguments manually as the number of products may vary with clients, as you can see below.
Link to a sample sheet
Following is my sample code-
*
*Code.gs
function doGet(e){
const tmpl = HtmlService.createTemplateFromFile('form');
tmpl.orderno = e.parameter.orderno;
tmpl.clientname = e.parameter.client;
tmpl.productsHtmlString = getProductsHtmlString(e.parameter.products.split(","));
return tmpl.evaluate();
}
function getProductsHtmlString(arr){
const productsHtmlArray = [];
for(let i in arr){
productsHtmlArray.push(`<div class="productrow"><input id="product${Number(i)+1}" type="text" class="validate" disabled value="${arr[i]}"><label for="product${Number(i)+1}" class="active">Product</label></div>`);
}
return productsHtmlArray.join("");
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
*form.html
<head>
<?!= include('stylesheet'); ?>
</head>
<body>
<div class="row">
<input id="orderno" type="text" disabled value="<?= orderno; ?>" class="validate">
<label for="orderno" class="active">Order Number</label>
</div>
<div class="row">
<input id="clientname" type="text" disabled value="<?= clientname; ?>" class="validate">
<label for="clientname" class="active">Client Name</label>
</div>
<div id="orderdetails">
Product Details
<?!= productsHtmlString; ?>
</div>
</body>
*stylesheet.html
<style>
.row{
margin-top: 7.5px;
margin-bottom: 7.5px;
}
</style>
Note: Updated the question to properly reflect my query.
A: Following solution works for me. The changes I made-
*
*In the sheet, I updated Hyperlink to have only rowindex="&row($B2:$B)&" as query string to the URL. This gives me the index of the row, which I use it in getRange() to fetch the orderno, client and products.
*In the doGet() function in Code.gs, I made the following changes-
Code.gs
function doGet(e){
const ws = ss.getSheetByName(sheetName);
const template = HtmlService.createTemplateFromFile('form');
const rowIndex = Number(e.parameter.rowindex);
template.orderno = ws.getRange(rowIndex, 2).getValue();
template.clientname = ws.getRange(rowIndex, 3).getValue();
const productsArr = ws.getRange(rowIndex, 4, 1, ws.getLastColumn()).getValues()[0]
.filter(arg => arg !== '');
template.productsHtmlString = getProductsHtmlString(productsArr);
return template.evaluate();
}
| |
doc_23532045
|
**Routing Error**
No route matches [GET] "/"
I honestly do not know how to debug this
This is what's in the index file
<% @snippet.each do |snippet| %>
<h2><%= snippet.title %></h2>
<%end%>
And for my routes:
Josegomez::Application.routes.draw do
resources :snippets
Here is the video I been following it requires you to be a member though but I figured most would ask about it http://tutsplus.com/tutorial/how-to-deploy-your-first-rails-app/
Here is what I got when I typed rake routes
Jose-Gomezs-MacBook-Pro:josegomez josegomez$ rake routes
snippets GET /snippets(.:format) snippets#index
POST /snippets(.:format) snippets#create
new_snippet GET /snippets/new(.:format) snippets#new
edit_snippet GET /snippets/:id/edit(.:format) snippets#edit
snippet GET /snippets/:id(.:format) snippets#show
PUT /snippets/:id(.:format) snippets#update
DELETE /snippets/:id(.:format) snippets#destroy
Hey may be using a older version...
A: You need route to root
Add this to routes.rb
root :to => 'snippets#index'
| |
doc_23532046
|
#define MYCHAR_1 0xC3
#define MYCHAR_2 0xB6
(These are the two bytes that form the UTF-8 character "ö")
Is it possible to create a macro that takes the prefix (in this example "MYCHAR") and yields the string "\xC3\xB6"? (i.e. "ö")
In other words can the C-preprocessor create a static string (or array) out of static array-elements?
The end result should be usable by a function that has a string as parameter, for example:
printf(MY_MAGIC_MACRO(MYCHAR));
should print "ö".
A: With numeric definitions as shown, it is moderately hard. However, assuming you have a C99 or later compiler, you can use a compound literal:
#define MYCHAR_1 0xC3
#define MYCHAR_2 0xB6
printf("%s", (char []){ MYCHAR_1, MYCHAR_2, '\0' });
If you're stuck with C89, then you probably don't have any good options other than to define an array variable and pass that to the function.
If you want a MY_MAGIC_MACRO(MYCHAR) to work, then you have to know how many names there are (2 per prefix in this example):
#define MY_MAGIC_MACRO(x) ((char []){ x##_1, x##_2, '\0' })
printf("%s\n", MY_MAGIC_MACRO(MYCHAR));
#include <stdio.h>
#define MYCHAR_1 0xC3
#define MYCHAR_2 0xB6
#define MY_MAGIC_MACRO(x) ((char []){ x##_1, x##_2, '\0' })
int main(void)
{
printf("%s\n", (char[]){ MYCHAR_1, MYCHAR_2, '\0' });
printf("%s\n", MY_MAGIC_MACRO(MYCHAR));
return 0;
}
The output on a UTF-8 terminal is ö twice on separate lines.
A: The closest thing to what you want to achieve that I can come up with:
#define MYCHAR_1 "\xC3"
#define MYCHAR_2 "\xB6"
const char STR [] = "ABC" MYCHAR_1 "DEF" MYCHAR_2;
| |
doc_23532047
|
struct product_t
{
char *product;
int id;
float price;
struct product_t *next;
};
I'm asked to make a create function as given below:
struct product_t *createProduct(char *data, int id)
so I thought of creating a new struct called data with pointers referring to the product struct:
struct data {
struct product_t *product;
struct product_t *price;
struct product_t *id;
struct data *next;
};
But when I use the create function like I did below I get errors:
struct product_t *createProduct(char *data, int id) {
struct data *New = malloc(sizeof(struct data));
New->product = (char*) malloc(sizeof(char)*sizeof(data)+1);
strcpy(New->product, data);
New->price = price;
New->id = id;
return New;
}
Edit:
I see now that I was quite unclear though. And I do understand how to manually allocate memory and stuff. But the point is that the data variable actually consists of the price and the product. And that is where I'm stuck since I don't know what and what not to allocate for memory.
Does anyone know what I'm doing wrong? I hope if I've been clear enough, if not let me know. Thanks in advance :)
A: Start with something like this:
#include <stdlib.h>
#include <string.h>
struct product_t
{
char* data;
int id;
};
struct product_t* createProduct(char* data, int id)
{
struct product_t *product = malloc(sizeof(struct product_t));
product->data = strdup(data); // Assumes that data is a \0 terminated string.
product->id = id;
return product;
}
void deleteProduct(struct product_t* product)
{
free(product->data);
free(product);
}
To do:
*
*Add checks to make sure that data is not NULL.
*Add code for for a linked-list of products.
*You may need to add casts, but the compiler will tell/warn you.
*...
Groetjes en succes!
A: I guess that you really wanted to do the following:
struct product_t {
char *product;
double price;
int id;
struct product_t *next;
};
struct product_t *createProduct(char *name, double price, int id) {
struct product_t *New = (product_t*) malloc(sizeof(struct product_t));
New->product = (char*) malloc(strlen(name)+1);
strcpy(New->product, name);
New->price = price;
New->id = id;
return New;
}
| |
doc_23532048
|
I don't mean an actual popup window, just the image popping out or blowing up in the screen.
So if my html code looks something like:
<p id="item1">item1 text</p>
<p id="item2">item2 text</p>
<p id="item3">item3 text</p>
When I mouse over the text “item1 text” on the HTML page, I want an image called “image1” to popup on the text. I also want to the popup to include some text above the picture. When I move the mouse pointer off of that item1 text, the popup should go away. Likewise, when I mouse over “item2 text”, image2 should pop up.
How do I do this using JavaScript, then how would I use jQuery to do it better?
I am a complete JavaScript and jQuery novice, sorry in advance for my lack of knowledge.
A: Hi I found this excellent tutorial: jQuery for Absolute Beginners, he used the <a> tag for the html code, here's how he did it:
http://jsfiddle.net/k2E7W/2/
A: Take a look at the excellent jQuery plugin Powertip which will save you lots of hazzle. Typically, such mouseover / mouseout - things are kind of tricky regarding cross browser compatibility and positioning.
Code would then look something like
$('#element')
.data('powertipjq', $('<p>Some text</p><img src="yourImage.png" />'));
.powerTip({
placement: 'e',
mouseOnToPopup: true
});
| |
doc_23532049
|
id,name,text,sth
1,"John","Text with 'c,o,m,m,a,s' and \"",qwerty
2,Bob,"",,sth
after parsing, I'd like to have in the set the same text as in input instead of:
id,name,text,sth
1,John,Text with 'c,o,m,m,a,s' and \",qwerty
2,Bob,null,null,sth
that element
"John" will parsed to string "John" ( instead of John )
"" --> ""
,, --> ,null,
etc.
I already wrote about this here, but I probably didn't make this clear enough.
I want to parse csv file to set of List<String>, do something with this and print to the stdout leaving quotes where they was. Please help me.
A: Something like this? Not using any existing parser, doing it from scratch:
public List<String> parse(String st) {
List<String> result = new ArrayList<String>();
boolean inText = false;
StringBuilder token = new StringBuilder();
char prevCh = 0;
for (int i = 0; i < st.length(); i++) {
char ch = st.charAt(i);
if (ch == ',' && !inText) {
result.add(token.toString());
token = new StringBuilder();
continue;
}
if (ch == '"' && inText) {
if (prevCh == '\\') {
token.deleteCharAt(token.length() - 1);
} else {
inText = false;
}
} else if (ch == '"' && !inText) {
inText = true;
}
token.append(ch);
prevCh = ch;
}
result.add(token.toString());
return result;
}
Then
String st = "1,\"John\",\"Text with 'c,o,m,m,a,s' and \\\"\",qwerty";
List<String> result = parse(st);
System.out.println(result);
Will print out:
[1, "John", "Text with 'c,o,m,m,a,s' and "", qwerty]
A: I have used this one:
http://opencsv.sourceforge.net/
And I was pretty satasfied with the results. I had a bunch of differently organized CSV files (it's sometimes funny what kinds of things people call CSV these days), and I managed to set up the reader for it. However, I don't think it will generate commas, but it will leave blanks where there is an empty field. Since you can fetch the whole line as an array, you can iterate it and but a comma between each iteration.
Look up the settings, there is a bunch of them, including quote characters.
| |
doc_23532050
|
Thanks
A: No, there is nothing built in to do this, you would need to roll your own.
| |
doc_23532051
|
Error Context: {
"body": {
"error": {
"code": 500,
"message": "[DATABASE_ERROR]: Attempt to read the ConditionOrderEntity of this template resulted in too many rows (2) for project [0000000000]",
"status": "INTERNAL"
}
},
"response": {
"statusCode": 500
}
}
| |
doc_23532052
|
With phonegap
It is like a turorial in how to read Quran
I want it to keep the progress the user nad made and resume it when reopen
Any help or clue?
A: You can Store the last page visited in a cookie and redirect to that after the app loads
Demo -- visit a page re-click run
https://jsfiddle.net/Ldgz38s4/
Code
//check if the lastpage exists and redirect to the page
if ($.cookie('lastpage')) {
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#"+$.cookie('lastpage'))
}
//store the page visited in a cookie
$(document).on("pageshow", function (e, data) {
var pageid = $.mobile.pageContainer.pagecontainer( 'getActivePage' ).attr( 'id' );
$.cookie('lastpage', pageid)
});
you need include the Jquery cookie plugging for cookies to work
https://github.com/carhartl/jquery-cookie
ahh just realized you are using Cordova and may have issues with storing cookies in Android webview. If you do and the above code(setting and reading the cookie) doesn't work then
Check here on how to enable local storage instead for Android webview
Android webview & localStorage'
and here on how to store and read data within the App, its easy
http://www.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/
| |
doc_23532053
|
Something like this:
public class MyObjectModel
{
public int Variable1 {get;set;}
public int VariableN {get;set;}
}
Let's say variable1 holds the value of a count and I know that the count will never get to become very large (ie. number of upcoming appointments for a certain day). For now, I've put these data types as int. Let's say it's safe to say that someone will book less than 255 appointments per day. Will changing the datatype from int to byte affect performance much? Is it worth the trouble?
Thanks
A: No, performance will not be affected much at all.
For each int you will be saving 3 bytes, or 6 in total for the specific example. Unless you have many millions of these, the savings in memory are very small.
Not worth the trouble.
Edit:
Just to clarify - my answer is specifically about the example code. In many cases the choices will make a difference, but it is a matter of scale and will require performance testing to ensure correct results.
To answer @Filip's comment - There is a difference between compiling an application to 64bit and selecting an isolated data type.
A: It will affect the amount of memory allocated for that variable. In my personal opinion, I don't think it's worth the trouble in the example case.
If there were a huge number of variables, or a database table where you could really save, then yes, but not in this case.
Besides, after years of maintenance programming, I can safely say that it's rarely safe to assume an upper limit on anything. if there's even a remote chance that some poor maintenance programmer is going to have to re-write the app because of trying to save a trivial amount of resources, it's not worth the pay-off.
A: Using a integer variable smaller than an int (System.Int32) will not provide any performance benefits. This is because most integer operations in the CLR will promote the variable to an int prior to performing the operation. int is considered the "natural" integer size on the systems for which the CLR was developed.
Consider the following code:
for (byte appointmentIndex = 0; appointmentIndex < Variable1; appointmentIndex++)
ProcessAppointment(appointmentIndex);
In the compiled code, the comparison (appointmentIndex < Variable1) and the increment (appointmentIndex++) will (most likely) be performed using 32-bit integers. Even if the optimizer uses a smaller data type, the CPU itself will require additional work to use the smaller data type.
If you are storing an array of values, then using a smaller data type could help save space, which might give a performance advantage in some scenerios.
A: The .NET runtime optimizes the use of Int32 especially for counters etc.
.NET Integer vs Int16?
A: Contrary to popular belief, making your data type smaller does not make access faster. In fact, it's slower. Look at bool, it's implemented as an int.
This is because internally, your CPU works with native-word-sized registers (32/64 bit these days), and you're forcing it to convert your data back and forth for no reason (well only when writing the result in memory, but it's still a penalty you could easily avoid).
Fiddling with integer widths only affects memory access, and caching specifically. This is the kind of stuff you can only figure out by profiling your application and looking at page fault counters in particular.
A: I agree with the other answers that performance won't be worth it. But if you're going to do it at all, go with a short instead of a byte. My rule of thumb is to pick the highest number you can imagine, multiply by 10, then use that as the basis to pick your value. So if you can't possibly imagine a value higher than 200, then use 2000 as your basis, which would mean you'd need a short.
| |
doc_23532054
|
var items = [{{type:t1,text:"abc"},{type:t2,data:"123"}}]
and view models:
function T1VM(t1) { ... }
function T2VM(t2) { ... }
How can I use the mapping plugin to map items to an observable array of matching view models?
A: It was too easy!
var mapping = {
create: function (options) {
if (options.data.type == "T1")
return new T1VM(options.data);
else if (options.data.type == "T2")
return new T2VM(options.data);
}
};
And then:
ko.mapping.fromJS(items, mapping);
| |
doc_23532055
|
The problem I am facing is when the user presses the HTML button the Raycast is happening as well that is because my Raycast code runs on the event 'ontouchstart'
This is unwanted behaviour for what I am trying to do.
I have tried using 'ontouchend' to detect Raycast instead, but that also doesn't solve the problem, I need some way where the Raycast code never runs if a button was every pressed.
The Raycast Code:
componentDidMount(){
window.addEventListener("touchstart",this._onTouchStart,false);
}
componentWillUnmount(){
window.addEventListener("touchstart",this._onTouchStart,false);
}
_onTouchStart = (event) =>{
event.clientX = event.touches[0].pageX;
event.clientY = event.touches[0].pageY;
const mouse = {
x: (event.clientX / this.props.gl.domElement.clientWidth) * 2 - 1,
y: -(event.clientY / this.props.gl.domElement.clientHeight) * 2 + 1
}
this.props.raycaster.setFromCamera(mouse,this.props.camera);
if(this.objects.current == null) return null;
const intersects = this.props.raycaster.intersectObjects( this.objects.current.children[1].children );
/* ** */
}
The ThreeJS Canvas I am using React Three Fiber
<Canvas>
<Component />
<CameraController />
<EnvironmentSettings />
</Canvas>
<HTMLButtons />
A: Don't add the event listener to the window element if you don't want it to capture the entire window. Be more specific with what you assign the listeners to. Perhaps you should add the event on the canvas instead, so when you click the button, the canvas doesn't need to know about it:
canvas.addEventListener("touchstart",this._onTouchStart,false);
| |
doc_23532056
|
My understanding so far
SCNTechnique can be configured with a sequence of render passes. A render pass allows for injection of a vertex and a fragment shader. These shaders are written in Metal. The Metal Shading Language Specification describes what inputs/outputs are supported for these two.
The vertex shader is called for every vertex that's being rendered. We can pass additional information from the vertex shader to the fragment shader (like position in 3D space, see MSLS section 5.2).
The fragment shader is closest to a pixel, and might be called multiples time for a single "pixel", if there are multiple triangles that "qualify" for that pixel. (Usually) after fragment shading, a fragment might be discarded if it fails the depth or stencil test.
What I attempted
This is what I attempted. (I hope it makes clear where my understanding is lacking).
struct VertexOut {
float4 position [[position]];
};
vertex VertexOut innerVertexShader(VertexIn in [[stage_in]]) {
VertexOut out;
out.position = in.position;
return out;
};
fragment half4 innerFragmentShader(VertexOut in [[stage_in]],
half4 color [[color(0)]]) {
half4 output;
output = color; // test to see if getting rendered color works
output.g = in.position.y; // test to see if getting y works
return output;
}
These shaders are referenced inside an SCNTechnique dictionary.
[
"passes": [
"innerPass: [
"draw": "DRAW_NODE",
"node": "inner",
"metalVertexShader": "innerVertexShader",
"metalFragmentShader": "innerFragmentShader"
]
],
"sequence": ["innerPass"],
"symbols": [:],
"targets": [:],
]
// ...
let technique = SCNTechnique(dictionary: techniqueDictionary)
This does the following: the technique is instantiated correctly and attached to the scene (because it affects the rendering). But it appears to not apply the camera transform or node position transform to the vertices. And instead renders each node as being viewed from (0,0,1) at position (0,0,0). The colors are wrong. If I remove the shaders from the SCNTechnique, every renders like I would expect.
How can I leverage regular SceneKit behavior (camera transform etc.), and only modify the color output based on the fragments' y world position? I'd expect that needs to happen on a fragment level, using the world position somehow obtained in the vertex shader. I have searched for things like "Metal basic vertex shader" and have come up with naught.
I have seen shaders like this but I'm convinced I should be able to rely on SceneKit rendering for stuff like lighting, PBR materials, camera transforms, etc. At this point I feel like whenever I search for some Metal topic, I end up on the same websites which haven't succeeded yet in taking my understanding to the next level. So, any new/additional resources are appreciated as well.
Background
For the past two months I have been working on my own game project, which uses SceneKit as the main graphics framework. I have turned to SCNTechnique and Metal shaders for custom effects. These last two in particular have given me solid headaches, both on the lack of sample code/documentation/runtime feedback.
I have considered moving to Unity/Unreal or even cancelling this project altogether because of this. But because I'm stubborn and also because I really don't want to port my Swift code to C#/C++, I haven't given up on SceneKit yet.
A: Having spent the past couple of days investigating this topic, my understanding of vertex and fragment shading and how SceneKit tackles these things has developed significantly.
As @mnuages pointed out in a comment, for this use case shader modifiers are the way to go. They leverage default SceneKit shading (as asked by OP) and allow for shader code injection.
Additional information
To compensate for some of the limitations of SceneKit documentation, I’ll elaborate a bit for other people looking into the subject.
For more information on how the shader modifiers tie into SceneKit default vertex/fragment shaders, see my answer to a related question or SceneKit's default shaders. The second link demonstrates the extent of SceneKit’s rendering logic that you get for free when leveraging shader modifiers instead of writing your own shader.
This page helped me build an understanding of the different stages of vector transforms from vertex to fragment (model space ➡️ world space ➡️ camera space ➡️ projection space).
Alternate approach (custom shader)
If you want to have single pass with a fully customized shader, this is a simple example. It passes the world y position from the vertex shader to the fragment shader.
// Shaders.metal file in your Xcode project
#include <metal_stdlib>
using namespace metal;
#include <SceneKit/scn_metal>
typedef struct {
float4x4 modelTransform;
float4x4 modelViewTransform;
} commonprofile_node;
struct VertexIn {
float3 position [[attribute(SCNVertexSemanticPosition)]];
};
struct VertexOut {
float4 fragmentPosition [[position]];
float height;
};
vertex VertexOut myVertex(
VertexIn in [[stage_in]],
constant SCNSceneBuffer& scn_frame [[buffer(0)]],
constant commonprofile_node& scn_node [[buffer(1)]]
) {
VertexOut out;
float4 position = float4(in.position, 1.f);
out.fragmentPosition = scn_frame.viewProjectionTransform * scn_node.modelTransform * position;
// store world position for fragment shading
out.height = (scn_node.modelTransform * position).y;
return out;
}
fragment half4 myFragment(VertexOut in [[stage_in]]) {
return half4(in.height);
}
let dictionary: [String: Any] = [
"passes" : [
"y" : [
"draw" : "DRAW_SCENE",
"inputs" : [:],
"outputs" : [
"color" : "COLOR"
],
"metalVertexShader": "myVertex",
"metalFragmentShader": "myFragment",
]
],
"sequence" : ["y"],
"symbols" : [:]
]
let technique = SCNTechnique(dictionary: dictionary)
scnView.technique = technique
You could combine this render pass with other passes (see SCNTechnique).
| |
doc_23532057
|
I want to convert it to Thu Mar 24 22:00:00 pm. How can I do that using SimpleDateFormat?
A: Look at this page and try this:
SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM d hh:mm:ss aa");
String formattedDate = dateFormat.format(new Date());
System.out.println(formattedDate);
*
*E stands for a day as word
*MMM stands for a shortened month
*d stands for a number of the day
*hh:mm:ss is the classic time format
*a is the am/pm marker
A: You should first parse the text intput:
Date date = new SimpleDateFormat("EEE MMM d hh:mm:ss z yyyy", Locale.ENGLISH)
.parse("Thu Mar 24 13:00:00 GMT+07:00 2016");
then format to local time in new format
String str = new SimpleDateFormat("EEE MMM d hh:mm:ss yyyy", Locale.ENGLISH).format(date);
| |
doc_23532058
|
String wsUrl = "https://218.17.179.67:8443/QhicPos/doService?wsdl";
String method = "doPosRequest";
QName qName = new QName("http://service.pos.qhic.com/", method);
HttpsURLConnection.setDefaultSSLSocketFactory(TrustAnyFactory.getInstance().getSslContext().getSocketFactory());
HostnameVerifier allHostsValid = (hostname, sslSession) -> true;
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
Client client = clientFactory.createClient(wsUrl);
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
conduit.getClient().setReceiveTimeout(0);
httpClientPolicy.setConnectionTimeout(6000000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(6000000);
conduit.setClient(httpClientPolicy);
try {
Object[] rst = client.invoke(qName, new Object[]{xmlRequest});
System.out.println(rst[0].toString());
} catch (Exception e) {
e.printStackTrace();
}
But I when i invoke the code, i got the exception:
org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
Waring: Interceptor for {http://service.pos.qhic.com/}PosServiceImplService# {http://service.pos.qhic.com/}doPosRequest has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Operation timed out
at org.apache.cxf.interceptor.AbstractOutDatabindingInterceptor.writeParts(AbstractOutDatabindingInterceptor.java:108)
at org.apache.cxf.wsdl.interceptors.BareOutInterceptor.handleMessage(BareOutInterceptor.java:68)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:423)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:324)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:277)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:297)
at HttpsWebServiceClient.getClient(HttpsWebServiceClient.java:65)
at HttpsWebServiceClient.main(HttpsWebServiceClient.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: com.ctc.wstx.exc.WstxIOException: Operation timed out
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:255)
at org.apache.cxf.interceptor.AbstractOutDatabindingInterceptor.writeParts(AbstractOutDatabindingInterceptor.java:106)
... 14 more
Caused by: java.net.ConnectException: Operation timed out
...
Which make me confused is that when I use HttpPost to send the soap message(Of course I used some work-around to skip ssl validation), it can successfully return response, but when using JaxwsDynamicClientFatory to generate dynamic client, it fails.
Is is something related with the ssl work-around part of the code?
Can anyone help me? Thanks very much.
A: java.net.ConnectException: Operation timed out means that your request did not get a response within the timeframe. Check https://stackoverflow.com/a/5663054/6371459
I have reproduced the problem executing your code. The WSDL points to 218.17.179.67/QhicPos/doService that is not accesible for me. This problem is previous to any SSL connection (that in fact is not needed because endpoint is published with http)
Maybe there is a firewall protection or is needed a proxy
A: Following code worked for me
BusFactory bf = CXFBusFactory.newInstance();
Bus bus = bf.createBus();
bus.getInInterceptors().add(new LoggingInInterceptor());
bus.getOutInterceptors().add(new LoggingOutInterceptor());
//MyHTTPConduitConfigurer myHttpConduitConfig = new MyHTTPConduitConfigurer();
bus.setExtension(new MyHTTPConduitConfigurer(), HTTPConduitConfigurer.class);
JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(bus);
private static class SoapHTTPConduitConfigurer implements HTTPConduitConfigurer {
public void configure(String name, String address, HTTPConduit c) {
try{
if(logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST,"\n Setting TLS and Connection TimeOut :" );
}
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(itfConfig.getConnectionTimeout());
httpClientPolicy.setReceiveTimeout(itfConfig.getSoTimeout());
c.setClient(httpClientPolicy);
if(tlsParams!=null)
c.setTlsClientParameters(tlsParams);
}catch(Exception ex){
}
}
}
| |
doc_23532059
|
button working fine:
<Button Grid.Row="0" Grid.Column="4" x:Name="btnIdDav" Padding="10" Margin="3" TextColor="#FFF" BackgroundColor="#565C5A" Clicked="btnIdDav_Clicked" WidthRequest="45">
<Button.ImageSource>
<FontImageSource FontFamily="{StaticResource FontAwesomeSolidOTF}" Glyph="" Color="#fff"/>
</Button.ImageSource>
</Button>
Last time I had to set Glyph from code, I had to do a bad 'workaround' with converter in order to show it, and it worked (icon is showing) in the end:
public const string _dollarGlyph = "\uf155";
public const string _percGlyph = "\uf541";
public class DescGlyphConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Glyph="{Binding DescImage, Converter={StaticResource Key=desconto}}
NOW I want to create a custom button and set the Glyph but the icon is not appearing (tested with both OTF and TTF files):
public static FontImageSource GetImgSource()
{
FontImageSource source = new FontImageSource();
source.FontFamily = Application.Current.Resources["FontAwesomeSolidTTF"].ToString();
source.Glyph = "\uf3e5";
source.Color = Color.FromHex("#fff");
return source;
}
public static Style BtnBack() {
return new Style(typeof(Button))
{
Setters = {
new Setter { Property = Button.ContentLayoutProperty, Value = new ButtonContentLayout(ButtonContentLayout.ImagePosition.Top, 5) },
new Setter { Property = Button.TextProperty, Value = "Back" },
new Setter { Property = Button.ImageSourceProperty, Value = GetImgSource()},
}
};
}
Any sugestions?
Thanks!
A: Here is the sample code, please change accordingly. I am using the FontFile name directly:
FontImageSource fontImageSource = new FontImageSource()
{
Glyph = "\uf15c",
Color = Color.Black,
Size = 18,
FontFamily = Device.RuntimePlatform == Device.Android ? "FontAwesome.otf#Regular" : null
};
this.IconImageSource = fontImageSource;
| |
doc_23532060
|
bathroom = response.xpath(“.//div[1][contains(., 'Baños’)]/text()").extract_first()
And I get this error:
ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters
I've tried the solutions given in these other similar questions:
Filtering out certain bytes in python
Scrapy xpath utf-8 literals
but none has resolved my problem!
Note: with the solution of the first link, I obviously replaced the 'input_string' by let's say word = "baños", and I got an error like "the function has one argument, 2 given..."
Can anyone help?
A: Besides the literal Baños, your code snippet contains invalid literal string delimiter (both single and double quotes) which will cause a different error :
bathroom = response.xpath(“.//div[1][contains(., 'Baños’)]/text()").extract_first()
^ ^
Converting the entire XPath expression to unicode, as suggested in the 2nd link, and fixing the two quotes pointed above should fix the initial errors. Below as a quick test using lxml (which scrapy uses under the hood) :
>>> from lxml import etree
>>> root = etree.fromstring('<root/>')
>>> root.xpath(u".//div[1][contains(., 'Baños')]/text()")
[]
| |
doc_23532061
|
Because the button always exist, using following code does not help.
wait.until {
driver.find_element(:id => 'changeStatus')
}
How can i ask webdriver to wait for 5 seconds before checking the button text after clicking.
A: You should be able to do a wait and look for the text instead
wait.until {
driver.find_elements_by_xpath("//*[text()='Deactivate']")
}
A: Brendan's answer is definitely correct, but I would use a more specific XPath, since the answer as stated will wait until the word 'Deactivate' appears ANYWHERE on the page.
Consider narrowing down the type of elements searched, and further narrowing down by ID. You don't say what type of element it is, so I will guess it's an anchor tag (//a), adjust as necessary
wait.until {
driver.find_elements_by_xpath("//a[@id='changeStatus' and text()='Deactivate']")
}
This should speed up the search considerably
| |
doc_23532062
|
I have done to classify the email as spam or nonspam according to the email's subject. For my second task, I have to classify the emails as spam or nonspam according to the time. If the email gets received on ('Friday and 'Saturday') it should be classified as spam. Otherwise nonspam. I literally don't have any idea how to do that. I tried to search but ended up with nothing.
This is a screenshot from the excel file
import pandas as pd
ExcelFile = pd.read_excel(r'C:\Users\Documents\Email Table.xlsx')
Subject = pd.DataFrame(ExcelFile, columns=['Subject'])
def spam(Subject):
A = len(ExcelFile[ExcelFile['Subject'].isnull()])
print("Number of spam emails ",A)
print(ExcelFile[ExcelFile['Subject'].isnull()])
spam(Subject)
A: There are a million ways you could do this, but this is how I would do it. I provided comments and some naming conventions simply for clarity which should allow you to take and modify as necessary to fit your specific needs
#All necessary imports
import pandas as pd
import numpy as np
import datetime
#Create same sample data (just made this up nothing specific)
data = {
'From' : ['test@gmail.com', 'test1@gmail.com', 'test2@gmail.com', 'test3@gmail.com', 'test4@gmail.com'],
'Subject' : ['Free Stuff', 'Buy Stuff', np.nan,'More Free Stuff', 'More Buy Stuff'],
'Dates' : ['2022-05-18 01:00:00', '2022-05-18 03:00:00', '2022-05-19 08:00:00', '2022-05-20 01:00:00', '2022-05-21 10:00:00']
}
#Create a Dataframe with the data
df = pd.DataFrame(data)
#Set all nulls/nones/NaN to a blank string
df.fillna('', inplace = True)
#Set the Dates column to a date column with YYYY-MM-DD HH:MM:SS format
df['Dates'] = pd.to_datetime(df['Dates'], format = '%Y-%m-%d %H:%M:%S')
#Create a column that will identify the what day the Dates column is on
df['Day'] = df['Dates'].dt.day_name()
#Write a np.select() to determine if the Subject column is null or if the Day column is on Friday or Saturday
#This is where you specify which days are spam days
list_of_spam_days = ['Friday', 'Saturday']
#List of conditions to test of true or false (np.nan is equivilent of a null)
condition_list = [df['Subject'] == '', df['Day'].isin(list_of_spam_days)]
#Mirroring the condition_list from before what should happen if the condition is true
true_list = ['Spam', 'Spam']
#Make a new column to which holds all of the results of our condition and true lists
#The final 'Not Spam' is the default if the condition list was not satisfied
df['Spam or Not Spam'] = np.select(condition_list, true_list, 'Not Spam')
df
| |
doc_23532063
|
package pcsettingfirstpj;
public class Sequential {
private static int sequential(int[] data, int target){
int i;
for (i = 0; i < data.length; i++)
if (data[i] == target) return i;
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] data = {89, 34, 78, 45, 12, 99, 23};
int i;
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("Please input value: ");
int target = sc.nextInt();
System.out.print("Original array: ");
for (i = 0; i < data.length; i++);
System.out.print("[" + data[i] + "]");
System.out.print("\n");
int pos = sequential(data, target);
if ( pos != -1){
System.out.print("Found: " + target);
System.out.println("(" + pos + ")");
}
else System.out.println("Not found: " + target);
sc.close();
}
}
How about not using package? Is that a must?
Thanks for your reply. I found it is fine today?!
| |
doc_23532064
|
The HttpContext.Request returns all other parts of the URL except the querystring.
With this url https://localhost:44394/Trackers/Create?Place=Vision_College
and this Model
[BindProperties(SupportsGet = true)]
public partial class Tracker
{
[FromQuery(Name = "Place")] //populates it from the query
public string Place { get; set; }
...}
and this controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name, Phone, Place")] Tracker tracker)
{
A: OK I found an answer.
I was trying to use it in the POST of the CREATE, when I should have been using it in the GET part of CREATE
Thanks for everyones help!
A: Since you are using the query parameters in httpPost you should use, [FromQuery] inside your arguments. Follow this
Your DTO class would be,
public class Tracker
{
[FromQuery(Name = "Place")]
public string Place{ get; set; }
}
In your controller class
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([FromQuery]Tracker tracker)
{
}
Note: If your query parameters match with the model property names, specifically annotating the properties would not be necessary.
Better you can get by body itself since this is a post request. otherwise make this as a get request. If converting to get by body, simply use [FromBody] in endpoint arguments instead of [FromQquery]
| |
doc_23532065
|
from pdf2image import convert_from_path
from PIL import Image, ImageChops
import cv2
import numpy as np
from shapely.geometry import Polygon
import svgwrite
import json
from defcon import Font
import ufo2ft
from fontTools import svgLib
I have a svg file looks like the image below this sentence(The image is upside-down).
SVG file
I load this file and add to Defcon.Font like this:
glyph = font.newGlyph(name=korean_unicode_list[int(key)])
glyph.unicode = int(korean_unicode_list[int(key)], 16)
pen = glyph.getPen()
svg = svgLib.SVGPath("svg_files/" + str(key) + ".svg")
svg.draw(pen)
But after I export this Font object with ufo2ft, The glyph's hole has disappeared :(
ttf = ufo2ft.compileTTF(font)
ttf.save('myFont.ttf')
After Export
I don't know how to make holes at glyphs. I'm guessing that there is a solution at pen object and its methods, but there is no example about glyph with holes. How can I get a glyph with holes?
A: I got a solution myself :)
I tested with Adobe Illustrator. I made '0'-shaped object and saved in svg file. When I export a font file with the svg file, there was a hole.
So I opened the svg file at PyCharm, there's a option name 'xml:space'. If its option set to "preserve", svgPath can draw a path with holes.
I hope this article help you.
| |
doc_23532066
|
I am just having a problem with not being able to validate the input because it is undefined.
**If my HTML is needed I will post, but i think this can be solved without it.
function fnValidation()
{
var validator = /^[a-zA-Z]*$/; //regex
var input = document.getElementById("fn").innerHTML;
if (!(input.match(validator)))
{
alert("Please enter only alphabetical characters!");
}
printReceipt();
}
I dug this old code up from a pervious problem and decided to salvage the username validation but am now having the problem described above
A: Input element doesn't have innerHTML, because all it has its value inside value attribute on html & value property
Inside DOM.
You should use
document.getElementById("fn").value
A: should be var input = document.getElementById("fn").value and not innerHTML
A: .innerHTML will return the string inside that id tag example here:
jsfiddle
<h1 id="fn">Hello World!</h1>
the id is 'fn' the innerHTML is Hello Wold!
| |
doc_23532067
|
But when I import it and try to use it says its methods are undefined.
Here is the code
service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Service {
public publicMethod() {}
}
component.ts
import { Service } from 'path/to/service';
import { Component } from '@angular/core';
import { AccountService } from 'app/core';
@Component({
selector: 'footer',
templateUrl: './footer.component.html',
})
export class FooterComponent {
constructor(private readonly service: Service) {
this.service.publicMethod // undefined
}
}
Other services imported the same way are working fine.
What can cause this issue?
A: Try to add your service you want to inject in providers : [ ] in your core.module
and in your AccountService replace @Injectable({ providedIn: 'root' }) with @Injectable()
A: @ChrisHamilton you are right, an imported module to that service caused the issue, it was not provided anywhere. Added providedIn: root to there was solved the issue.
| |
doc_23532068
|
#in user.py
class User(object):
def __init__(self, first_name: str, last_name: str):
self.first_name = first_name
self.last_name = last_name
def create_full_name(self):
return f'{self.first_name} {self.last_name}'
#in conftest.py
@pytest.fixture(scope='function')
def normal_user():
'''Returns a normal user'''
normal_user = user.User(first_name = 'katherine', last_name = 'rose')
yield normal_user
@pytest.fixture(scope='function')
def missing_details():
'''Returns a user without a last name'''
missing_details = user.User(first_name = ' ', last_name = 'rose')
yield missing_details
#in test_user.py
@pytest.mark.parametrize('user, expected', [('normal_user', 'katherine rose'), ('missing_details', TypeError)], indirect= ['normal_user', 'missing_details'])
def test_parametrize_user_full_name(user, expected):
assert user.create_full_name(user) == expected
The error message I keep getting is:
In test_parametrize_user_full_name: indirect fixture 'normal_user' doesn't exist
Is it necessary to specify which fixtures should be indirect in conftest.py or am I writing the code for the parametrised test incorrectly?
A: This is not how indirect parametrization works. You have to reference one fixture with the indirect parameter, and the fixture will return the actual value based on the value in the parameter value list. You can find an example in the documentation.
In your case you would need something like:
@pytest.fixture
def user(request):
if request.param == 'normal_user':
# Returns a normal user
yield User(first_name='katherine', last_name='rose')
if request.param == 'missing_details':
# Returns a user without a last name
yield User(first_name=' ', last_name='rose')
@pytest.mark.parametrize('user, expected', [('normal_user', 'katherine rose'),
('missing_details', TypeError)],
indirect=['user'])
def test_parametrize_user_full_name(user, expected):
...
As an aside: comparing the result against an exception will not work the way you do it, but I guess this is only a dumbed down example that is not expected to work.
| |
doc_23532069
|
This command doesn't provide my custom index, only system ones.
$ curl -XGET localhost:9200/_cat/indices?pretty | grep 2019.10.17
What should I do to create index and restore/push logs to it?
Is it the issue of logstash or Elasticsearch?
Looks like logstash.
| |
doc_23532070
|
In my folder I have files like lesson1.mp4, lesson2.mp4, lesson3.mp4 ... and so on. And in the text file, I have the new names 1-newname, 2-newname, 3-newname (separated by a newline).
First, I change the directory and store the variable in file and then I use file.readlines() to separate line by line.
import os
os.chdir(r"C:\Users\Samaritan\Documents\Python\
Ejercicios\pruebarenamefiles")
file = open('new_names.txt')
lines = file.readlines()
Then, I created a function to return the new names based on the position of the list.
def n_name(num):
return lines[num]
Then I iterate over the directory and rename each position with the function n_name
i = 0
for file in os.listdir():
if file != "new_names.txt":
os.rename(file, n_name(i))
i += 1
But it doesn't work at all. I got "OSError: [WinError 123]"
C:\Users\Samaritan\Documents\Python\Ejercicios\rename_files\venv\Scripts\python.exe C:/Users/Samaritan/Documents/Python/Ejercicios/rename_files/main.py
Traceback (most recent call last):
File "C:\Users\Samaritan\Documents\Python\Ejercicios\rename_files\main.py", line 16, in <module>
os.rename(file, n_name(i)) OSError: [WinError 123] El nombre de archivo, el nombre de directorio o la sintaxis de la etiqueta del volumen no son correctos: 'Nuevo documento de texto - copia (2).txt'
-> '01 - Course Introduction\n'
Process finished with exit code 1
In English it means something like this: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:
A: The error message indicates the problem if you read it carefully. The destination file name contains a newline character at the end, which isn't allowed on Windows.
To read the lines without newlines, try
with open("new_names.txt") as file:
lines = [line.rstrip("\n") for line in file]
However, it's also weird to use a separate function to obtain the n:th object out of a list; indexing is a fundamental built-in method of lists.
files = os.listdir()
files.remove("new_names.txt")
for idx, filename in enumerate(files):
os.rename(filename, lines[idx])
Identically, you could zip the two lists, as suggested in the other answer, but then you still separately have to remove new_names.txt from the input list first, like the code above does.
If the new names are as monotonous as your question suggests, maybe just generate them on the fly instead of putting them in a file.
idx = 1
for filename in os.listdir():
if file == "new_names.txt":
continue
os.rename(filename, f"{idx}-newname.txt")
idx += 1
If you want to apply formatting to the number, try e.g. f"{idx:02}-newname.txt" to force the index number to two digits with zero padding.
| |
doc_23532071
|
int Integer;
public void Test() {
Console.WriteLine(Integer);
}
If I change int Integer to int Integer { get; set; }, the code that uses it stays unchanged. Is there any case when I need to change calling code?
The same question about readonly fields and get-only properties.
EDIT: I clarified my question. Also, taking into account existing answers, instead of auto property, question will be about ref property:
Is it possible to replace this
int Integer;
with
int _integer;
ref int Integer => ref _integer
Without any changes of calling code?
A:
I want to find a case when I need to change client source code if I
replace a field with a property or opposite. I want to know how safe
this replacement is
Fields (C# Programming Guide)
Generally, you should use fields only for variables that have private
or protected accessibility. Data that your class exposes to client
code should be provided through methods, properties and indexers. By
using these constructs for indirect access to internal fields, you can
guard against invalid input values. A private field that stores the
data exposed by a public property is called a backing store or backing
field.
So there you have the official word on field and property usage
I mean, if we replace a field with auto property or opposite, do we
need to change client code in some cases
Yes, you are likely to break things in the following cases,
*
*If you are exposing fields that are being passed by ref
*If this class is being inherited and in cases where fields or properties are getting re-implemented or overridden
*A derived classes implement Interfaces that require properties etc.
*Also there could be cases where they are used in Expressions and it expects field or a property (I think).
In short, if large code bases relied on fields/properties and you change them this is likely to cause breakable changes for any of the above.
Though in summary, if you lived by the Microsoft recommendations above, you should have less of a problem, and if you do it points to the fact this should probably be refactored as a new version anyway (with breakable changes, and more expected usage).
| |
doc_23532072
|
The request makes it to bar, executes but because the apache server does not add any CORS headers, the browser says the request failed.
The CORS documentation on MDN explains that the browser Javascript doesn't know the specifics of the failure, it just knows that the response failed.
My question is, does the response object contain the response returned by my cgi script and the browser just chose to show this as an error because it couldn't find the Access-Control-Allow-Origin header ?
From my inspection of the response object, it seems that the apache server did not send the response from the cgi script's output at all.
It is unclear, who is responsible for containing the response here:
*
*Is it the apache server
*Is it the fetch/XMLHTTP api
Note: I used jquery to make the AJAX calls
A:
How do CORS response headers prevent browser javascript to access response object?
They don't. Your JS being unable to access the response data is the default behaviour. CORS headers can grant permission that would be denied by default.
The Same Origin Policy is implemented by the browser. The server doesn't know about it (except in so much as it might be explicitly configured to send CORS headers in the response).
The browser receives the HTTP response, determines that permission was not granted, and generates a response object saying as much which it provides to the JavaScript program.
| |
doc_23532073
|
This app has been containerized to windows container and deployed on Azure app service webapp as containers.
It has option to mount Azure files storage as persistent storage volume to the container.
So I have mapped the mount to point the upload directory. The idea is when user upload the file, it will go to Azure Filestorage via the mount volume.
The mount is successful, how ever when trying to upload getting error "The Parameter is Incorrect" from system.IO.
If we inspect the Azure Filestorage from the storage explorer, there is been an empty file being created. Not sure what is going wrong.
2020-10-17 02:36:20,959 82924433ms INFO FileHelper UpLoadFile - ToFilePath : C:\inetpub\wwwroot\FileStorage\UserProfileImages\banner-img.jpg
2020-10-17 02:36:20,975 82924449ms ERROR FileHelper UpLoadFile - Error in saving file. The parameter is incorrect.
2020-10-17 02:36:20,975 82924449ms ERROR FileHelper UpLoadFile - System.IO.IOException: The parameter is incorrect.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at System.Web.HttpPostedFile.SaveAs(String filename)
at ConnecTiQa.Mvc.Helpers.FileHelper.UpLoadFile(HttpPostedFileBase file, HttpServerUtilityBase server, String rename, String SaveFilePath) in C:\app\ConnecTiQa.Mvc\Helpers\FileHelper.cs:line 204
Storage account screenshot
Update 1:
Not only update. Having issue with accessing the file(reading) from the mounted volume as well.
Mount volume file access error
A: This was too long to post as a comment. Direct from Microsoft Support:
Hypervisor-isolated containers run inside a lightweight component called a UVM (Utility VM). When a directory from the host is mapped into a hypervisor-isolated Windows container, Hyper-V uses VSMB (virtual SMB) to map the share into the UVM. VSMB supports an optimization called direct map, which reduces memory overhead on the host for the share. As part of supporting direct map, VSMB must be able to query for the file ID of the file being accessed. So in this case VSMB would be querying Azure Files to get the file ID. However, Azure Files currently does not support querying for file ID from its shares, and this is what produces the ERROR_INVALID_PARAMETER error that is observed when accessing the share.
There are effectively two issues here:
Azure Files does not support querying for file ID.
I have started a thread with a contact on Azure Files to see if this is something they could support in the future.
When querying for file ID fails, VSMB does not fall back to using a non-direct mapped access to the share
This bug exists in 19H1, 20H1, and 20H2. In RS5 VSMB did not query for file ID, but this was changed in 19H1 to make VSMB more correct, and eliminate other bugs. Post-20H2, this bug has been fixed so that VSMB will fall back to non-direct map if the file ID query fails, but there hasn't been a new version of Windows Server since the bug was fixed. The fix will be available in the next Windows Server release.
But still we have the issue with azure file that does not support querying for file ID and there is no ETA at this point. The Windows team is looking at it in this case a workaround recommended by our product group is to use another mechanism like the Azure SDK for .NET for reading/writing files to storage
A:
The problem is that the mount in the Windows container only has the permission RX, see the screenshot here:
You do not have the write permission in the mount point, so you cannot write the content into the files.
Update:
I made a mistake and I'm sorry about that. The mount point is the path that you set in the path mappings. For example, if you set the mount path as /inetpub/wwwroot/filestorage/mnt, then the mount point is the final folder mnt, and all the actions in it would be incorrect:
I'm not sure if this the issue, but I guess it's the problem.
| |
doc_23532074
|
public class Locations_ByUser : AbstractIndexCreationTask<LocationModel>
{
public Locations_ByUser()
{
Map = locations => from location in locations
select new { location.UserId };
}
}
I am registering the index with the following code
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//ADD THE MODEL BINDER FOR LIST TO STRING
ModelBinders.Binders.Add(typeof(TestAPI.Models.LocationModel), new TestAPI.Classes.LocationModelBinder());
//INIT THE STORE, DO ONCE PER APP START
TestAPI.Classes.DataDocumentStore.Initialize();
//SET THE INDEXES
IndexCreation.CreateIndexes(typeof(Locations_ByUser).Assembly, TestAPI.Classes.DataDocumentStore.Instance);
}
However, when i try to call the index from the mvc app
[HttpGet]
public ActionResult Index()
{
var result = this.DocumentSession.Query<LocationModel>("Locations_ByUser").ToList();
foreach (var userid in result)
{
Console.Out.WriteLine(userid);
}
return View();
}
it returns the following error
Could not find index named: Locations_ByUser
I was wondering if anyone else has encountered this before and could point me in the right direction. Thanks in advance.
A: The index in RavenDB will actually be named: "Locations/ByUser" when it's generated.
If you open up the Raven Studio you can see this under the index's. The _ is replaced with /
Also you don't need to specify the string value, you can write your query like:
var result = this.DocumentSession.Query<LocationModel, Locations_ByUser>().ToList();
| |
doc_23532075
|
My problem occurs when I enter 7 or more values; the values that go beyond the buffer size are still used as the program runs in a loop, constatly filling up buf with what is left in stdin (at least, that is how I think it is working).
#define SIZE 8
char *readLine(char *buf, size_t size) {
printf("$ ");
fgets(buf, size, stdin);
return buf;
}
int main() {
char *buf = malloc(SIZE * sizeof(char));
for (;;) {
readLine(buf, SIZE);
printf("> %s", buf);
}
}
The output I have, testing an input size of 6, 7, and 8 respectively:
$ abcdef
> abcdef
$ abcdefg
> abcdefg$ >
$ abcdefgh
> abcdefg$ > h
The things I don't understand:
*
*Why does the 7th value make the program's output appear strange? I thought the 7th character plus the null character would work correctly?
*Why does buf fill up with values beyond the size of SIZE (8 in this case)?
From this, is there a simple change/addition I could make to achieve what I want to make?
A:
Why does the 7th value make the program's output appear strange? I thought the 7th character plus the null character would work correctly?
fgets doesn't read the excessive input (beyond the buffer size you provided excluding one byte space for null byte). So the character h is left in the input stream and is then consumed by your next call to fgets - that read h and the newline char \n. Upon reading newline char, fgets terminates reading further input.
Why does buf fill up with values beyond the size of SIZE (8 in this case)?
It doesn't. As noted, the leftover input is read and thus it gives such an appearance.
From this, is there a simple change/addition I could make to achieve what I want to make?
You can check if the buffer read by fgets has newline char; if not, read & ignore the leftover bytes from the input stream.
You can do:
void discard(const char *buf)
{
if(strchr(buf, '\n') == NULL) {
/* No newline found, so read & discard everything.
while(getchar() != '\n');
}
}
char *readLine(char *buf, size_t size) {
printf("$ ");
if (fgets(buf, size, stdin) != NULL) {
discard(buf);
}
return buf;
}
| |
doc_23532076
|
I would like to color cells depending on the value of numtype. For example, if numtype = 'abc', the nummin cell will be lightblue and nummax will be lightred. So i would expand this for other possible values of numtype and set colors for nummin/nummax accordingly.
I found documentation for exceljs at https://github.com/exceljs/exceljs#conditional-formatting
but I have not been able to make conditional formatting of cells work for me.
worksheet.addConditionalFormatting({
ref: 'A3:AR106',
rules: [
{
type: 'containsText',
operator: 'containsText',
text: 'abc',
style: {fill: {type: 'pattern', pattern: 'solid', bgColor: {argb: '#98b8eb'}}},
}
]
})
Does anyone have an example I could follow that would lend itself to what I have described?
Thanks
Dan
A: Use priority option
worksheet.addConditionalFormatting({
ref: 'A3:AR106',
rules: [
{
priority:1, // add this
type: 'containsText',
operator: 'containsText',
text: 'abc',
style: {fill: {type: 'pattern', pattern: 'solid', bgColor: {argb: '#98b8eb'}}},
}
]
})
| |
doc_23532077
|
<asp:ListView runat="server" ID="FullInfoListView">
<LayoutTemplate>
<table class="tablestripe" width="100%">
<asp:Placeholder runat="server" ID="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr valign="top" class="eventrow1">
<td colspan="2">
<h3><%# Eval("FirstName") Eval("LastName") %></h3>
</td>
</tr>
<tr valign="top" runat="server" Visible="<%# (bool)Eval("PhotoVis") %>">
<td colspan="2">
<img src="~/Userphoto/thumb/<%# Eval("NetworkLogin") %>.jpg" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
A: You have to have single quotes around the Visible setter:
<tr valign="top" runat="server" Visible='<%# (bool)Eval("PhotoVis") %>'>
<td colspan="2">
<img src='~/Userphoto/thumb/<%# Eval("NetworkLogin") %>.jpg' />
</td>
</tr>
A: You could wrap the row in a PlaceHolder:
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible='<%# (bool)Eval("PhotoVis") %>'>
<tr valign="top">
<td colspan="2">
<img src='~/Userphoto/thumb/<%# Eval("NetworkLogin") %>.jpg' />
</td>
</tr>
</asp:PlaceHolder>
EDIT: Included single quotes around image src attribute
A: Try setting style="display:none" instead of using Visible.
| |
doc_23532078
|
Here is a gif which shows what I am talking about:
https://imgur.com/a/hnYLTyA
A: *
*Use Stack to position the drawer on top of calculator screen.
*Use Positioned for the drawer and set its left parameter according to the amount that it's pulled.
*Set the left parameter of the drawer to the end of the screen initially.
*Use GestureDetector and onPanUpdate to change the position when it's pulled.
*Change the drawer icon according to the position of the drawer.
*For the dim effect on the calculator screen, use a ModalBarrier. Wrap it with an Opacity widget and set its opacity parameter according to the amount the drawer is pulled.
static double _offset = 30;
double _drawerLeft = 400;
IconData _drawerIcon = Icons.arrow_back_ios;
bool _init = true;
@override
Widget build(BuildContext context) {
if (_init) {
_drawerLeft = MediaQuery.of(context).size.width - _offset;
_init = false;
}
return Scaffold(
body: Align(
alignment: Alignment.bottomCenter,
child: FractionallySizedBox(
widthFactor: 1,
heightFactor: 0.5,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Positioned.fill(
child: Container(
color: Colors.grey[200],
child: Center(
child: Text(
'text',
style: TextStyle(fontSize: 32),
)),
),
),
Positioned.fill(
right: 0,
child: Opacity(
opacity: 1 -
_drawerLeft /
(MediaQuery.of(context).size.width - _offset),
child:
ModalBarrier(dismissible: false, color: Colors.black87),
),
),
Positioned(
width: MediaQuery.of(context).size.width * 3 / 4,
top: 0,
height: MediaQuery.of(context).size.height / 2,
left: _drawerLeft,
child: GestureDetector(
onPanUpdate: (details) {
_drawerLeft += details.delta.dx;
if (_drawerLeft <= MediaQuery.of(context).size.width / 4)
_drawerLeft = MediaQuery.of(context).size.width / 4;
if (_drawerLeft >=
MediaQuery.of(context).size.width - _offset)
_drawerLeft =
MediaQuery.of(context).size.width - _offset;
if (_drawerLeft <= MediaQuery.of(context).size.width / 3)
_drawerIcon = Icons.arrow_forward_ios;
if (_drawerLeft >=
MediaQuery.of(context).size.width - 2 * _offset)
_drawerIcon = Icons.arrow_back_ios;
setState(() {});
},
child: Container(
decoration: BoxDecoration(color: Colors.blue),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(right: _offset),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Icon(
_drawerIcon,
color: Colors.white,
),
],
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'text',
style: TextStyle(
color: Colors.white, fontSize: 32),
)
],
)
],
),
)),
),
],
),
),
),
);
}
Result:
A:
Flutter use native keyboards by default, and what you want to do is make your own custom keyboard.
What you need to do:
*
*prevent showing keyboard. (https://github.com/flutter/flutter/issues/16863)
*create your own custom keybord widget
*Add animation on taping for close and open.
*Add dragging functionality with 'auto ending' (don't know how to say it in English correctly, I mean what would happen if you drop dragging in the middle).
*Add tapping.
I've made a simple example.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: SafeArea(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
TextEditingController _controller;
NoKeyboardEditableTextFocusNode focusNode;
bool isKeyboardOpen = false;
void initState() {
super.initState();
focusNode = NoKeyboardEditableTextFocusNode();
focusNode.addListener(() {
setState(() {
isKeyboardOpen = focusNode.hasFocus;
});
});
_controller = TextEditingController(text: 'tap here');
}
void dispose() {
_controller.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (context, constraintes) {
var maxHeight = constraintes.maxHeight;
return Column(
children: [
AnimatedContainer(
height: isKeyboardOpen ? maxHeight - 300 : maxHeight,
duration: Duration(milliseconds: 300),
child: Center(
child: GestureDetector(
onTap: () {
setState(() {
isKeyboardOpen = true;
});
},
child: NoKeyboardEditableText(
noKeyboardEditableTextFocusNode: focusNode,
controller: _controller,
cursorColor: Colors.green,
selectionColor: Colors.red,
style: TextStyle(
fontStyle: FontStyle.normal,
fontSize: 30.0,
color: Colors.black),
),
),
),
),
AnimatedContainer(
height: isKeyboardOpen ? 300 : 0,
duration: Duration(milliseconds: 300),
color: Colors.red,
child: _CustomKeybord(
onAdd: (v) => _controller.value =
TextEditingValue(text: _controller.value.text + v)),
),
],
);
},
),
);
}
}
class _CustomKeybord extends StatefulWidget {
_CustomKeybord({Key key, this.onAdd}) : super(key: key);
final Function(String value) onAdd;
@override
__CustomKeybordState createState() => __CustomKeybordState();
}
class __CustomKeybordState extends State<_CustomKeybord> {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return Stack(
children: [
Positioned(
left: 0,
top: 0,
bottom: 0,
child: Container(
width: constraints.maxWidth * 0.9,
height: constraints.maxHeight,
child: _FirstLayerKeybord(
onAdd: widget.onAdd,
),
),
),
Positioned(
right: 0,
top: 0,
bottom: 0,
child: _SecondLayerKeybord(
onAdd: widget.onAdd,
),
),
],
);
},
);
}
}
class _SecondLayerKeybord extends StatefulWidget {
const _SecondLayerKeybord({
Key key,
@required this.onAdd,
}) : super(key: key);
final Function(String value) onAdd;
@override
__SecondLayerKeybordState createState() => __SecondLayerKeybordState();
}
class __SecondLayerKeybordState extends State<_SecondLayerKeybord>
with TickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
)..addListener(_listener);
}
void _listener() {
if (!_controller.isAnimating) {
setState(() {
isOpen = _controller.isCompleted && _controller.value == 1;
});
}
}
void onTap() {
_controller.isCompleted ? _controller.reverse() : _controller.forward();
}
bool isOpen = false;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
double _currentX;
_onDrag(details) {
var maxWidth = MediaQuery.of(context).size.width;
var x = details.globalPosition.dx;
_currentX = x;
var v = math.max(0.0, 1 - (_currentX / maxWidth - 0.5) * 2);
_controller.value = v;
}
_onDragEnd(_) {
if (_controller.value > .5) {
_controller.animateTo(1);
} else {
_controller.animateTo(0);
}
}
@override
Widget build(BuildContext context) {
var maxWidth = MediaQuery.of(context).size.width;
return AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Container(
width: maxWidth,
child: Stack(
children: [
Positioned(
left: 0,
right: 0,
top: 0,
bottom: 0,
child: IgnorePointer(
child: Opacity(
opacity: 0.3 * _controller.value,
child: Container(
color: Colors.black,
),
),
),
),
Positioned(
left: maxWidth * 0.9 - (_controller.value * maxWidth * 0.45),
bottom: 0,
top: 0,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.blueAccent,
),
),
width: maxWidth * 0.6,
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
GestureDetector(
onTap: onTap,
onPanDown: (details) {
_currentX = details.globalPosition.dx;
},
onPanStart: _onDrag,
onPanUpdate: _onDrag,
onPanEnd: _onDragEnd,
child: Container(
alignment: Alignment.center,
color: Colors.blue,
width: maxWidth * 0.1,
child: Icon(
isOpen
? Icons.keyboard_arrow_right
: Icons.keyboard_arrow_left,
color: Colors.white,
),
),
),
buildColumn(['INV', 'sin', 'ln', 'π', '(']),
buildColumn(['Deg', 'cos', 'log', 'e', ')']),
],
),
),
),
],
),
);
},
);
}
Column buildColumn(List<String> listBtns) {
return Column(
children: listBtns
.map((btnText) => Expanded(
child: RaisedButton(
color: Colors.blue,
onPressed: () => widget.onAdd(btnText),
child: Text(
btnText,
style: TextStyle(color: Colors.white),
),
),
))
.toList(),
);
}
}
class _FirstLayerKeybord extends StatelessWidget {
const _FirstLayerKeybord({
Key key,
@required this.onAdd,
}) : super(key: key);
final Function(String value) onAdd;
final primaryButtons = const [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['0', '.', '='],
];
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: primaryButtons
.map((row) => Expanded(
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: row
.map((e) => Expanded(
child: RaisedButton(
onPressed: () => onAdd(e),
child: Text(e),
),
))
.toList(),
),
))
.toList());
}
}
class NoKeyboardEditableText extends EditableText {
NoKeyboardEditableText({
@required TextEditingController controller,
@required TextStyle style,
@required Color cursorColor,
bool autofocus = false,
Color selectionColor,
@required NoKeyboardEditableTextFocusNode noKeyboardEditableTextFocusNode,
}) : super(
controller: controller,
focusNode: noKeyboardEditableTextFocusNode,
style: style,
cursorColor: cursorColor,
autofocus: autofocus,
selectionColor: selectionColor,
backgroundCursorColor: Colors.black,
);
@override
EditableTextState createState() {
return NoKeyboardEditableTextState();
}
}
class NoKeyboardEditableTextState extends EditableTextState {
@override
void requestKeyboard() {
FocusScope.of(context).requestFocus(widget.focusNode);
}
}
class NoKeyboardEditableTextFocusNode extends FocusNode {
@override
bool consumeKeyboardToken() {
return false;
}
}
A: You can use a side sheet from Material design.
Here you have a package to implement this. You can see the code of this package here
| |
doc_23532079
|
MSI (s) (F8:C4) [12:39:26:183]: Executing op: CustomActionSchedule(Action=WriteIIS7ConfigChanges,ActionType=11265,Source=BinaryData,Target=**********,CustomActionData=**********)
MSI (s) (F8:F8) [12:39:26:188]: Invoking remote custom action. DLL: C:\WINDOWS\Installer\MSI7B14.tmp, Entrypoint: WriteIIS7ConfigChanges
WriteIIS7ConfigChanges: Error 0x80070002: Site not found for create application
WriteIIS7ConfigChanges: Error 0x80070002: Failed to configure IIS application.
WriteIIS7ConfigChanges: Error 0x80070002: WriteIIS7ConfigChanges Failed.
CustomAction WriteIIS7ConfigChanges returned actual error code 1603 (note this may not be 100% accurate if translation happened inside sandbox)
Action ended 12:39:26: InstallFinalize. Return value 3.
Am i missing out something. Any help is appreciated, Thanks in Advance :)
A: If it's a repair and the site name is missing, chances are that it was entered in a UI dialog in the original install. In a repair there is no UI to re-enter the site name and properties aren't automatically saved. It may be trying to configure a site with no name. The best way to deal with this type of thing in general is to use the WiX remember property pattern on the site name so that it is preserved and is available for a repair. I can't tell if that would be a good thing in this particular case because I don't know if writing the config changes again on top of the existing config changes will work or be handled correctly by the code. A verbose log of the original install should tell you what property names are being used for site names etc.
If you think it's unlikely that the IIS config changes will break and that they won't need repair, you could consider adding "Not Installed" to the condition on the CA so that a repair won't call it.
| |
doc_23532080
|
[product_categories ids="135, 214, 244, 1958, 72, 205, 43, 559, 73, 1033, 69, 2009, 1365, 1250, 462, 346, 1649, 1344, 1379, 1373" orderby="id"]
to display Woocommerce product categories on a Wordpress site. It works, but I need the categories to be displayed in the order that they're listed in the ids quotations. I know of orderby="name", "date", and "id", and none of those will work for this particular task unless you know of any nifty hacks that involve them.
Any Ideas? Thanks
A: I haven't solved the issue but I'm going to post this work around as an answer in case anyone else is struggling with this.
Just re-ordered the sub-categories in the order you want them displayed manually. Do this with the drag-and-drop method in WooCommerce > products > categories. Then in your short-code, write:
[product_categories parent="*your parent category id*" ids="*the sub-category ids you want displayed*" hide_empty="0"]
This will display your specified sub categories in the order that you put them in with the drag and drop.
Note:
If you want to hide categories without any products in them remove the 'hide_empty' portion of the short-code. Also when displaying multiple sub categories, remember that the ids are separated by commas. ie: ids="1, 2, 3"
If anyone knows the short-code solution please post/comment, because the drag and drop method is very time consuming when you have hundreds of categories.
A: The shortcode now has an attribute orderby = "include" to order by the ids.
| |
doc_23532081
|
"{"error": "(1305, u'PROCEDURE tbl_user.sp_createUser does not exist')"}.
I see it in terminal, but can't seem to get my app to find it. I have a hunch the stored procedure is in the wrong database, but I can't find any clear instructions on how to confirm which DB my procedure is in.
I've tried looking at all the databases I have. I even tried resetting my connection and making sure I could find the procedure in terminal before trying to test my app. I find it, but am unable to get my app to work.
Python App code excert:
'''python
mysql = MySQL()
#MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'peace2you'
app.config['MYSQL_DATABASE_DB'] = 'BucketList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
@app.route("/")
def main():
return render_template('index.html')
@app.route("/showSignup")
def showSignup():
return render_template('signup.html')
@app.route("/signUp",methods=['POST','GET'])
def signUp():
try:
# read the posted values from the UI
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
if _name and _email and _password:
#all good, lets call MySQL
with closing(mysql.connect()) as conn:
with closing(conn.cursor()) as cursor:
_hashed_password = generate_password_hash(_password)
cursor.callproc('tbl_user.sp_createUser',(_name,_email,_hashed_password))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({'message':'User created successfully !'})
else:
return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
except Exception as e:
return json.dumps({'error':str(e)})
'''
'''mysql from commandline
show create procedure `tbl_user.sp_createUser`
-> ;
+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| Procedure | sql_mode | Create Procedure | character_set_client | collation_connection | Database Collation |
+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| tbl_user.sp_createUser | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | CREATE DEFINER=`root`@`localhost` PROCEDURE `tbl_user.sp_createUser`(
IN p_name VARCHAR(20),
IN p_username VARCHAR(20),
IN p_password VARCHAR(20)
)
BEGIN
if ( select exists (select 1 from tbl_user where user_username = p_username) ) THEN
select 'Username Exists !!';
ELSE
insert into tbl_user
(
user_name,
user_username,
user_password
)
values
(
p_name,
p_username,
p_password
);
END IF;
END | utf8mb4 | utf8mb4_0900_ai_ci | utf8mb4_0900_ai_ci |
+------------------------+-----------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
'''
I'm expecting the console to show 'User Created Successfully' but I keep getting :
{"error": "(1305, u'PROCEDURE tbl_user.sp_createUser does not exist')"}.
Any help or understanding you could provide would be fantastic! Thanks
A: In a comment, you mentioned that you want to create a procedure called sp_createUser in the table tbl_user. That's not how it works.
You may be thinking of triggers, which is code that belongs to a specific table, but those cannot be called like a procedure, and instead gets executed automatically when you update your table data, e.g. insert a row into your table.
A procedure just sits in a database and can be called without reference to a table. You just need to specify the database if it differs from your current database, in the form databasename.procedurename. This is what you did in your python call: you tried to execute a procedure called sp_createUser in a database tbl_user, which appearently does not exist.
In MyQSL Workbench, you used backticks to create and verify the procedure, show create procedure `tbl_user.sp_createUser`. This way, you told MySQL to take the string literally, e.g. create a procedure with a dot in the name. And you basically never want to do this.
To sum up: create the procedure using create procedure sp_createUser ... and call it using cursor.callproc('sp_createUser', ....
You can include the database name, e.g. create procedure BucketList.sp_createUser ... and/or cursor.callproc('BucketList.sp_createUser', ..., although if you do this, it might get more complicated if you want to run your application on a different database, e.g. a test installation with a different name.
| |
doc_23532082
|
I'd like to display this information into a lightbox of some sort. I've researched the lightbox2 and colorbox modules but it seems that those are mainly used for media.
Has anyone done this and/or are there any suggestions as to how I can accomplish this?
A: The calendar module has a popup option built in. If you'd like another alternative you can look at the Fullcalendar module which has color box integration and is a better calendar in my opinion anyway.
| |
doc_23532083
|
Printing description of error.some.instance_type:
expression produced error: error: /var/folders/k8/ppsgsylx27b5061mkcw9c7n40000gn/T/./lldb/4446/expr7.swift:1:65: error: use of undeclared type 'Builtin'
Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer(bitPattern: 0x101b94360)!.pointee)
What is 'Builtin' here? The error occurs in the following block.
recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in ...}
Shall the real problem be?
[Client] {"msg":"Fence: onClientEventRegionState, invalid state", "regionState":"0"}
Here is the article that I followed. Any hint?
| |
doc_23532084
|
DECLARE @Customers TABLE (Customer_Name VARCHAR(20), Residence_State VARCHAR(20), Move_In_Date DATE)
INSERT INTO @Customers VALUES
('Rachel', 'Wisconsin', '2010-01-01'),
('Rachel', 'Nevada', '2012-06-03'),
('Rachel', 'Arizona', '2018-02-01'),
('Chad', 'Texas', '2010-01-01'),
('Chad', 'Idaho', '2012-04-15'),
('Chad', 'Texas', '2019-11-17'),
('Jake', 'Illinois', '2010-01-01'),
('Jake', 'Florida', '2011-02-04'),
('Jake', 'Wisconsin', '2013-08-13'),
('Jake', 'California', '2016-01-15')
Given this table, I would like to get a row for each customer that showed their name, their oldest known State of residence, and their current State of residence. So for the data above, that would be:
Rachel - Wisconsin - Arizona
Chad - Texas - Texas
Jake - Illinois - California
What is the most efficient way to write this query?
A: Your code looks like SQL Server. Unfortunately, there is not a first() aggregation function. But you can use first_value():
select distinct customer_name,
first_value(residence_state) over (partition by customer_name order by move_in_date) as first_residence_state,
first_value(residence_state) over (partition by customer_name order by move_in_date desc) as last_residence_state
from @customers c;
Here is a db<>fiddle.
A: You could also do this row_number() and conditional aggregation:
select
customer_name,
max(case when rn_asc = 1 then residence_state end) first_residence_state,
max(case when rn_desc = 1 then residence_state end) last_residence_state
from (
select
c.*,
row_number() over(partition by customer_name order by move_in_date asc) rn_asc,
row_number() over(partition by customer_name order by move_in_date desc) rn_desc
from @customers c
) c
where 1 in (rn_asc, rn_desc)
group by customer_name
The inner query ranks the records of each customer_name by ascending and descending move_in_date. Then, the outer query aggregates by customer_name and uses conditional expressions to pull out the residence_state that correspond to the first and last move_in_date of each customers.
Demo on DB Fiddle:
customer_name | first_residence_state | last_residence_state
:------------ | :-------------------- | :-------------------
Chad | Texas | Texas
Jake | Illinois | California
Rachel | Wisconsin | Arizona
| |
doc_23532085
|
When I connect my device (Moto G4 plus) running Android 7 - it receives the FCM message which is sent via the FCM API by a separate server app. I can process the data in the FCM message on the code running on the device.
However the emulators in Android Studio (API 24, 25) DO NOT receive the message at all. The emulators do show being synced with Firebase in logcat.
What am i doing wrong?
Thanks
App build. gradle
apply plugin: 'com.android.application'
check.dependsOn 'assembleDebugAndroidTest'
android {
compileSdkVersion 26
buildToolsVersion '26.0.1'
defaultConfig {
applicationId "****"
minSdkVersion 24
targetSdkVersion 26
versionCode 1
versionName "1.0"
//multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
dexOptions {
javaMaxHeapSize "2g"
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'LICENSE.txt'
}
lintOptions {
abortOnError false
}
}
configurations.all {
resolutionStrategy.force 'com.android.support:support-annotations:26.1.0'
}
repositories {
maven { url 'https://maven.google.com' }
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
//For FCM
compile 'com.google.firebase:firebase-messaging:11.2.2'
compile 'com.firebase:firebase-jobdispatcher:0.8.1'
//For Networking
compile 'com.android.volley:volley:1.0.0'
//For InstanceID
compile 'com.google.android.gms:play-services:11.2.2'
// Testing dependencies
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support:support-annotations:26.0.0'
}
apply plugin: 'com.google.gms.google-services'
A: I un-installed and re-installed Android Studio. And the emulators can now receive the FCM Message.
I can't find a reason why this solves it but it does.
| |
doc_23532086
|
I want to create a dropdown in a splunk dashboard based on the first field (A).
So my problem here, is first, how to extract the first string before semicolon.
And Second, how to use that field dynamically in the dropdown
| |
doc_23532087
|
I'm deploying on Azure and therefore would like to look up the credentials from Azure app settings in code on app startup.
Is there a way to configure Elmah emails declaratively in code rather than using the <errorMail> tag?
A: The best way to do this is by overriding the SendMail method of Elmah's ErrorMailModule, as suggested by Atif Aziz in this discussion on Google Groups.
I've given more details in this answer.
A: You could trap the Elmah Mailing event and substitute your email addresses.
http://scottonwriting.net/sowblog/archive/2011/01/06/customizing-elmah-s-error-emails.aspx
| |
doc_23532088
|
Thanks
Code1 : with Main method
import javax.swing.*;
import javax.swing.text.MaskFormatter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.text.ParseException;
public class HangmanGUI {
DetailsPanel myPanel;
public HangmanGUI() throws ParseException {
myPanel = new DetailsPanel();
JFrame myframe = new JFrame();
myframe.getContentPane().setLayout(new BorderLayout());
myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
myframe.setTitle("Hangman Game");
myframe.setVisible(true);
myframe.setLocationRelativeTo(null);
myframe.pack();
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws ParseException {
new HangmanGUI();
}
}
code 2: with panel and components
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;
public class DetailsPanel extends JPanel {
public DetailsPanel() {
setPreferredSize(new Dimension(400, 600));
setBorder(BorderFactory.createTitledBorder(" ciick here "));
createFormattedPanel();
for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
String buttonText = String.valueOf(alphabet);
JButton letterButton = new JButton(buttonText);
letterButton.addActionListener(clickedbutton());
this.add(letterButton, BorderLayout.CENTER);
}
}
private ActionListener clickedbutton() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
System.out.println("actionCommand is: " + actionCommand);
}
};
}
public void createFormattedPanel() {
MaskFormatter formatter = null;
try {
JLabel label = new JLabel("Guesss");
formatter = new MaskFormatter("? ? ? ? ? ? ?");
formatter.setPlaceholderCharacter('?');
JFormattedTextField input = new JFormattedTextField(formatter);
input.setColumns(20);
this.add(label);
this.add(input);
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
}
}
A: "IF" I understand correctly, why not just add the buttons to their own panel and set the title border on it instead, for example...
public DetailsPanel() {
setPreferredSize(new Dimension(400, 600));
createFormattedPanel();
JPanel buttons = new JPanel();
buttons.setBorder(BorderFactory.createTitledBorder(" ciick here "));
for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
String buttonText = String.valueOf(alphabet);
JButton letterButton = new JButton(buttonText);
letterButton.addActionListener(clickedbutton());
buttons.add(letterButton, BorderLayout.CENTER);
}
add(buttons);
}
A: I would use an image JPanel to hold your hangman drawing, and to act as a placeholder and place it in the JFrame in the BorderLayout.CENTER position. I would also clean up the south JPanel by using layout managers and not relying on default FlowLayout. For instance a BorderLayout for the south Jpanel, put the guess in the page start slot and the buttons in the center slot, and put the buttons into a GridLayout JPanel. For example:
import javax.swing.*;
import javax.swing.text.MaskFormatter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.text.ParseException;
public class HangmanGUI {
private DetailsPanel myPanel;
private ImagePanel imagePanel = new ImagePanel();
public HangmanGUI() throws ParseException {
myPanel = new DetailsPanel();
JFrame myframe = new JFrame();
// myframe.getContentPane().setLayout(new BorderLayout());
myframe.getContentPane().add(imagePanel, BorderLayout.CENTER);
myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
myframe.setTitle("Hangman Game");
// myframe.setVisible(true);
// myframe.setLocationRelativeTo(null);
myframe.pack();
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setLocationRelativeTo(null);
myframe.setVisible(true);
}
public static void main(String[] args) throws ParseException {
new HangmanGUI();
}
}
class ImagePanel extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final String TITLE = "Hangman Image";
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public ImagePanel() {
setBorder(BorderFactory.createTitledBorder(TITLE));
}
}
class DetailsPanel extends JPanel {
public DetailsPanel() {
setLayout(new BorderLayout());
setBorder(BorderFactory.createTitledBorder(" ciick here "));
add(createFormattedPanel(), BorderLayout.PAGE_START);
JPanel letterPanel = new JPanel(new GridLayout(0, 5));
for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
String buttonText = String.valueOf(alphabet);
JButton letterButton = new JButton(buttonText);
letterButton.addActionListener(clickedbutton());
letterPanel.add(letterButton, BorderLayout.CENTER);
}
add(letterPanel, BorderLayout.CENTER);
}
private ActionListener clickedbutton() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
System.out.println("actionCommand is: " + actionCommand);
}
};
}
public JPanel createFormattedPanel() {
JPanel panel = new JPanel();
MaskFormatter formatter = null;
try {
JLabel label = new JLabel("Guesss");
formatter = new MaskFormatter("? ? ? ? ? ? ?");
formatter.setPlaceholderCharacter('?');
JFormattedTextField input = new JFormattedTextField(formatter);
input.setColumns(20);
// this.add(label);
// this.add(input);
panel.add(label);
panel.add(input);
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
return panel;
}
}
Also, don't set the position of a component or set it visible until after adding all and packing all. Don't set a component's size but rather let the preferred sizes and the layout managers set the sizes for you.
Edit
You ask:
first of all thank you for helping out. This is the solution I wanted. I have some basic questions though. why did you comment out // myframe.getContentPane().setLayout(new BorderLayout());
The JFrame's contentPane already uses BorderLayout by default so it would be unnecessary to explicitly set it to this layout.
also you created three panels, which is nice. for imagepanel, you specified the dimension. but for detailsPanel, you did not specify the dimension. does it mean?
I figure that the image will have a definite size, and so I override its getPreferredSize so that it will be big enough to show the image. All other components, I let them size themselves based on their component's preferred sizes and their layout managers.
if I have many panels and I specify dimension(size) for one panel, all others will get that default on the frame.
Again, all others will have their own preferred sizes based on the preferred sizes of their components and their layout managers.
A: You count create a GridLayout for your buttons like so:
public DetailsPanel() {
setPreferredSize(new Dimension(400, 600));
createFormattedPanel();
JPanel buttons = new JPanel();
buttons.setBorder(BorderFactory.createTitledBorder(" ciick here "));
buttons.setLayout(new GridLayout(5,6));
for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
String buttonText = String.valueOf(alphabet);
JButton letterButton = new JButton(buttonText);
letterButton.addActionListener(clickedbutton());
buttons.add(letterButton);
}
add(buttons);
}
Then I also added an extra dummy Panel in your main with just a label, change this label to what ever component you want:
myPanel = new DetailsPanel();
JFrame myframe = new JFrame();
JPanel aDummy = new JPanel();
aDummy.add(new JLabel("Extra text"));
myframe.getContentPane().setLayout(new BorderLayout());
myframe.getContentPane().add(aDummy, BorderLayout.CENTER);
myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
//...etc
Comes out like this
| |
doc_23532089
|
Currently php pages don't see Unicode 'get' arguments. The pages see the arguments as question marks, although we added <META http-equiv="Content-Type" content="text/html; charset=utf8">
See sample here.
Many thanks!
A: Output the strings trough utf8_encode();
| |
doc_23532090
|
join p in db.Users on e.ParentID equals p.Id
select new ViewEmployees
{
EmployeeName = e.Name,
EmployeeID = e.Id,
EmployeeCode = e.UserName,
ParentID = e.ParentID,
ParentName = p.Name
};
This query is written to pick the name of parent and shows all the employees..
It shows only the employee how have parent Id..
I want both who have parentId and who don't...
A: The first step in producing a left outer join of two collections is to perform an inner join by using a group join. (See How to: Perform Inner Joins (C# Programming Guide) for an explanation of this process.) In this example, the list of Person objects is inner-joined to the list of Pet objects based on a Person object that matches Pet.Owner.
The second step is to include each element of the first (left) collection in the result set even if that element has no matches in the right collection. This is accomplished by calling DefaultIfEmpty on each sequence of matching elements from the group join. In this example, DefaultIfEmpty is called on each sequence of matching Pet objects. The method returns a collection that contains a single, default value if the sequence of matching Pet objects is empty for any Person object, thereby ensuring that each Person object is represented in the result collection.
public static void LeftOuterJoinExample()
{
Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };
Pet barley = new Pet { Name = "Barley", Owner = terry };
Pet boots = new Pet { Name = "Boots", Owner = terry };
Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
Pet daisy = new Pet { Name = "Daisy", Owner = magnus };
// Create two lists.
List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };
foreach (var v in query)
{
Console.WriteLine("{0,-15}{1}", v.FirstName + ":", v.PetName);
}
}
http://msdn.microsoft.com/en-us/library/bb397895.aspx
A: You can get the parent User in a temporary variable parent like so:
var employees = from e in db.Users
let parent = db.Users.FirstOrDefault(p => e.ParentID == p.Id)
select new ViewEmployees
{
EmployeeName = e.Name,
EmployeeID = e.Id,
EmployeeCode = e.UserName,
ParentID = e.ParentID,
ParentName = parent.Name
};
You don't need to check for parent != null because the statement is translated into SQL, which is not troubled by null values.
It would even be easier if User had a navigation property Parent.
| |
doc_23532091
|
This is a line from my stored procedure:
SET @AdIDNumber = PARSENAME(REPLACE(@AdIDNumber, '-', '.'), 1);
ADIDNumber is a parameter being passed into this stored procedure. I'm trying to get the last component of the ADIDNumber nvarchar separated by '-'. I am getting the following error:
Conversion failed when converting from a character string to uniqueidentifier.
The strange thing is, it doesn't happen every time. Here are some ADIDNumbers that work:
188CR-000O-000199
188CR-000D-000105
and some that cause an error:
188CR-000A-000505
188CR-000S-001459
What am I doing wrong? Please help.
Thank you.
EDIT:
Here is my whole stored procedure:
ALTER PROCEDURE [dbo].[sp_getOutlookDetails]
-- Add the parameters for the stored procedure here
@CountryName nvarchar(max),
@CommunityName nvarchar(max),
@AdIDNumber nvarchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @dbName nvarchar(max);
-- remove spaces
SET @CountryName = LOWER(REPLACE(@CountryName, ' ', ''));
SET @CommunityName = LOWER(REPLACE(@CommunityName, ' ', ''));
SET @dbName = @CountryName;
IF @CommunityName IS NOT NULL
SET @dbName = @dbName+'_'+@CommunityName;
IF DB_ID(@dbname) IS NULL
BEGIN
RAISERROR('Database not found',16,1)
RETURN
END
DECLARE @tab AS TABLE (AdName nvarchar(max), OwnerJALName nvarchar(max), OwnerEmail nvarchar(max), AdContactEmail nvarchar(max),
AdWebsiteLink nvarchar(max), Ad1stPhone nvarchar(max), Ad2ndPhone nvarchar(max), VideoUrl nvarchar(max),
AdBusinessType nvarchar(max), AdBusinessLocation nvarchar(max),
PublishStatus INTEGER, MediaGalleryEnabled INTEGER, MapTabEnabled nvarchar(max),
MapCategory nvarchar(max), VMEnabled INTEGER);
-- format the PostID
SET @AdIDNumber = PARSENAME(REPLACE(@AdIDNumber, '-', '.'), 1);
-- we fill the table with LocationCoordinates in the MapCategory column twice so we can replace it later
DECLARE @dynsql nvarchar(max);
DECLARE @PostIDInt INTEGER;
SET @PostIDInt = CAST(@AdIDNumber AS INTEGER);
SET @dynsql = N'USE '+ QUOTENAME(@dbname) + N' SELECT dbo.cs_Posts.Subject, dbo.cs_Users.UserName, dbo.cs_Users.Email, dbo.drive_DirectoryPosts.ContactEmail,
dbo.drive_DirectoryPosts.ContactWebsite, dbo.drive_DirectoryPosts.ContactPhone, dbo.drive_DirectoryPosts.ContactPhoneOther, dbo.drive_DirectoryPosts.VideoUrl,
dbo.drive_DirectoryPosts.ContactBusinessType, dbo.drive_DirectoryPosts.ContactBusinessLocation,
dbo.drive_DirectoryPosts.IsActive, dbo.drive_DirectoryPosts.IsMediaGalleryActive,
dbo.drive_DirectoryPosts.LocationCoordinates, dbo.drive_DirectoryPosts.LocationCoordinates, dbo.drive_DirectoryPosts.IsMediaGalleryActive
FROM dbo.drive_DirectoryPosts INNER JOIN
dbo.cs_Posts ON dbo.drive_DirectoryPosts.PostID = dbo.cs_Posts.PostID INNER JOIN
dbo.cs_Users ON dbo.cs_Posts.UserID = dbo.cs_Users.UserID
WHERE dbo.cs_Posts.PostID = @PostIDInt';
INSERT INTO @tab EXECUTE sp_executesql @dynsql, N'@PostIDInt INTEGER', @PostIDInt = @PostIDInt;
DECLARE @MapCategory nvarchar(max);
DECLARE @VMEnabled INTEGER;
EXEC [dbo].sp_getMapCategory @dbName, @PostIDInt, @MapCategory OUTPUT, @VMEnabled OUTPUT;
UPDATE @tab SET MapCategory = @MapCategory;
UPDATE @tab SET VMEnabled = @VMEnabled;
SELECT * FROM @tab;
A: Maybe something like this:
DECLARE @AdIDNumber VARCHAR(MAX)
SET @AdIDNumber='188CR-000O-000199'
DECLARE @REVERSE VARCHAR(MAX)=REVERSE(@AdIDNumber)
select REVERSE(LEFT(@REVERSE,CHARINDEX('-',@REVERSE)-1))
A: It was caused by the sp_getMapCategory stored procedure.
| |
doc_23532092
|
TestID | Logic | Criterion_1 | Criterion_2 | ... | Criterion N
---------------------------------------------------------------------------------------
101 | 1 AND 2 | Apple | California | ... | Space Quest 6
102 | (1 OR 2) AND (3 OR 5 OR 6) | Banana | New Jersey | ... | Scorched Earth
My program would then compare this to some data and see if criteria match the data in some pattern that satisfies the logic. In my ideal world, I could take the Logic string and replace the numbers with tests:
(DataElement_1 = Criterion_1) AND (DataElement_2 = Criterion_2)
for Test 101. Of course, simply replacing pieces like that does not logic make. Is there some way in VBA to evaluate that as though it were in-code logic? Is there, perhaps, a better way of doing this that I have completely overlooked?
Thanks!
A: Sub ert()
LastRow = Worksheets("data").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 'finds the last row with data on the "data" sheet
For i = 1 To LastRow 'for each row
evalstr = "=" & Cells(i, 2).Value 'creates a function from the statement in column "B"
evalstr = Replace(evalstr, "AND", "*") 'replaces the "AND" operator with a logical multiplication
evalstr = Replace(evalstr, "OR", "+") 'replaces the "OR" operator with a logical addition
For j = 1 To 7 'for each condition
evalstr = Replace(evalstr, CStr(j), Cells(i, 2 + j).Value = ActiveWorkbook.Names("Criterion_" & j).RefersToRange.Value) 'replace the reference with the applicable evaluation
Next
Worksheets("data").Cells(i, 10) = evalstr 'inserts the formula to your "J" column
Next
End Sub
Works fine on my test worksheet.
| |
doc_23532093
|
Is there any problem if all computers are running simultaneously?
And what about SQL Server connection pools?
Note that when I try to find active connections of my database on SQL Server using this command:
sp_who
I found more than 20 active connection .
Does this cause a problem ?
A: For Windows 7 runing SQL Server:
It appears that only 20 simultaneous connections are allowed from other devices.(Source) However, depending on the applications that are running on these 20 devices, possibly more connections can be initiated and that can be causing what you see.
Also make sure that you are properly closing connections within your application as necesary and not leaving connections open unnecesarily.
For any Windows Server OS, the following applies in case your need for simultaneous connections is greater:
From How to: Set User Connections (SQL Server Management Studio) - MSDN
To set user connections
*
*In Object Explorer, right-click a server and click Properties.
*Click the Connections node.
*Under Connections, in the Max number of concurrent connections box, type or select a value from 0 through 32767 to set the maximum number
of users that are allowed to connect simultaneously to the instance of
SQL Server.
*Restart SQL Server.
Maximum connections, therefore, is 32,767 and this is true through SQL Server 2014.
You can run sp_configure to get the current running value as well.
A: If you're just looking at ten clients, SQL Server should be able to handle that.
Beyond that, it's just a matter of designing for that kind of load. For instance, you want to make sure you've got the right locks happening at the right times. In essence, having multiple concurrent clients accessing the same database is the same as having multiple, concurrent threads accessing the same variables on a single machine. The database is a bit smarter than just, say, an int, but you'll still want to make sure you're on top of how things happen.
For instance, say you have a table for Tasks that you want to complete, and it has a column for the ID and one for the LastCompleted time. On a single client, you might want to write something that accesses it like this:
*
*Fetch the next one which has LastCompleted < DATEADD(HOUR, -1, GETDATE())
*Do that task, which takes five minutes
*UPDATE the table to set LastCompleted = GETDATE()
You could then complete all tasks every hour, pretty easily.
However, if you were faced with multiple clients accessing, this would result in multiple clients grabbing the same task multiple times, and doing it concurrently. In that scenario, you'd probably want another column to indicate InProgressAsOf as a date, then you can retry orphaned tasks as necessary but you never risk overlapping things happening. And even with that, you'd probably want to use OUTPUT clauses on your UPDATE to make sure it was all atomic.
*
*Fetch the result from UPDATE Tasks SET InProgressAsOf = GETDATE() OUTPUT DELETED.* WHERE LastCompleted < DATEADD(HOUR, -1, GETDATE()) AND InProgressAsOf < DATEADD(MINUTE, -10, GETDATE())
*Do that task, which takes five minutes
*UPDATE the table to set LastCompleted = GETDATE()
But yes, as long as you're on top of those nuances of multithreaded operations, you should be fine running ten concurrent connections against the same database.
| |
doc_23532094
|
I need that flash is worked permanently, regardless of outside light.
In order to accomplish it i have changed one line of code:
private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
if (mFlashSupported) {
// requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
}
}
It was CONTROL_AE_MODE_ON_AUTO_FLASH i have changed it to CONTROL_AE_MODE_ON_ALWAYS_FLASH.
And i have faced with issue, when i click Take picture button, camera is flashing and that is it. App goes to stack...
What am i doing wrong?
EDIT
I figure out next:
i have tryed tern on flash on three different device Meizu MX5, Samsung S5 and Samsung S6.
Two of them Meizu MX5, Samsung S5 work correctly with code above and app doesn't drives in stack.
Problem occur with Samsung S6, BUT ...
Method setAutoFlash() invokes within code 3 times in different places
*
*captureStillPicture()
*unlockFocus()
*onConfigured()
And trick is if i disable setAutoFlash() in captureStillPicture() for Samsung S6 it is stop stacking and flash begins to works but if i try this approach for Meizu MX5, Samsung S5 flash doesn't works...
A: Eventually i found solution
As i said method
protected final void setAutoFlash(CaptureRequest.Builder requestBuilder) {
if (isFlashSupported) {
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
}
}
invoked in three different places in code.
*
*captureStillPicture()
*unlockFocus()
*onConfigured()
So i implemented this line requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); locally in each method.
Finally that i get :
*
*unlockFocus() ->
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
*onConfigured() ->
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
and for this method remained auto settings
*captureStillPicture() ->
captureBuilder.set(CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
But i don't know the reason why i got such issue... If someone know the reason please let me know.
| |
doc_23532095
|
import cv2
import numpy as np
img = cv2.imread('\\home\\gaiarsa\\matrix\\poste.jpg')
gray = cv2.imread('\\home\\gaiarsa\\matrix\\poste.jpg', 1)
sift = cv2.xfeatures2d.SIFT_create()
dummy = np.zeros((1,1))
kp = sift.detect(gray, None)
img = cv2.drawKeypoints(gray, kp,dummy, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imwrite('sift_keypoints.jpg', img)
After I run it I get the error:
OpenCV Error: Assertion failed (!outImage.empty()) in drawKeypoints, file /home/gaiarsa/opencv/modules/features2d/src/draw.cpp, line 113
Traceback (most recent call last):
File "sift.py", line 14, in <module>
img = cv2.drawKeypoints(gray, kp,dummy, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.error: /home/gaiarsa/opencv/modules/features2d/src/draw.cpp:113: error: (-215) !outImage.empty() in function drawKeypoints
When I try removing the dummy array from the function arguments, I get the following error:
Traceback (most recent call last):
File "sift.py", line 14, in <module>
img = cv2.drawKeypoints(gray, kp, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
TypeError: Required argument 'outImage' (pos 3) not found
A: The problem was reading a png file as a jpeg. As soon as I changed it, it worked
A: Just check you filenames. If they are wrong you'll not get nice error messages, but just get NULL pointers or whatever, and the program will only break way up ahead giving a message such as this...
A: Path doesn't exist!(if the extension is .png is the same)
'\home\gaiarsa\matrix\poste.jpg'
Check the path before use it:
import os
if not os.path.exists('path/file'):
print('Incorrect path or file missing')
exit(0)
| |
doc_23532096
|
Logging the EXTRA_STATE and EXTRA_STATE_RINGING it gives me the same response that they are both "RINGING" I have also tried comparing it directly to the text "RINGING"
In OnReceive
Log.d("DebugData", intent.getExtras().getString(TelephonyManager.EXTRA_STATE));
Log.d("DebugData", TelephonyManager.EXTRA_STATE_RINGING);
if (intent.getExtras().getString(TelephonyManager.EXTRA_STATE) == TelephonyManager.EXTRA_STATE_RINGING) {
Log.d("DebugData", "The Phone is ringing");
} else {
// Do Nothing
}
I expect the comparison to output true but it outputs false.
A: You can't compare strings in Java with ==, you need to use .equals() instead.
e.g.
if (TelephonyManager.EXTRA_STATE_RINGING.equals(intent.getExtras().getString(TelephonyManager.EXTRA_STATE))) { ... }
read more here: https://www.geeksforgeeks.org/difference-equals-method-java/
| |
doc_23532097
|
var contactDetails = context.contacts
.Where(s=>s.contact_code == contactCode)
.Join(context.accounts, s => s.)
It will not list down the properties after "."
Any Idea? I have import the using System.Linq too.
A: var contactDetails = (from con in context.contacts.Where(s=>s.contact_code == contactCode)
join acc in context.accounts
on con.Property equals acc.Property
select con or select acc or select new{con,acc})
select con if you only want contacts
select acc if you only want accounts
select new{con,acc} if you only want both
Note use only one select
| |
doc_23532098
|
Is it possible to dynamically create previous and next buttons in a jquery dialog box?
I have a list of links, and I would like to click on a link and have a dialog box open. In that dialog box would have a previous and next button that when clicked on would close the current dialog box and open the previous or next item in the list in another dialog box and so on.
Somthing like this
HTML
<ul id="dialoglist">
<li>
<a href="list1.html">
</li>
<li>
<a href="list2.html">
</li>
<li>
<a href="list3.html">
</li>
<li>
<a href="list4.html">
</li>
</ul>
jQuery
$("ul#dialoglist a").click(function(){
var link = $(this).attr('href') + " #content";
var box = $('<div></div>').load(link).dialog({
buttons: {
"prev": function() {
$(this).dialog('close');
//open previous dialog
},
"next": function() {
$(this).dialog('close');
//open next dialog
}
}
});
$(box).dialog('open');
return false;
});
Thanks
A: Something like this should work:
$("ul#dialoglist a").click(function(){
var a = $(this);
var link = a.attr('href') + " #content";
// move button creation here so we can dynamically build
// the button hash:
var aParent = a.parent();
var buttons = {};
var prevLi = aParent.prev();
var nextLi = aParent.next();
if(prev.length > 0){
buttons.prev = function(){
// not sure if this is in the corret scope here - you may need to select by id
$(this).dialog('close');
$('a', prevLi).click();
};
}
if(next.length > 0){
buttons.next = function(){
/ not sure if this is in the corret scope here - you may need to select by id
$(this).dialog('close');
$('a', nextLi).click();
};
}
var box = $('<div></div>').load(link).dialog({
'buttons': buttons
});
$(box).dialog('open');
return false;
});
Since you just trigger the click event on the prev/next links you shouldnt have to worry about manually openeing the dialogs.
However... why open new dialogs instead of using the dialog widgets api to set the content directly?
A: I'm kind of new to Jquery, I have a bit of experience but not much, but the solution prodigitalson provided looks great, it just seems to me that since you are getting the click event, wouldn't you need to prevent the default link click? Otherwise, it will just try to follow the href provided in the anchor, right?
Sorry to post this as an answer, but my reputation isn't enough to post a comment...
A: JS
$(function() {
/* construct prev/next button */
$(".dialog div.dialogs").each(function (i) {
var totalSize = $(".dialog div.dialogs").size() - 1;
if (i != 0) {
prev = i - 1;
$(this).append("<div class='prev_button'><a href='#tabs' class='prev-tab mover' rel='" + prev + "'>Previous</a></div>");
}
if (i != totalSize) {
next = i + 1;
$(this).append("<div class='next_button'><a href='#tabs' class='next-tab mover' rel='" + next + "'>Next</a></div>");
}
});
/* next button click */
$('.next-tab').click(function () {
var nextDialog= $(this).parent().parent().data("id") + 1;
var currentDialog = $(this).parent().parent(); currentDialog.dialog("close");
$("#dialog"+ nextDialog).dialog();
});
/* previous button click */
$('.prev-tab').click(function () {
var prevDialog = $(this).parent().parent().data("id") - 1;
var currentDialog = $(this).parent().parent(); currentDialog.dialog("close");
$("#dialog"+ prevDialog).dialog();
});
/* intial dialog(first) */
$( "#dialog1" ).dialog();
});
HTML
<div class="dialog" style="display:none">
<div id="dialog1" class="dialogs" data-id="1" title="dialog1">
<p>Dialog content1</p>
</div>
<div id="dialog2" class="dialogs" data-id="2" title="dialog2">
<p>Dialog content2</p>
</div>
<div id="dialog3" class="dialogs" data-id="3" title="dialog3">
<p>Dialog content3</p>
</div>
<div id="dialog4" class="dialogs" data-id="4" title="dialog4">
<p>Dialog content4</p>
</div>
</div>
PLUGGINS
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
| |
doc_23532099
|
1.In app/views/participations/show.html.erb
I would like to make a call like this to return prefered exam_center's city field which kept under the exam_centers table:
<%= @participation.exam_center_preference %>
But it's only returning the ID. I need to fetch the exam_center's "city" field with this ID number.
2.In app/views/participations/index.html.erb
I need to make exactly the same thing in show.html.erb
<%= participation.examination.bookings %>
3. In app/views/participations/_form_html.erb
I don't know how to call data from exam_centers model in my form partial for Participation model. When I use something like this;
<%= f.input :exam_center_preference, collection:Booking.where(examination_id: @examination.id), label: 'Choose', label_method: :id %>
It's returning ID's of related exam_centers - but I also need "city" values from ExamCenter model as label_method.
See collection and label_method below:
<%= simple_form_for([@examination, @participation]) do |f| %>
<%= f.input :exam_center_preference, collection:HOW?, label: 'Choose', label_method: HOW? %>
<%= f.button :submit, "Save", :class => 'btn btn-large btn-warning' %>
<% end %>
Thanks in advance.
Here is the my model structure:
examination.rb:
class Examination < ActiveRecord::Base
has_many :participations
has_many :users, :through => :participations
has_many :bookings
has_many :exam_centers, :through => :bookings
end
participation.rb:
class Participation < ActiveRecord::Base
belongs_to :user
belongs_to :examination
end
user.rb
class User < ActiveRecord::Base
foo-bar
end
As you can see I'm having "Participation" as a join model between Examination and User models.
I also have this kind of relationship between Examination and ExamCenter with a "Booking" join model. This is the structure =>
examination.rb
class Examination < ActiveRecord::Base
you-can-see-above
end
booking.rb
class Booking < ActiveRecord::Base
belongs_to :examination
belongs_to :exam_center
end
exam_center.rb
class ExamCenter < ActiveRecord::Base
has_many :bookings
has_many :examinations, :through => :bookings
end
*Schema Structure => *
create_table "examinations", force: true do |t|
t.string "name"
t.string "shortname"
t.datetime "exam_date"
end
create_table "participations", force: true do |t|
t.integer "user_id"
t.integer "examination_id"
t.boolean "payment_status"
t.string "language_preference"
t.string "exam_center_preference"
end
create_table "bookings", force: true do |t|
t.integer "examination_id"
t.integer "exam_center_id"
end
create_table "exam_centers", force: true do |t|
t.string "country"
t.string "city"
t.string "building"
t.text "address"
end
Routes =>
resources :exam_statuses, :exam_centers, :exam_fees
resources :examinations do
resources :participations do
member do
get :update_profile_information
get :approve_application
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.