text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to read and connect a csv file to a sql database I am looking for ways I can take a csv file read it line by line then take selected coluns and rows and connect them to a mysql database.
I have made the following code however I am unable to connect it to insert in a sql database.
How can I connect this to my db with Columns Time,Name,Location all Varchars?
Imports System.IO
Imports System.IO
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim com As New SqlCommand
Dim str As String
Public Sub ReadCSVFile()
Dim fileIn As String = "C:\Users\FFFF\Downloads\new.csv"
Dim fileRows(), fileFields() As String
TextBox1.Text = String.Empty
If File.Exists(fileIn) Then
Dim fileStream As StreamReader = File.OpenText(fileIn)
fileRows = fileStream.ReadToEnd().Split(Environment.NewLine)
For i As Integer = 0 To fileRows.Length - 1
fileFields = fileRows(i).Split(",")
If fileFields.Length >= 4 Then
TextBox1.Text += fileFields(3) & " " & fileFields(2) & " " & fileFields(0) & "<br /> "
End If
Next
Else
TextBox1.Text = fileIn & " not found."
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call ReadCSVFile()
End Sub
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con = New SqlConnection("Data Source=FFF-PC;Initial Catalog=MySolution;User Id=sa;Password=sarfar.811;")
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "fileFields(3)")
cmd.Parameters.Add("@Time", SqlDbType.VarChar, 20, "fileFields(2)")
cmd.Parameters.Add("@Location", SqlDbType.VarChar, 50, "fileFields(0)")
Dim strSql As String = "Insert into New_1(Name,Time,Location) values(@Name@Time,@Location)"
Dim dAdapter As New SqlDataAdapter()
dAdapter.InsertCommand = cmd
'Dim result As Integer = dAdapter.Update(ReadingCsv)
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
A: cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "fileFields(3)") will pass "filefields(3)" as a string when you're really trying to pass the actual field. When your insert is called, you're going to have to write some sort of a loop through your code and then you can insert it like:
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
Where your value and columns correspond. Now to get the CSV, save it as a variable (parse it from the text box included in this) or pass it back from the webpage. Once you have it back, I'd create a class which holds your file field so you can read your code later then stick that into a list. Iterate through that list and make a string. I'd use a string builder because I think it's more readable. Then you can drop your creating parameters and just call the strSql directly. Does this make sense?
If this answer still helps you / you're curious about the actual code, comment and I'll write it but as it's a month old I'm assuming you solved your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18650268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Electron webContents executeJavaScript : Cannot execute script on second on loadURL I am testing out Electron and specifically working with executeJavaScript. My project uses a POST request to sign into a website, then does a bit of work and loads a second URL using the same session. In this second URL, I need to execute JS but I am not sure what I am doing wrong.
In this example I created a dumbed down version that simulates going to two URL's and executing JS on the second. Any ideas on what is going on here?
const {app, BrowserWindow} = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({width: 1000, height: 600})
win.openDevTools();
// First URL
win.loadURL('https://www.google.com')
// Once dom-ready
win.webContents.once('dom-ready', () => {
// THIS WORKS!!!
win.webContents.executeJavaScript(`
console.log("This loads no problem!");
`)
// Second URL
win.loadURL('https://github.com/electron/electron');
// Once did-navigate seems to function fine
win.webContents.once('did-navigate', () => {
// THIS WORKS!!! So did-navigate is working!
console.log("Main view logs this no problem....");
// NOT WORKING!!! Why?
win.webContents.executeJavaScript(`
console.log("I canot see this nor the affects of the code below...");
const form = document.querySelectorAll('form.js-site-search-form')[0];
const input = form.querySelectorAll('input.header-search-input')[0]
input.value = 'docs';
form.submit();
`)
})
})
}
app.on('ready', createWindow );
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
A: It is because you are trying to run the Javascript before the dom-ready event.
Try executing your javascript after this event is completed like below
const { app, BrowserWindow } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({ width: 1000, height: 600 })
win.openDevTools();
// First URL
win.loadURL('https://www.google.com')
// Once dom-ready
win.webContents.once('dom-ready', () => {
// THIS WORKS!!!
win.webContents.executeJavaScript(`
console.log("This loads no problem!");
`)
// Second URL
win.loadURL('https://github.com/electron/electron');
// Once did-navigate seems to function fine
win.webContents.once('did-navigate', () => {
// THIS WORKS!!! So did-navigate is working!
console.log("Main view logs this no problem....");
win.webContents.once('dom-ready', () => {
// NOT WORKING!!! Why?
win.webContents.executeJavaScript(`
console.log("I canot see this nor the affects of the code below...");
const form = document.querySelectorAll('input.js-site-search-form')[0];
const input = form.querySelectorAll('input.header-search-input')[0]
input.value = 'docs';
form.submit();
`)
})
});
})
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43554536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do i find the duplicates in java array I am trying to make it so if there are any duplicates in the array, it turns true and if there is not it turns false. But, no matter what I do the if statement always turns in into false, even if there isn't a duplicate. This has to be done as a boolean.
int array[] = {10, 20, 30, 10, 40, 50};
public boolean hasDuplicates2() {
for (int i = 0; i <= array.length; i++) {
for (int i2 = 1; i2 <= array.length - 1; i2++) {
if (array[i] != array[i2]) {
return false;
}
}
}
return true;
}
A: public static void main(String[] args) {
int array[] = {10, 20, 30, 10, 40, 50};
System.out.println(hasDuplicates(array));
}
public static boolean hasDuplicates(int[] array) {
var distinct = Arrays.stream(array).distinct().count();
return distinct != array.length;
}
A: your code return false because its stops when first cycle says its false
and after that your for statement return false
instead of "return false" you can change a bit
public boolean hasDuplicates2()
{
bool hasDuclicates = false;
for (int i = 0; i < array.length; i++) {
for (int i2 = i+1; i2 < array.length - 1; i2++) {
if (array[i] == array[i2]) {
hasDuplicates = true;
}
}
}
return hasDuplicates;
}
it may not be efficient by the way
A: So a couple of problems:
1)You need to have array.length - 1 even in the first for loop, or you're going to go out of range at the last iteration.
2)You're checking each and every element including the element itself - which means when i = i2, you're always going to satisfy the if condition, so you need to check for that as well.
Try this:
public static boolean hasDuplicates2(int[] array) {
for (int i = 0; i <= array.length - 1; i++) {
for (int i2 = 1; i2 <= array.length - 1; i2++) {
if (i != i2 && array[i] == array[i2]) {
return true;
}
}
}
return false;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74161293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Linking a JavaScript file to HTML file not working by any means I've tried all the posibilities as described in previous similar cases and still no results.
I'm adding the link tags at the end of the of the HTML and I am calling the folder where the file is placed but still nothing.
</div>
<script type="text/javascript" src="../pages/counter.js"></script>
Folder structure:
A: It's not clear for me where is the js file. But you should try the same folder:
"./pages/counter.js"
A: Looks like pages has the same hierarchy level as index.html, so the path getting used is incorrect.
Try using the following path:
</div>
<script type="text/javascript" src="./pages/counter.js"></script>
Let me know in case of issues
A: Seems like your index file is in same directory as of pages. So try
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59229459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Pull List of GA4 Properties Using Google Analytics Admin API and App Script Wondering if anyone has experience exporting a list of GA accounts and properties to a spreadsheet using the new Analytics Admin API.
I've used the Management API for this purpose in the past but that limits us to UA properties and I want to hopefully include GA4 properties here as well.
I've taken a shot at converting an old script to the new API but I haven't even succeeded in pulling in account names.
function listGA4Accounts() {
var createss = SpreadsheetApp.create("Google Analytics Accounts");
var ssid = createss.getId();
var openss = SpreadsheetApp.openById(ssid);
var insertsheet = openss.insertSheet('Google Analytics Schema');
insertsheet.setFrozenRows(1);
insertsheet.getRange("A1:D1").setValues([['displayName', 'Account ID', 'Property Name', 'Property ID']]);
var sheet = SpreadsheetApp.openById(createss.getId()).getSheetByName("Google Analytics Schema")
var accounts = AnalyticsAdmin.Accounts.list();
if (accounts && !accounts.error) {
accounts = accounts.accounts;
// Logger.log(accounts[0]);
for (var i = 0, account; account = accounts[i]; i++) {
sheet.appendRow([accounts.accounts[i].displayName]);
}
}
}
A: I've been struggling with this as well. Here's what I came up with after a lot of trail and error:
function listAccounts() {
try {
accounts = AnalyticsAdmin.AccountSummaries.list();
//Logger.log(accounts);
if (!accounts.accountSummaries || !accounts.accountSummaries.length) {
Logger.log('No accounts found.');
return;
}
Logger.log(accounts.accountSummaries.length + ' accounts found');
for (let i = 0; i < accounts.accountSummaries.length; i++) {
const account = accounts.accountSummaries[i];
Logger.log('** Account: name "%s", displayName "%s".', account.name, account.displayName);
if (account.propertySummaries) {
properties = AnalyticsAdmin.Properties.list({filter: 'parent:' + account.account});
if (properties.properties !== null) {
for (let j = 0 ; j < properties.properties.length ; j++) {
var propertyID = properties.properties[j].name.replace('properties/','');
Logger.log("GA4 Property: " + properties.properties[j].displayName + '(' + propertyID + ')')
}
}
} else {
var accountID = account.account.replace('accounts/','');
var webProperties = Analytics.Management.Webproperties.list(accountID);
for (var j = 0; j < webProperties.items.length; j++) {
Logger.log("UA Property: " + webProperties.items[j].name + '(' + webProperties.items[j].id + ')');
var profiles = Analytics.Management.Profiles.list(accountID, webProperties.items[j].id);
for (var k = 0; k < profiles.items.length; k++) {
Logger.log('Profile:' + profiles.items[k].name);
}
}
}
}
} catch (e) {
// TODO (Developer) - Handle exception
Logger.log('Failed with error: %s', e.error);
}
}
Not saying it's the right way...but it does appear to be able to pull all of my UA and GA4 properties.
If you only want GA4 properties then you can leave out the else on "if (account.propertySummaries)".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71772152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to count the number of occurrences of a specific value in a column in SQL without doing two SQL calls I have a table: Judges(JName char(25), LawSchool char(25)).
I'm trying to retrieve the number of judges that attended Harvard and the number of Judges that attended Yale in one SQL Call. I know that I could do this
SQL CALL 1)
select LawSchool, count(*) as cnt from Judges where LawSchool = 'Harvard'
SQL CALL 2)
select LawSchool, count(*) as cnt from Judges where LawSchool = 'Yale'
But is there not a way I can retrieve the number of Judges who attended Yale and the number of judges who attended Harvard in one SQL call but store them in two variables such as cnt and cnt2?
A: select LawSchool, count(*) as cnt
from Judges
where LawSchool in ('Harvard','Yale')
Group By LawSchool
A: You can use a group by clause to separate the aggregate result per unique value:
SELECT LawSchool, COUNT(*)
FROM Judges
WHERE LawSchool IN ('Harvard', 'Yale')
GROUP BY LawSchool
A: You can use in and group by
select LawSchool, count(*) as cnt
from Judges where LawSchool in ( 'Harvard', 'Yale')
group by LawSchool
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40293856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Grip control in Kinect I want to use the grip control in Kinect. I cant find sources related to grip control in Kinect sdk.
Does Kinect sdk provides inbuilt support for recognizing the grip movement,or we have to write our own?
Is there any open source samples available for grip control in Kinect?
A: The Kinect for Windows SDK v1.7 introduced Grip recognition for up to four hands simultaneously, which includes new controls for WPF.
I suggest you download that version of the SDK in case you are not using it yet, and check the documentation for details of its usage and capabilities.
Source: kinectingforwindows.com
Source: blog.msdn.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16036144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: totaljs --translate command does not find all texts for translation , despite wrapped in ‘@()’ tag I followed this documentation
and executed total.js --translate command in the root directory of total.js eshop app. But many words despite wrapped in ‘@()’ tag not available for translation in the created file.
For example “@(Category),@(Manufacturer),@(Availability),@(In stock), and more” in product template (/themes/default/views/cms/product.html) don’t exist in created “translate.resource” file.
What is the problem here or what am I doing wrong?
A: Which version of Total.js are you using? Try to install latest beta version of Total.js framework as a global module: $ npm install -g total.js@beta and try again --translate. If your problem still persists, write me an email at [email protected]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57975091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I remove -fobjc-arc flag when convert to ARC? I was wanted to convert my project to ARC which is using partial files in ARC already. They are using -fobjc-arc flags in build phases, and I did refactoring(Edit->Refactor->Convert to Objective-C ARC) but those flags are still remained in Build Phase.
What I am not clear here,
*
*When I refactor project to ARC, the project is changing to ARC mode or just the code in class files(.m) are changing to ARC type?
Anybody experiencing this, advice is great help to me
A: I figured out this answer. It's doing both, changing target to ARC as well as code to ARC but not converting -fobjc-arc flag at build phase
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29312049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access parent window which contains modal from iframe which opens in that modal I have an html page named parent.html which has Bootstrap accordion. By clicking a link on accordion, it calls in another page search.html and opens the iframe on a modal.
search.html has a button "finish" whose functionality is to close the modal, post data on the accordion, and accordion should remain open.
I tried .opener(). It didn't seem to work. Any pointers??
parent.html
Shop for Florist
Find Florist
$(function () {
$("*[data-modal]").click(function (e) {
e.preventDefault();
var href = $(this).attr('href');
if (href.indexOf('#') != 0) {
$('<div id="searchBox" class="modal bigModal" data-backdrop="static"><div class="searchModal-header gutter10-lr"><button type="button" onclick="window.location.reload()" class="close" data-dismiss="modal" aria-hidden="true">×</button></div><div class=""><iframe id="search" src="' + href + '" class="searchModal-body"></iframe></div></div>').modal();
}
});
});
search.html
<!DOCTYPE html>
<html lang="en">
<head>
<head>
<meta charset="utf-8">
<title>Getting Started</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../css/bootstrap.css">
</head>
<body id="detail">
<form class="form-horizontal" id="frmdetail" name="frmdetail" action="preferences" method="POST">
<div class="row-fluid gutter10-tb border-t">
<a class="btn btn-primary my-list" href="#">Finish</a>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
if (top === window) {
alert("this page is not in an iframe");
} else {
alert ("Im here");
$('.my-list').click(function(){
alert("Im clicked");
$('.modal', opener.document).dialog('close');
});
}
});
</script>
</body>
</html>
A: You can try with postMessage:
http://en.wikipedia.org/wiki/Cross-document_messaging
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
You should send a command from search.html to the main page and let the main page handle the event of a received message.
You'll find what you need in the links above
Example (Parent page):
window.onmessage = function(e){
//Here is the data that you receive from search.html
var DataReceived = e.data;
var OriginUrl = e.origin;
//Do what you want when the message is received
};
Example (search.html):
function buttonClick() {
var curDomain = location.protocol + '//' + location.host; //This will be received as e.origin (see above)
var commandString = "Hello parent page!"; //This will be received as e.data
parent.postMessage(commandString,curDomain); //Sends message to parent frame
}
The windows.onmessage in the parent page should be 'launched' on page load. The 'buttonClick()' function could be called when and where you want to send a message to the parent page that will execute some stuff (in this case your stuff with accordion)
EDIT:
to close the modal try this way:
Parent:
window.onmessage = function(e){
//Here is the data that you receive from search.html
var DataReceived = e.data;
var OriginUrl = e.origin;
if (e.data == 'close') {
$(this).modal('hide'); //Example code, you can run what you want
}
};
Search:
function buttonClick() {
var curDomain = location.protocol + '//' + location.host; //This will be received as e.origin (see above)
var commandString = "close"; //This will be received as e.data
parent.postMessage(commandString,curDomain); //Sends message to parent frame
}
In this case you send the message 'close' to the parent frame. When parent receive the message he check if it's "close" and then run the code you want (in this case you close your modal with $(".modal").dialog('close'))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16067515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get open window instance from a third window I have one window (in domain-1) from there I need to open a new window (in another domain say domain-2). Now in domain-2 I need to open a same window (parent of domain-1) but need to close the already opened window (which is parent).
Is it possible?
Flow is like:
domain1.window1 [1st] ----open in new window ---> domain2.window2 [2nd] ----- open in new window --> domain1.window1 [3rd], but first instance needs to close.
One thing... is there any way by which one window can check whether it is already open; without the window object reference?
A: I don't think it's possible. Because of the same origin policy, you can't communicate between window 2 and window 1 and 3. So window 1 and 3 can't communicate. Unless you're using some session or cookies, but it's outside the scope of you question if I'm not mistaken.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17608573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to adjust the advance amount to corresponding bills in CodeIgniter? I need to adjust/allocate the advance amount to the corresponding bills, if it's possible.
For example: Exactly advance amount is less than of invoice amount, may be if overpaid i just want to adjust the excess amount(means Invoice amt rs. 8500/- but paid amt is Rs.10,000/-, here Rs.1,500 is the excess amount) to the next corresponding bills when the excess amount turns zero.
If customer pay advance amount Rs.10,000/- I want to allocate the amount to the customer bills like: 1st bill like Rs.5000/-, 2nd bill Rs.3500/-, 3rd bill Rs.3000/-, after adjusting the advance amount Rs.10,000/- balance amount the customer wants to pay us is Rs.1500/-.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24242016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a table with Silverlight for Windows Phone 7 I'd like to create a table on WP7. This is my current approach using a ListBox with a Grid as the data template.
<ListBox x:Name="ResultsList" Margin="12,0" Grid.Row="1">
<ListBox.Resources>
<DataTemplate x:Key="ResultsListItem">
<Grid d:DesignWidth="385" Height="28">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="88"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="textBlock1" Margin="0,0,24,0"/>
<TextBlock x:Name="textBlock2" Margin="0,0,24,0"
VerticalAlignment="Top" Grid.Column="1"/>
<TextBlock x:Name="textBlock3" Margin="0,0,24,0"
VerticalAlignment="Top" Grid.Column="3"/>
</Grid>
</DataTemplate>
</ListBox.Resources>
<ListBox.ItemTemplate>
<StaticResource ResourceKey="ResultsListItem"/>
</ListBox.ItemTemplate>
</ListBox>
The problem is, that the resulting table's columns are not sized equally. The Grid's column definitions are applied to each row independently of the other rows. That means, if there is a long text in textBlock1, column 0 will be larger. In the next row there could be a shorter text in textBlock1, resulting in column 0 also being shorter than the column 0 in the previous row.
How can the columns in all rows be sized equally? I don't want to use fixed width because when the orientation changes from portrait to landscape the colums would resize automatically.
There is the HeaderedItemsControl, but as I understand it it is not available for Windows Phone 7?
A: This is a tricky problem! In WPF there exists the concept of a SharedSizeGroup, which allows you to share column widths across multiple grids, but this is not available in silverlight.
There are a few workarounds on the web:
http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/
http://databaseconsultinggroup.com/blog/2009/05/simulating_sharedsizegroup_in.html
Although neither are simple solutions.
You might also try Mike's AutoGrid:
http://whydoidoit.com/2010/10/06/automatic-grid-layout-for-silverlight/
A: Here is my solution using SharedSizeGroup as suggested by ColinE.
<ListBox x:Name="ResultsList">
<ListBox.Resources>
<SharedSize:SharedSizeGroup x:Key="Col1Width" />
<SharedSize:SharedSizeGroup x:Key="Col2Width" />
<SharedSize:SharedSizeGroup x:Key="Col3Width" />
<DataTemplate x:Key="ResultsListItem">
<StackPanel d:DesignWidth="385" Orientation="Horizontal">
<SharedSize:SharedSizePanel WidthGroup="{StaticResource Col1Width}">
<TextBlock x:Name="textBlock" MaxWidth="100" Text="{Binding A}"/>
</SharedSize:SharedSizePanel>
<SharedSize:SharedSizePanel WidthGroup="{StaticResource Col2Width}">
<TextBlock x:Name="textBlock1" MaxWidth="85" Text="{Binding B}"/>
</SharedSize:SharedSizePanel>
<SharedSize:SharedSizePanel WidthGroup="{StaticResource Col3Width}">
<TextBlock x:Name="textBlock2" MaxWidth="200" Text="{Binding C}"/>
</SharedSize:SharedSizePanel>
</StackPanel>
</DataTemplate>
</ListBox.Resources>
<ListBox.ItemTemplate>
<StaticResource ResourceKey="ResultsListItem"/>
</ListBox.ItemTemplate>
</ListBox>
Even the maximum with of each column can be controlled via the TextBlock's MaxWidth property. The SharedSizeGroups ensure that the TextBlocks have the same size in each row.
A: You can use WrapPanel. Set the following ItemsPanel in the Datatemple, you can just have textblock.
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<control:WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4562104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use scalajs-bundler with client only app In another question I was advised to use ScalaJS bundler to import NPM dependencies.
I would like to use some Javascript NPM packages in a simple client-only web application. There is an example called static which shows this.
My changes to the example:
Add into build.sbt:
npmDependencies in Compile += "esprima" -> "3.1.3"
Add into Main.scala:
import Esprima._
import JsonToString._
val code = "answer = 42"
val tokens = tokenize(code)
val tokensStr = tokens.json
Change in Main.scala: "This is bold" into s"This is bold $tokensStr"
Facade (a bit simplified, for full a version see GitHub):
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
@JSName("esprima")
@js.native
object Esprima extends js.Object {
def tokenize(input: String, config: js.Any = js.native, delegate: String => String = js.native): js.Array[js.Any] = js.native
def parse(input: String, config: js.Any = js.native): js.Dynamic = js.native
}
When running the html generated with fastOptJS::webpack the error is:
Uncaught TypeError: Cannot read property 'tokenize' of undefined
Inspecting the static-fastopt-bundle.js shows esprima is used, but its js is not bundled.
What other steps are needed to add dependencies into a client-only web page?
A: As described in this part of the documentation, you have to use @JSImport in your facade definition:
@JSImport("esprima", JSImport.Namespace)
For reference, @JSName defines a facade bound to a global name, while @JSImport defines a facade bound to a required JavaScript module.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42021880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using the Live method to bind a function to dynamically created checkboxes How do I bind the following to all future instances of checkboxes that might be added to my page dynamically. I'm not sure how to use the Live() method to do this.
$('input:checkbox').imageTickBox({
tickedImage: "/Content/Img/checkbox_tick.png",
unTickedImage: "/Content/Img/checkbox_notick.png",
imageClass: "tickbox"
});
A: You cannot do this with .live() (or .delegate()). Those are for binding event handlers for events which may not yet exist.
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
The image tick box plugin you're using is not any sort of "event." You will have to explicitly call the initialization code (e.g. $('selector').imageTickBox(...)) whenever a new checkbox is added.
A: This is definitely a duplicate question: Please see
jquery live event for added dom elements
Event binding on dynamically created elements?
A: .live() is for listening to events and then detecting where those events originated from. Adding elements to the page doesn't trigger anything that .live() can listen to. You'll have to call your plug-in initialization whenever you are adding the checkbox to the page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5899126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to structure BEM modifiers with nested elements in SASS SASS + BEM is pretty much a match made in heaven most of the time, but a common struggle of mine is understand how to best define BEM modifiers on an element that affects it's child elements while using SASS parent selectors.
I have the following component defined in SASS using BEM style syntax:
.card {
background-color: #FFF;
&__value {
font-size: 2em;
color: #000;
}
}
This works well because of SASS's parent selector. It keeps relevant code organized and self-contained.
But when I need to add a modifier that alters a child element using a parent selector, the idea quickly falls apart:
.card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
&--big {
padding: 2.5em;
&__value { // Is this going to work?
font-size: 3em;
}
}
}
Nope. It generates this:
.card {
padding: 2em;
}
.card__value {
font-size: 1.5em;
color: #000;
}
.card--big {
padding: 2.5em;
}
.card--big__value { // Wrong
font-size: 3em;
}
It would make more sense to somehow get this selector:
.card--big .card__value {
font-size: 3em;
}
The reason for this, is so you can simply add a modifier to the top level element and have it affect any or all of the child elements.
I've tried a couple approaches:
Use two structures
.card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
}
.card--big {
padding: 2.5em;
&__value {
font-size: 3em;
}
}
This works (especially in this simplified demonstration) but in a more complicated set of components with many modifiers this can be a potential pain to maintain and keep bug free. Also, it would nice to continue to use SASS parent selectors if possible.
Use a variable for the element
.card {
$component: &; // Set the variable here
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
&--big {
padding: 2.5em;
#{$component}__value { // Use it here
font-size: 3em;
}
}
}
This works well. But it seems kind of silly to have to define the element as a variable. Maybe it's the only real way to do this... I'm not sure. Are there better options to how to structure this?
A: Why not just do this?
.card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
&--big {
padding: 2.5em;
}
&--big &__value {
font-size: 3em;
}
}
A: You can split up the modifiers in a different structure, but nested within the .card selector, like this:
.card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
&--big {
padding: 2.5em;
}
&--big &__value {
padding: 2.5em;
}
}
Which will in turn produce this:
.card {
padding: 2em;
}
.card__value {
font-size: 1.5em;
color: #000;
}
.card--big {
padding: 2.5em;
}
.card--big .card__value {
padding: 2.5em;
}
I think this is an almost perfect way, although its not perfectly nested
I hope this was a help!
A: I just found a much better way to achieve this with sass, by using a variable to store the value of the parent selector you can use it at any level of nesting!
For example here I am storing the .card selector in the $this variable, and reusing it like this #{$this}
So this code
.card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
$this: &;
&--big {
padding: 2.5em;
#{$this}__value {
font-size: 3em;
}
}
}
will compile to
.card {
padding: 2em;
}
.card__value {
font-size: 1.5em;
color: #000;
}
.card--big {
padding: 2.5em;
}
.card--big .card__value {
font-size: 3em;
}
This answer was inspired by this article on css-tricks. Thanks to Sergey Kovalenko
A: There is another pattern you could use here.
This will:
- separate actual card modifier from its elements' modifiers
- will keep the modified styles within the same elements' selector so you don't need to scroll your code up and down to see what is being modified
- will prevent more specific rules from appearing above less specific rules, if that's your thing
Here's an example:
// scss
.card {
$component: &;
padding: 2em;
&--big {
padding: 2.5em;
}
&__value {
font-size: 1.5em;
color: #000;
#{$component}--big & {
font-size: 3em;
}
}
}
/* css */
.card {
padding: 2em;
}
.card--big {
padding: 2.5em;
}
.card__value {
font-size: 1.5em;
color: #000;
}
.card--big .card__value {
font-size: 3em;
}
A: You can do this by adding ONE character, no variables or mixins are needed.
&--big { becomes &--big & {:
.card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
&--big & {
padding: 2.5em;
&__value { // Is this going to work? (yes!)
font-size: 3em;
}
}
}
A: Going through the same issue I've build a library called Superbem which is basically a set of SCSS mixins that help you write BEM declarative way. Take a look:
@include block(card) {
padding: 2em;
@include element(value) {
font-size: 1.5em;
color: #000;
}
@include modifier(big) {
padding: 2.5em;
@include element(value) {
font-size: 3em;
}
}
}
Gives you:
.card, .card--big {
padding: 2em;
}
.card__value {
font-size: 1.5em;
color: #000;
}
.card--big {
padding: 2.5em;
}
.card--big .card__value {
font-size: 3em;
}
Hope you'll find this useful!
A: Your solution looks quite fine but you may also try @at-root.
A: .card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
&--big {
padding: 2.5em;
&__value { // Is this going to work?
font-size: 3em;
}
}
}
You can achieve the result You wanted by the following :
.card {
padding: 2em;
&__value {
font-size: 1.5em;
color: #000;
}
&--big {
padding: 2.5em;
.card {
&__value { // this would work
font-size: 3em;
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44450387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How to using JPQL to join two tables I made employee table and position table.Every Employees have one position.I want join two table ,but I don't know how to write code.
Employee.java
@Table(name = "employees")
@NamedQueries({
@NamedQuery(name = "getAllEmployees", query = "SELECT e FROM Employee AS e ORDER BY e.emp_id DESC")
})
@Entity
public class Employee {
@Id
@Column(name = "emp_id", length = 8)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer emp_id;
@Column(name = "emp_name", length = 20, nullable = false)
private String emp_name;
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "position", joinColumns = {
@JoinColumn(name = "emp_id", referencedColumnName = "emp_id") }, inverseJoinColumns = {
@JoinColumn(name = "pos_id", referencedColumnName = "pos_id") })
private Position pos;
~setter/getter~
Position.java
@Table(name = "position")
@Entity
public class Position {
@Id
@Column(name = "pos_id")
private Integer pos_id;
@Column(name = "pos_name", length = 30, nullable = false)
private String pos_name;
@OneToOne(mappedBy = "pos")
private Employee employee;
~setter/getter~
A: Employee.java
@Entity
public class Employee {
@Id
@Column(name = "emp_id", length = 8)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer emp_id;
@Column(name = "emp_name", length = 20, nullable = false)
private String emp_name;
@ManyToOne
private Position position;
Position.java
@Entity
public class Position {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int pos_id;
@Column(name = "pos_name", length = 16)
private String pos_name;
@OneToMany(mappedBy = "position")
private List<Employee> employees;
Thank you.I can join two tables!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64410816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compatibility View and its importance I have just finished the layout for my website, and it is working perfectly fine in all browsers (Opera, Safari, Chrome, IE 7, 8, 9, 10 (both), and several others) - but this time around, the Compatibility View button in the address bar of IE 10 is appearing. This has not happened for a very long time and it's really annoying me.
I don't want the Compatibility View button to display at all. It sends a bad message to viewers/visitors. In this case, I have tested my whole site on different computers all running different browsers and different versions of browsers and I have not noticed a single problem.
Why is the Compatibility View button appearing if there are no issues?
Here's the problem, and like I said, everything works fine - except for when I turn ON Compatibility View in IE 10. When I turn it ON, the only things in my entire website I can see is my logo, and a little image in the top right corner of the page (but they're positioned exactly where I wanted them). What gives?
There's nothing wrong with the code - seriously. i've had it validated several times, all AJAX stuff works like a charm, and I really tried so hard to find a problem and I even intentionally tried to mess it up but it's working really well. The positioning of everything is spot on.
So what's the deal with this Compatibility View junk? Why is it there - on a website that does not have any issues? And, most importantly, is it important that I make sure my website works well while in Compatibility View even though it works perfectly when it's off and even though it works perfectly in all the major browsers - and then some?
A: First and foremost, you can force IE not to display the Compatibility View button simply by adding this to your page head:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
As for your other questions:
Why is the Compatibility View button appearing if there are no issues?
So what's the deal with this Compatibility View junk? Why is it there - on a website that does not have any issues?
It's there in case a site, typically one that was written many years ago, fails to work in a newer version of IE, to allow users to view or IE to display it in a legacy rendering mode where it will hopefully work better.
Additionally, it's there by default because legacy sites will not even have the meta tag above to begin with. In order for the button to display when viewing existing sites without having to update their code, it's only logical to make it an opt-out feature instead, by having the developer add it to new code to tell newer versions of IE to hide the button when it's not needed.
And, most importantly, is it important that I make sure my website works well while in Compatibility View even though it works perfectly when it's off and even though it works perfectly in all the major browsers - and then some?
Compatibility View is meant for websites that were specifically designed for legacy browsers, and as such, depend on legacy rendering quirks not present in more recent browsers which may cause "problems" in those more recent browsers.
Without seeing your site, we won't be able to determine why it works in IE7 and IE10 in IE7 mode but not Compatibility View, but if it works well in newer versions of IE, you do not need to ensure that it works well in Compatibility View. Using the meta tag above to hide the button when it's not necessary will suffice.
A: Can you provide us a link to your site? I always use
<!DOCTYPE html>
on the first line of the HTML document. This is a universal switch to the latest rendering mode in all modern browsers. Use BoltClock's solution to hide a compatible view button in IE's address bar. I would prefer a HTTP header rather than HTML meta tag, because the meta tag causes parser switch and reset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16666088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Make my jQuery accordion responsive I have created this jQuery accordion and want to make it responsive on smaller screens. I know there is a way to make this responsive using CSS media query but I am wondering if there is a better way of making it responsive using JS. I am also hoping that the tabs sit on top of each other on smaller screens. Can anyone please help me.
Also please feel free to suggest anything that could improve this code.
$(document).ready(function(){
var tabButton = ".allContainer .tabsList .tab-wrapper .tabButton";
var tabButtonCurrent = ".allContainer .tabsList .tab-wrapper > .curr";
var tabContent = ".allContainer .tabsList .tab-content .curr";
var tabContentParent = ".allContainer .tabsList .tab-content";
$(tabButton).on('click', function(){
$(tabButtonCurrent).removeClass('curr');
$(this).addClass('curr');
var panelId = $(this).attr('rel');
$(tabContent).hide(500, showClickedSlider);
function showClickedSlider(){
$(this).removeClass('curr');
$(panelId).show(500, function(){
$(this).addClass('curr');
});
}
});
});
.tabList {
width:100%;
}
.tab-wrapper {
float:left;
margin-right:10px;
background-color:olivedrab;
height:200px;
}
.tabButton {
float:left;
margin-right:1%;
min-width: 50px;
height:200px;
background-color:orange;
cursor:pointer;
}
.tab-content {
overflow:hidden;
float:left;
width:70%;
}
.tab-content > div {
display: none;
width:350px;
}
.tab-content .curr {
display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="allContainer">
<div class="tabsList">
<div class="tab-wrapper">
<div class="tabButton curr" data-u="#tab01" rel="#tab01">tab1</div>
<div class="tab-content">
<div class="curr" id="tab01">content 01</div>
</div>
</div>
<div class="tab-wrapper">
<div class="tabButton" rel="#tab02">tab2</div>
<div class="tab-content">
<div id="tab02">content 02</div>
</div>
</div>
<div class="tab-wrapper">
<div class="tabButton" rel="#tab03">tab3</div>
<div class="tab-content">
<div id="tab03">content 03</div>
</div>
</div>
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48819500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I filter based on dict contents in a DictField on a model using the Django-MongoDB Engine? Given the models:
class Post(models.Model):
datas = ListField(EmbeddedModelField('Comment'),blank=True)
data = DictField()
class Comment(models.Model):
name = models.CharField(max_length=255)
date = DateField(blank=True, null=True)
If we set the data variable to:
{'key':'value'}
Is there a way to filter for Posts with key=='value'?
As an alternative, what about with embedded documents? Is there a way to filter for a Post that has an author with the name 'Ralph'?
It seems like this must be possible, or else this ORM is far too limiting to be useful, which seems unlikely.
A: I recommend trying it out for yourself, but the comment in the code
#TODO/XXX: Remove as_lookup_value() once we have a cleaner solution
# for dot-notation queries
suggests that it does. I've ever only really used lists.
A: You can filter for a Post that has an author named "Ralph" using raw queries:
Post.objects.raw_query({'author.name': "Ralph"})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9629661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Double quotes in a string C# I'm trying to read through a file and look for this tag
,<table name="File">,
i've read a bunch and everyone tells me to use @""" or \" to accept the double quotes in the middle of the string, but what it does is turns my string into this. <table name=\"File\"> and it still doesn't work because thats not how it is in the file. examples:
string tblName = " <table name="+@"""File"""+">";
string tblName = " <table name=\"File\">";
Nothing seems to work. It just addes the \ into the string and i can't replace it because it removes the quotes. Any suggestions?
Thanks
string tblName = " <table name="+@"""File"""+">";
try
{
// Only get files that begin with the letter "c."
string[] dirs = Directory.GetFiles(@"C:\Users\dylan.stewart\Desktop\Testing\", "*.ism");
//Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
foreach (string dir in dirs)
{
foreach( string line in File.ReadLines(dir))
if(line.Contains(tblName))
{
Console.WriteLine(dir);
}
//Console.WriteLine(dir);
}
}
A: The above methods for adding " into a string are correct. The issue with my OP is i was searching for a specific amount of white space before the tag. I removed the spaces and used the mentioned methods and it is now working properly. Thanks for the help!
A: string tblName = "<table name=" + '"' + "File" + '"' + ">";
should work since the plus sign concatenate
A: It should be either
string tblName = @" <table name=""File"">";
or
string tblName = " <table name=\"File\">";
No need for concatenation. Also what do you mean "it still doesn't work"? Just try Console.Write() and you'll see it ok. If you mean the backslashes are visible while inspecting in debugger then it's supposed to be that way
B
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34748425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Looping over with FileReader only displays last image in grid of divs I am trying to create a HTML form that allows the user to upload up to 5 images. After the user selects the images (from the filesystem using <input multiple>) I'd like to display them in 5 divs (ID'ed from #contactImage0 to #contactImage4).
To achieve this I loop over the selected images using vanilla JS and set them as background-image in the corresponding div. The problem is that only the last image in a selection actually shows up. All other divs stay empty.
After debugging a bit I found out that for all but the last image reader.result returns "" but I can't figure out why as the "image" variable I pass to reader.readAsDataURL() seems to be valid.
Why is that and how do I fix it?
HTML:
<div id="contactImage0" class="imagePreview"></div>
<div id="contactImage1" class="imagePreview"></div>
<div id="contactImage2" class="imagePreview"></div>
<div id="contactImage3" class="imagePreview"></div>
<div id="contactImage4" class="imagePreview"></div>
<input id="upload" type="file" onchange="LoadImage(this)" name="image" accept="image/*" multiple>
JavaScript:
function LoadImage(input){
if (input.files.length > 5){
alert("You may only select a maximum of 5 images!");
// TODO: Remove selected images
return;
}
var i;
for (i = 0; i < input.files.length; i++){
var image = input.files[i]
var imageDiv = 'contactImage' + i.toString();
var element = document.getElementById(imageDiv);
var reader = new FileReader();
reader.onloadend = function(){
element.style.backgroundImage = "url(" + reader.result + ")"; // <-- RETURNS EMPTY STRING (EXCEPT FOR LAST IMAGE)
}
if(image){
reader.readAsDataURL(image);
}else{
}
}
}
CSS (Shouldn't be the cause of the problem but you never know):
.imagePreview{
margin: .5em;
display: inline-block;
width: calc(100% - 1em);
height: 80px;
background-color: #fff;
background-image:url('');
background-size:cover;
background-position: center;
}
A: See https://dzone.com/articles/why-does-javascript-loop-only-use-last-value
Solution 1 - Creating a new function setElementBackground
for (i = 0; i < input.files.length; i++) {
setElementBackground(input.files[i], i);
}
function setElementBackground(file, i) {
var image = file;
var imageDiv = "contactImage" + i.toString();
var element = document.getElementById(imageDiv);
var reader = new FileReader();
reader.onloadend = function() {
element.style.backgroundImage = "url(" + reader.result + ")";
};
if (image) {
reader.readAsDataURL(image);
}
}
Solution 2 - Using Another Closure inside for loop
for (i = 0; i < input.files.length; i++) {
(function() {
var count = i;
var image = input.files[count];
var imageDiv = "contactImage" + count.toString();
var element = document.getElementById(imageDiv);
var reader = new FileReader();
reader.onloadend = function() {
element.style.backgroundImage = "url(" + reader.result + ")";
};
if (image) {
reader.readAsDataURL(image);
}
})();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57476322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MinGW DLL project compatability with linux I've recently created a DLL project using the MinGW (4.8.1) compiler through the CodeBlocks IDE, and in the debugging output folder I have: my ".dll" ("AttribRdr.dll" in this case) file with an Export Definition File and finally a ".a" file ("libAttribRdr.a" in this case).
According to my knowledge, the programs built for Linux/Unix based operating systems use libraries in the ".a" format. My question is: can I use that ".a" file, generated by MinGW on my Windows system, on my Linux system without having to change the library's code or to re-compile? Obiously I would have to change the code of the program using the ".a" library, but otherwise can I use that ".a" file as-is?
I'm asking this because I know MinGW aims to be a "cross-platform" C++ compiler and if I can use the generated ".a" file on Linux systems without having to re-compile it would reduce my workload drastically.
A: To use libraries (or executables) built on Windows in Linux environment you need to cross-compile your code. GCC is capable of cross compilation - so you can research the topic, there is plenty of information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33962765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript Download remote picture in background In my project, I need to implement an Image viewer to display pictures stored on the server on an HTML Page (thumbnail first and on click on the thumbnail display the full screen picture).
Currently, the server is providing me an URL (ex: https://testsrv/getImage?id=0) which is sending back the picture to the browser (Servlet sending a File to an OutputStream). For the moment, I'm just adding an a href hyperlink to download the picture that's ok.
but If I want to improve this, I would need to download the pictures (thumbnail and full size picture) in background while opening the html page to show the thumbnail on the screen.
I assume I would need to download the picture by using AJAX in background and store the pictures in a local temporary folder but if you have some examples to provide me that would be very helpful...
EDIT1:
I finally found a way thanks to the comments based on the onload service:
var image = document.images[0];
var downloadingImage = new Image();
downloadingImage.onload = function(){
image.src = this.src;
document.getElementById("img_ref").setAttribute('href', "../../../testSRV/GetPhoto?id="+id_attach);
console.log('preloaded');
};
downloadingImage.src = "../../../testSRV/GetPhoto?id="+id_attach;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51521535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Turn on All ec2(+ future created ec2) 'termination protection' Using Lambda Im trying to turn on 'termination protection' for all ec2.
(termination protection doesn't work to spot instance, so i want to add skip condition not to make an error for spot instance.)
I saw a code like below, however the code doesn't work.
import json
import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
client = boto3.client('ec2', region_name=region)
conn = boto3.resource('ec2',region_name=region)
instances = conn.instances.filter()
for instance in instances:
if instance.state["Name"] == "running":
#print instance.id # , instance.instance_type, region)
terminate_protection=client.describe_instance_attribute(InstanceId =instance.id,Attribute = 'disableApiTermination')
protection_value=(terminate_protection['DisableApiTermination']['Value'])
if protection_value == False:
client.modify_instance_attribute(InstanceId=instance.id,Attribute="disableApiTermination",Value= "True" )
Summary,,,
I want to turn on 'Termination protection' for all EC2 which is running(not spot instance).
The region should be ap-northeast-2.
Could you help me to fix this code to running appropriatly?
A: if you want to skip the spot instance all you need to do this is figure out which one is spot instance.
You need to use describe_instances api and then using if-else condition, request_id is empty its a spot instance, if not then its not a spot instance
import boto3
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) #add filter of your own choice
for instance in instances:
if instance.spot_instance_request_id:
# logic to skip termination ( spot instance )
else:
# logic to terminate ( not spot instance )
You can refer a similar question on this -> https://stackoverflow.com/a/45604396/13126651
docs for describe_instances
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73481175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using `if-case` format in boolean assignment in Swift? If I have the following enum defined:
enum CardRank {
case number(Int)
case jack
case queen
case king
case ace
}
I know I can use an if-let to check if it's a number:
let cardRank = CardRank.number(5)
if case .number = cardRank {
// is a number
} else {
// something else
}
Instead of using an if statement, though, I want to assign the boolean result of "is this a number" to a variable.
E.g. something like this:
let isNumber = (case .number = cardRank)
However, this gives me the compiler error:
error: expected expression in list of expressions
let isNumber = (case .number = cardRank)
^
Is there a similar 1-line syntax to get this kind of assignment to work?
The closest I got was this, but it's pretty messy:
let isNumber: Bool = { if case .number = cardRank { return true } else { return false } }()
I know I can implement the Equatable protocol on my enum, and then do the following:
let isAce = cardRank == .ace
But I'm looking for a solution that doesn't require needing to conform to the Equatable protocol.
A: Add it as a property on the enum:
extension CardRank {
var isNumber: Bool {
switch self {
case .number: return true
default: return false
}
}
}
let isNumber = cardRank.isNumber
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46005134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What is the best way to implement this SQL query? I have a PRODUCTS table, and each product can have multiple attributes so I have an ATTRIBUTES table, and another table called ATTRIBPRODUCTS which sits in the middle. The attributes are grouped into classes (type, brand, material, colour, etc), so people might want a product of a particular type, from a certain brand.
PRODUCTS
product_id
product_name
ATTRIBUTES
attribute_id
attribute_name
attribute_class
ATTRIBPRODUCTS
attribute_id
product_id
When someone is looking for a product they can select one or many of the attributes. The problem I'm having is returning a single product that has multiple attributes. This should be really simple I know but SQL really isn't my thing and past a certain point I get a bit lost in the logic. The problem is I'm trying to check each attribute class separately so I want to end up with something like:
SELECT DISTINCT products.product_id
FROM attribproducts
INNER JOIN products ON attribproducts.product_id = products.product_id
WHERE (attribproducts.attribute_id IN (9,10,11)
AND attribproducts.attribute_id IN (60,61))
I've used IN to separate the blocks of attributes of different classes, so I end up with the products which are of certain types, but also of certain brands. From the results I've had it seems to be that AND between the IN statements that's causing the problem.
Can anyone help a little? I don't have the luxury of completely refactoring the database unfortunately, there is a lot more to it than this bit, so any suggestions how to work with what I have will be gratefully received.
A: Take a look at the answers to the question SQL: Many-To-Many table AND query. It's the exact same problem. Cletus gave there 2 possible solutions, none of which very trivial (but then again, there simply is no trivial solution).
A: SELECT DISTINCT products.product_id
FROM products p
INNER JOIN attribproducts ptype on p.product_id = ptype.product_id
INNER JOIN attribproducts pbrand on p.product_id = pbrand.product_id
WHERE ptype.attribute_id IN (9,10,11)
AND pbrand.attribute_id IN (60,61)
A: Try this:
select * from products p, attribproducts a1, attribproducts a2
where p.product_id = a1.product_id
and p.product_id = a2.product_id
and a1.attribute_id in (9,10,11)
and a2.attribute_id in (60,61);
A: This will return no rows because you're only counting rows that have a number that's (either 9, 10, 11) AND (either 60, 61).
Because those sets don't intersect, you'll get no rows.
If you use OR instead, it'll give products with attributes that are in the set 9, 10, 11, 60, 61, which isn't what you want either, although you'll then get multiple rows for each product.
You could use that select as an subquery in a GROUP BY statement, grouping by the quantity of products, and order that grouping by the number of shared attributes. That will give you the highest matches first.
Alternatively (as another answer shows), you could join with a new copy of the table for each attribute set, giving you only those products that match all attribute sets.
A: It sounds like you have a data schema that is GREAT for storage but terrible for selecting/reporting. When you have a data structure of OBJECT, ATTRIBUTE, OBJECT-ATTRIBUTE and OBJECT-ATTRIBUTE-VALUE you can store many objects with many different attributes per object. This is sometime referred to as "Vertical Storage".
However, when you want to retrieve a list of objects with all of their attributes values, it is an variable number of joins you have to make. It is much easier to retrieve data when it is stored horizonatally (Defined columns of data)
I have run into this scenario several times. Since you cannot change the existing data structure. My suggest would be to write a "layer" of tables on top. Dynamically create a table for each object/product you have. Then dynamically create static columns in those new tables for each attribute. Pretty much you need to "flatten" your vertically stored attribute/values into static columns. Convert from a vertical architecture into a horizontal ones.
Use the "flattened" tables for reporting, and use the vertical tables for storage.
If you need sample code or more details, just ask me.
I hope this is clear. I have not had much coffee yet :)
Thanks,
- Mark
A: You can use multiple inner joins -- I think this would work:
select distinct product_id
from products p
inner join attribproducts a1 on a1.product_id=p.product_id
inner join attribproducts a2 on a1.product_id=p.product_id
where a1.attribute_id in (9,10,11)
and a2.attribute_id in (60,61)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1057944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Send requests to a website from an iOS app I was wondering if there's a way to send requests to a website, directly from an iOS app, for example, I type my username and password in two inputbox and then I just tap a "login" button on the iPhone, sending the credentials to a website. Can it be done?
A: You can send requests to a website from an iOS application. You're probably looking to perform a HTTP action.
There is a great guide by the Spring development team which guides you through the process of using RESTful services on iOS, this includes Posting data to a web service.
RESTful services also allow you the create, retrieve, update and delete data from a webservice too using a variety of HTTP calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30385208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-11"
} |
Q: Laravel - Redirect user after login to specific page I want to redirect the user to the edit.blade page when they login for the first time. for this I made this code, but it doesn't work and i have no idea what the problem is. Can someone help me.
this is the code that I have now:
// This section is the only change
if ($this->guard()->validate($this->credentials($request))) {
$user = $this->guard()->getLastAttempted();
// Make sure the user is active
if ($user->verified && $this->attemptLogin($request)) {
if ($user->first_time_login == true || $user->first_time_login == 1) {
$this->redirectTo = '/users/edit';
$user->first_time_login = false;
$user->save();
}
return $this->sendLoginResponse($request);
}
}
everything works except this line:
if ($user->first_time_login == true || $user->first_time_login == 1) {
$this->redirectTo = '/users/edit';
}
A: You could do this with the redirectTo property or the authenticated method:
redirectTo property: docs
If the redirect path needs custom generation logic you may define a
redirectTo method instead of a redirectTo property:
protected function redirectTo()
{
$user = Auth::user();
if($user->first_time_login){
$user->first_time_login = false;
$user->save();
return '/users/edit';
}else{
return '/home';
}
}
authenticated method:
protected function authenticated(Request $request, $user)
{
if ($user->first_time_login) {
$url = '/users/edit';
$user->first_time_login = false;
$user->save();
} else {
$url = $this->redirectTo;
}
return redirect($url);
}
A: I have found the problem, i had to add return redirect()->to('/users/edit'); on the bottom of the auth function that $this->redirrectTo is the default if the user has not already navigated to a different authed route.
My code now looks like this:
if ($user->first_time_login == true || $user->first_time_login == 1) {
$this->redirectTo = '/users/edit';
$user->first_time_login = false;
$user->save();
return redirect()->to('/users/edit');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52970923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: String formula for linear models I'm trying to create a string formula with the independent variables that are significant within my linear model, though I'm finding it difficult trying to include the + at the end of each variable.
I have tried:
as.formula(sprintf("encounter ~ %s",
names(tbest$model)[-1]))
However, this only gives the first variable:
encounter ~ open_shrubland
Warning message:
Using formula(x) is deprecated when x is a character vector of length > 1.
Consider formula(paste(x, collapse = " ")) instead.
How would I include all of them such that: encounter ~ X1 + X2 + X3 ..., also, can this be made functional, such that if I wanted to remove a variable, I would only have to do my.formula[-3] to remove it?
list of variable names:
c("open_shrubland", "Appalachian_Mountains", "Boreal_Hardwood_Transition",
"Central_Hardwoods", "Piedmont", "wetland", "Badlands_And_Prairies",
"Peninsular_Florida", "Central_Mixed_Grass_Prairie", "water",
"New_England_Mid_Atlantic_Coast", "grassland", "mixed_forest",
"cropland", "Oaks_And_Prairies", "Eastern_Tallgrass_Prairie",
"evergreen_needleleaf", "year", "pland_change", "evergreen_broadleaf",
"Southeastern_Coastal_Plain", "Prairie_Potholes", "Shortgrass_Prairie",
"urban", "Prairie_Hardwood_Transition", "Lower_Great_Lakes_St.Lawrence_Plain",
"mosaic", "Mississippi_Alluvial_Valley", "deciduous_broadleaf",
"deciduous_needleleaf", "barren")
A: Using reformulate will be helpful.
reformulate(names(tbest$model)[-1], 'encounter')
If the list of variable names are in x :
reformulate(x, 'encounter')
encounter ~ open_shrubland + Appalachian_Mountains + Boreal_Hardwood_Transition +
Central_Hardwoods + Piedmont + wetland + Badlands_And_Prairies +
Peninsular_Florida + Central_Mixed_Grass_Prairie + water +
New_England_Mid_Atlantic_Coast + grassland + mixed_forest +
cropland + Oaks_And_Prairies + Eastern_Tallgrass_Prairie +
evergreen_needleleaf + year + pland_change + evergreen_broadleaf +
Southeastern_Coastal_Plain + Prairie_Potholes + Shortgrass_Prairie +
urban + Prairie_Hardwood_Transition + Lower_Great_Lakes_St.Lawrence_Plain +
mosaic + Mississippi_Alluvial_Valley + deciduous_broadleaf +
deciduous_needleleaf + barren
A: We can create a formula with paste
as.formula(paste('encounter~', paste(names(tbtest$model)[-1], collapse = "+")))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66731481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VBScript, purpose of colon? What is the purpose of the colon?
e. g.:
Dim objConn : Set objConn = OpenConnection()`
Is the colon used to combine the two statements into one line? I just want to be sure.
A: Yes this is correct. In VB style languages, including VBScript, the colon is an end of statement token. It allows you to place several statements on the same line.
A: What you have stated is correct. The purpose of the colon is to combine 2 otherwise separate lines into a single line. It works on most statements, but not all.
A: Yes, the code would work exactly the same on two lines; the colon's just a statement separator.
A: You can put two (or more) lines of code in one line. It's most often used, as in your example, to declare and set a variable on one line.
Think of it like a semicolon in every other language, except optional.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1144914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: jasmine-expect cannot find jest, jasmine v2.x, or jasmine v1.x I'm trying unit test with jasmine-expect. However I keep getting the error:
jasmine-expect cannot find jest, jasmine v2.x, or jasmine v1.x
I have installed the latest version of jasmine. What am I missing?
package.json
{
"name": "js",
"version": "1.0.0",
"description": "",
"main": "Person.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"add-matchers": "^0.4.0",
"babel-cli": "^6.22.2",
"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0",
"jasmine": "^2.5.3",
"jasmine-expect": "^3.6.0",
"jest": "^18.1.0",
"webpack": "^2.2.1"
},
"dependencies": {
"deep-freeze": "0.0.1"
}
}
My Code:
'use strict';
import expect from 'jasmine-expect';
console.log('It is working...');
Error Message:
A: I have switched to the mjackson expect library. It seems to be working fine. Thanks.
A: Please see https://github.com/JamieMason/Jasmine-Matchers/tree/master/examples/jest for a working example of jasmine-expect with jest, thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42155942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 'failed to lookup address information' error is displayed on executing selenium test using Gecko driver on Mac OS I am having tuff time on executing Selenium test in Mac OS using Gecko driver. I am using Firefox 56.
Here is the code which i have used to initialize web driver.
System.setProperty("webdriver.gecko.driver", "/Users/<username>/Documents/Tools/geckodriver");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
Now, when i execute a test, it seems Gecko driver is initialized but below mentioned error is displayed and the browser is not being initialized.
1507662170977 geckodriver INFO geckodriver 0.19.0
1507662170983 geckodriver INFO Listening on 127.0.0.1:42748
FAILED CONFIGURATION: @BeforeClass initializeDriver
org.openqa.selenium.WebDriverException: failed to lookup address information: nodename nor servname provided, or not known
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T15:28:36.4Z'
System info: host: '<username>s-MacBook-Pro.local', ip: '192.168.1.2', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_144'
Driver info: driver.version: FirefoxDriver
remote stacktrace: stack backtrace:
0: 0x10d96ca8e - backtrace::backtrace::trace::h69682bcb53decaf6
1: 0x10d96cacc - backtrace::capture::Backtrace::new::hdc9d731a957304a6
2: 0x10d8ce8e3 - webdriver::error::WebDriverError::new::h4c6ae7c4aac049c6
3: 0x10d8cf352 - _$LT$webdriver..error..WebDriverError$u20$as$u20$core..convert..From$LT$std..io..error..Error$GT$$GT$::from::ha068e680ab4e1954
4: 0x10d8a221e - geckodriver::marionette::MarionetteHandler::create_connection::hc09196342b760e35
5: 0x10d8847d4 - _$LT$webdriver..server..Dispatcher$LT$T$C$$u20$U$GT$$GT$::run::hfda25a6dc0b512aa
6: 0x10d85c645 - std::sys_common::backtrace::__rust_begin_short_backtrace::h95009c1d3a320838
7: 0x10d86411d - std::panicking::try::do_call::h8c5f07f1fc714fb2
8: 0x10da1d9cc - __rust_maybe_catch_panic
9: 0x10d879f55 - _$LT$F$u20$as$u20$alloc..boxed..FnBox$LT$A$GT$$GT$::call_box::h6a96e09ff4d37bff
10: 0x10da19c3b - std::sys::imp::thread::Thread::new::thread_start::h823686b907c11c46
11: 0x7fffdf79f93a - _pthread_body
12: 0x7fffdf79f886 - _pthread_start
Your solution would be appreciated.
A: Apparently there is an issue with the JDK and OSX where the hostname does not recognize localhost.
The solution is to add localhost to /etc/hosts
A: You need to pass the capabilities to the driver:
WebDriver driver = new FirefoxDriver(capabilities);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46674223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TensorFlow Probability: how to do sample weighting with log_prob loss function? I'm using TensorFlow probability to train a model whose output is a tfp.distributions.Independent object for probabilistic regression. My problem is that I'm unsure how to implement sample weighting in the negative log likelihood (NLL) loss function.
I have the following loss function which I believe does not use the sample_weight third argument:
class NLL(tf.keras.losses.Loss):
''' Custom keras loss/metric for negative log likelihood '''
def __call__(self, y_true, y_pred, sample_weight=None):
return -y_pred.log_prob(y_true)
With standard TensorFlow loss functions and a dataset containing (X, y, sample_weight) tuples, the use of sample_weight in the loss reductions summations is handled under the hood. How can I make the sum in y_pred.log_prob use the weights in the sample_weight tensor?
A: I found a solution to my problem as posted in this GitHub issue.
My problem was caused by the fact that my model outputs a tfp.Independent distribution, which means the log_prob is returned as a scalar sum over individual log_probs for each element of the tensor. This prevents weighting individual elements of the loss function. You can get the underlying tensor of log_prob values by accessing the .distribution attribute of the tfp.Independent object - this underlying distribution object treats each element of the loss as an independent random variable, rather than a single random variable with multiple values. By writing a loss function that inherits from tf.keras.losses.Loss, the resulting weighted tensor is implicitly reduced, returning the weighted mean of log_prob values rather than the sum, e.g.:
class NLL(tf.keras.losses.Loss):
''' Custom keras loss/metric for weighted negative log likelihood '''
def __call__(self, y_true, y_pred, sample_weight=None):
# This tensor is implicitly reduced by TensorFlow
# by taking the mean over all weighted elements
return -y_pred.distribution.log_prob(y_true) * sample_weight
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69886735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: BoxFit.cover does not work with CachedNetworkImage plus PhotoView In this scenario I can not make to work the fit property with BoxFit.cover.
There is always borders on screen. How can I do it?
Scaffold(
appBar: AppBar(),
body: CachedNetworkImage(
height: double.infinity,
width: double.infinity,
fit: BoxFit.cover, // does not work
imageUrl: _imageUrl,
imageBuilder: (context, imageProvider) => PhotoView(
imageProvider: imageProvider,
),
),
);
A: Container(
child: CachedNetworkImage(
imageUrl: _imageUrl,
imageBuilder: (context, imageProvider)=>PhotoView(
minScale: 1.0,
imageProvider: imageProvider,
),
),
),
A: For the future searchers, there is an another solution which seems perfectly fits the desired behaviour.
https://stackoverflow.com/a/58200356/5829191
A: This work for me. Since I have a Container with the same borderRadius as the Catched Image. Without the BoxDecoration it failed med too!
Container( decoration: BoxDecoration(borderRadius:
BorderRadius.circular(10),),child:CachedNetworkImage(imageUrl: ("UrlToImage"),imageBuilder: (context, imageProvider) => Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),image: DecorationImage(image: imageProvider,
fit: BoxFit.cover,
)),),placeholder: (context, url) => CircularProgressIndicator(),errorWidget: (context, url, error) => Image.asset("PathToImage")
),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64935572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Awful looking custom transition I have a problem with custom transition between controllers. I have two view controllers. First is a table view controller and initiate controller is the second one. It has a button on it's top left corner which, when it is pressed, first navigation controller is called. There should be slide animation, but from left to right, not from right to left. I made my own transition but when the button is pressed, transition looks very awful. Transition code:
CATransition *transition = [CATransition animation];
transition.duration = 0.45;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
transition.type = kCATransitionFromLeft;
[transition setType:kCATransitionPush];
transition.subtype = kCATransitionFromLeft;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[self.navigationController pushViewController:controller animated:NO];
This is a screenshot, how the transition looks like:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34889531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: put part of the method which returns null in other method The method storeData works fine, but I am trying to put a part of my method in another method samePosition to minimize it, but I have the problem that some of its part returns null.
I put it in the other method names samePosition with return values Integer but then I received this error message:
This method must return a result of type Integer
How can I solve this problem?
storeData method before minimization:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response storeData(Data data) {
String macD = data.getMac();
int routeD = data.getRoute();
float latD = data.getLatitude();
float longD = data.getLongitude();
// Add the lat and Long to the ArrayList.
latLongList.add(new LatLong(latD, longD));
////////////I want to put this part in seperate method "samePosition" //////////////
int size = latLongList.size();
if (size > 1) {
ArrayList<Double> array = new ArrayList<>();
for (int i = 0; i < latLongList.size() - 1; i++) {
LatLong last = latLongList.get(latLongList.size() - 1);
double distance = haversineDistance(latLongList.get(i), last);
array.add(distance);
}
ArrayList<Double> distanceRange = new ArrayList<>();
for (int j = 0; j < array.size(); j++) {
// Store request in the circumcircle of 4 meter into ArrayList.
if (array.get(j) < 4) {
distanceRange.add(array.get(j));
}
}
if (distanceRange.size() == 0) {
processData(macD, routeD, latD, longD);
} else {
return null;
}
} else {
processData(macD, routeD, latD, longD);
}
//////////////////////until here/////////////////////////
return Response.status(201).build();
}
Edit:
storeData:
public Response storeData(Data data) {
String macD = data.getMac();
int routeD = data.getRoute();
float latD = data.getLatitude();
float longD = data.getLongitude();
// Add the lat and Long to the ArrayList.
latLongList.add(new LatLong(latD, longD));
System.out.println("latLondList size: " + latLongList.size());
int valueReturned = samePosition(macD, routeD, latD, longD);
if (valueReturned == -1) {
return null;
} else {
return Response.status(201).build();
}
}
samePosition method:
private int samePosition(String macD, int routeD, float latD, float longD) {
int size = latLongList.size();
if (size > 1) {
ArrayList<Double> array = new ArrayList<>();
for (int i = 0; i < latLongList.size() - 1; i++) {
LatLong last = latLongList.get(latLongList.size() - 1);
double distance = haversineDistance(latLongList.get(i), last);
array.add(distance);
}
ArrayList<Double> distanceRange = new ArrayList<>();
for (int j = 0; j < array.size(); j++) {
// Store request in the circumcircle of 4 meter into ArrayList.
if (array.get(j) < 4) {
distanceRange.add(array.get(j));
}
}
if (distanceRange.size() == 0) {
processData(macD, routeD, latD, longD);
} else {
return -1;
}
} else {
processData(macD, routeD, latD, longD);
}
}
A: Instead of returning null you could return -1 and then check for the value you return being -1.
if (valueReturned == -1) {
return null;
} else {
//continue with method
}
The samePosition() method should return always an integer:
private int samePosition(String macD, int routeD, float latD, float longD) {
int size = latLongList.size();
if (size > 1) {
ArrayList<Double> array = new ArrayList<>();
for (int i = 0; i < latLongList.size() - 1; i++) {
LatLong last = latLongList.get(latLongList.size() - 1);
double distance = haversineDistance(latLongList.get(i), last);
array.add(distance);
}
ArrayList<Double> distanceRange = new ArrayList<>();
for (int j = 0; j < array.size(); j++) {
// Store request in the circumcircle of 4 meter into ArrayList.
if (array.get(j) < 4) {
distanceRange.add(array.get(j));
}
}
if (distanceRange.size() == 0) {
processData(macD, routeD, latD, longD);
return 0;
} else {
return -1;
}
} else {
processData(macD, routeD, latD, longD);
return 0;
}
}
A: Check the below and modify as needed. Instead of returning 201 as response in all the cases I preferred to return different status code based on whether you processed the data or not.
In your earlier code, the code segment you are trying to extract is returning null from one point and nothing from last else where you are calling processData(..).
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response storeData(Data data) {
..
int status = samePosition(..);
return Response.status(status).build();
}
private int samePosition(..) {
int status = 201;
if() {
...
if (distanceRange.size() == 0) {
processData(macD, routeD, latD, longD);
} else {
status = <Preferred HTTP status code to return for not processing>;
}
} else {
}
return status;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30047866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UICollectionViewCompositionLayout with auto-sizing cells containing a fixed ratio UIImageView The goal is to configure a UICollectionViewCompositionalLayout for full-width cells which contain a fixed-aspect ratio UIImageView (plus some other views underneath including variable height UILabels and UIStackViews) and have the cells properly auto-size. My naive attempt doesn't work and I can't figure out why. The simple case I present here gives me a bunch of constraint errors at runtime.
I cribbed the code from this answer, but it looks pretty straightforward:
override func viewDidLoad() {
super.viewDidLoad()
let size = NSCollectionLayoutSize(
widthDimension: NSCollectionLayoutDimension.fractionalWidth(1),
heightDimension: NSCollectionLayoutDimension.estimated(100)
)
let item = NSCollectionLayoutItem(layoutSize: size)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 10
let layout = UICollectionViewCompositionalLayout(section: section)
collectionView.collectionViewLayout = layout
}
And the constraints look like this:
And as soon as I scroll, I get these constraint errors:
2021-01-21 20:29:18.311491+0100 CompositionalLayoutDynamicHeight[96399:2597528] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x6000020a82d0 UIImageView:0x138818600.width == 1.33333*UIImageView:0x138818600.height (active)>",
"<NSLayoutConstraint:0x6000020a8460 V:|-(0)-[UIImageView:0x138818600] (active, names: '|':UIView:0x13881c4d0 )>",
"<NSLayoutConstraint:0x6000020a84b0 H:[UIImageView:0x138818600]-(0)-| (active, names: '|':UIView:0x13881c4d0 )>",
"<NSLayoutConstraint:0x6000020a8500 V:[UIImageView:0x138818600]-(0)-| (active, names: '|':UIView:0x13881c4d0 )>",
"<NSLayoutConstraint:0x6000020a8550 H:|-(0)-[UIImageView:0x138818600] (active, names: '|':UIView:0x13881c4d0 )>",
"<NSLayoutConstraint:0x6000020a85a0 'UIIBSystemGenerated' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.leading == UIView:0x13881c4d0.leading (active)>",
"<NSLayoutConstraint:0x6000020a85f0 'UIIBSystemGenerated' H:[UIView:0x13881c4d0]-(0)-| (active, names: '|':CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280 )>",
"<NSLayoutConstraint:0x6000020a8640 'UIIBSystemGenerated' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.top == UIView:0x13881c4d0.top (active)>",
"<NSLayoutConstraint:0x6000020a8690 'UIIBSystemGenerated' V:[UIView:0x13881c4d0]-(0)-| (active, names: '|':CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280 )>",
"<NSLayoutConstraint:0x6000020a60d0 'UIView-Encapsulated-Layout-Height' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.height == 292.667 (active)>",
"<NSLayoutConstraint:0x6000020a6120 'UIView-Encapsulated-Layout-Width' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.width == 390 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000020a82d0 UIImageView:0x138818600.width == 1.33333*UIImageView:0x138818600.height (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
It seems that AutoLayout is creating that UIView-Encapsulated-Layout-Height constraint which is conflicting with the aspect ratio constraint—but why isn't it just resizing to fit it?
A: Auto-layout makes multiple "passes" when laying out the UI elements for Collection views (and Table views).
Frequently, particularly when using variable-sized cell content, auto-layout will throw warnings as it walks its way through the constraints.
Probably the easiest way to get rid of that warning is to give your Aspect Ratio constraint a Priority of less-than Required.
If you set it to Default High (750), that tells auto-layout it's allowed to "break" it without throwing the warning (but it will still be applied).
A: I had the same issue on a horizontal slider with dynamic item widths. I found the solution in my case which looks like a bug to me.
There are two functions to create a NSCollectionLayoutGroup. Using the other one fixed it for me.
This breaks my constraints:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)
This doesnt:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitems: [item])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65835209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: has anyone undergone certification of PCI-DSS using general purpose HSM (and not payshield)? can we utilise a general purpose HSM for EMV related work ? like ARQC/ARPC ? PCI guidelines do not specifically prohibit general purpose HSM from being used. There are certain constraints (e.g. disallow trnslation of ISO Type 0 to Type 1), etc.
But im generally curious - has anyone passed certification of a EMV switch using a general purpose HSM ?
Here's why I think it is possible:
ISO 9564 and TR-31 standards mandate that a few common things like
b) It must prevent the determination of key length for variable length
keys.
c) It must ensure that the key can only be used for a specific
algorithm (such as TDES or AES, but not both).
d) It must ensure a modified key or key block can be rejected prior to use, regardless of the utility of the key after modification. Modification includes changing any bits of the key, as well as the reordering or manipulation of individual single DES keys within a TDES key block
In forthcoming TR-31 regulations, I see that AWS KMS is compliant at the "at-rest integrity checks" using stuff like EncryptionContext and Policy Constraints
so im generally wondering what prevents us from using KMS for this purpose ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72883557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Performing a WHERE - IN query in CouchDB I would like to query for a list of particular documents with one call to CouchDB.
With SQL I would do something like
SELECT *
FROM database.table
WHERE database.table.id
IN (2,4,56);
What is a recipe for doing this in CouchDB by either _id or another field?
A: You need to use views keys query parameter to get records with keys in specified set.
function(doc){
emit(doc.table.id, null);
}
And then
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]
To retrieve document content in same time just add include_docs=True query parameter to your request.
UPD: Probably, you might be interested to retrieve documents by this reference ids (2,4,56). By default CouchDB views "maps" emitted keys with documents they belongs to. To tweak this behaviour you could use linked documents trick:
function(doc){
emit(doc.table.id, {'_id': doc.table.id});
}
And now request
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]&include_docs=True
will return rows with id field that points to document that holds 2,4 and 56 keys and doc one that contains referenced document content.
A: In CouchDB Bulk document APi is used for this:
curl -d '{"keys":["2","4", "56"]}' -X POST http://127.0.0.1:5984/foo/_all_docs?include_docs=true
http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12763430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Qt SDK download for MingW I´m looking for Qt SDK for windows that uses MingW as the compiler. Unfortunately, on the official download sites, I can only find the one that uses MSVC. Or just the library instead of the whole SDK.
Can anybody tell me where I can find the version I am looking for, or explain what I should do if I download QT library, QT creator and MingW seperately?
A: Here you can find pre-release builds using MinGW 4.7.
http://releases.qt-project.org/digia/5.0.1/latest/
They work well with the MinGW builds distributed here:
http://sourceforge.net/projects/mingwbuilds/
The Qt builds come with Qt Creator, so you can install it and should be good to go after setting up your kits.
A: You can find binaries here:
http://qt-project.org/forums/viewthread/23002/
But then you ought to reconfigure installation manual or you may use this utility.
Some guy from Digia promised MinGW builds by the end of January, so you can wait instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14454745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add into map in range loop package main
import (
"fmt"
)
func main() {
m := make(map[int]int, 4)
m[1] = 0
m[2] = 0
for k, _ := range m {
i := 10 + k
m[i] = 0
}
fmt.Println(m)
fmt.Println("len:", len(m))
}
This code returns: 8 or 10 or 6 as length of map after loop.
Video is here, playgroud here.
I see that new added elements go into range, but can't explain why this loop stops randomly?
A: Spec: For statements:
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.
The spec states that if you add entries to the map you are ranging over, the elements you add may or may not be visited by the loop, and moreover, which is visited is not even deterministic (may change when doing it again).
A: You are modifying map you are iterating over. This is the cause.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55399243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: IOS Charts Labels not centered to data points. Charts Library I am currently using IOS Charts to for a line chart.
This is the link to it: Link
It is horribly documented and I am having trouble centering my X-Axis labels to the plots on my chart.
I have already enabled granularity and set it to 1. - This ensures the labels do not get repeated
Here is what my chart looks like now:
Here is what I want it to look like:
I know the spacing of the points is different, but my main focus is how to get the labels centered to the correct data points.
My Code:
`import UIKit
import Charts
class ReviewDetailVC: UIViewController, ChartViewDelegate {
@IBOutlet weak var chartView: LineChartView!
var yValues = [Double]()
var months = [String]()
var xValues = [String]()
let red = UIColor(hue: 0.9639, saturation: 0.62, brightness: 0.93, alpha: 1.0)
let black = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
let grey = UIColor(red:0.81, green:0.81, blue:0.81, alpha:1.0)
let avenirDemi = UIFont(name: "AvenirNext-DemiBold", size: 14)
override func viewDidLoad() {
super.viewDidLoad()
chartView.delegate = self
// Chart Ui Settings
chartView.xAxis.axisMinimum = 1
chartView.leftAxis.axisMaximum = 5
chartView.leftAxis.axisMinimum = 0.0
chartView.chartDescription?.text = ""
chartView.xAxis.labelPosition = .bottom
chartView.legend.enabled = false
chartView.scaleYEnabled = false
chartView.scaleXEnabled = true
chartView.doubleTapToZoomEnabled = false
chartView.highlighter = nil
chartView.rightAxis.enabled = false
chartView.xAxis.drawGridLinesEnabled = false
chartView.dragEnabled = true
chartView.scaleXEnabled = false
chartView.scaleYEnabled = false
chartView.zoom(scaleX: 4, scaleY: 1, x: 0, y: CGFloat(AxisDependency.left.rawValue))
chartView.xAxis.labelFont = avenirDemi!
chartView.xAxis.labelTextColor = grey
chartView.leftAxis.labelFont = avenirDemi!
chartView.leftAxis.labelTextColor = black
chartView.xAxis.axisLineWidth = 0
chartView.leftAxis.axisLineWidth = 0
//chartView.xAxis.avoidFirstLastClippingEnabled = true
chartView.xAxis.granularityEnabled = true
chartView.xAxis.granularity = 1
chartView.leftAxis.gridColor = grey
chartView.leftAxis.gridLineDashLengths = [4]
chartView.leftAxis.gridLineWidth = 1.5
chartView.xAxis.centerAxisLabelsEnabled = true
chartView.noDataText = "This person has not reviewed your business."
//**MARK:: DATA SHIT
let sales = DataGenerator.data()
xValues = ["MAR 10"," MAR 15", "APR 7", "APR 8", "APR 15", "APR 30", "MAY 14", "MAY 21","MAY 31", "MAY 31"]
yValues = [4,2,4,5,3,4,2,4,5]
var salesEntries = [ChartDataEntry]()
var salesMonths = [String]()
var i = 0
for sale in sales {
// Create single chart data entry and append it to the array
let saleEntry = ChartDataEntry(x: Double(i), y: sale.value)
salesEntries.append(saleEntry)
// Append the month to the array
salesMonths.append(sale.date)
i += 1
}
// Create bar chart data set containing salesEntries
let chartDataSet = LineChartDataSet(values: salesEntries, label: "Profit")
// Create bar chart data with data set and array with values for x axis
let chartData = LineChartData(dataSets: [chartDataSet])
//setChart(dataPoints: xValues, values: yValues)
//let formatter = CustomLabelsAxisValueFormatter(miniTime: 0.0)
//formatter.labels = xValues
chartView.xAxis.valueFormatter = CustomLabelsAxisValueFormatter(miniTime: 0.0)
//**MARK:: END DATA SHIT
chartDataSet.colors = [red]
chartDataSet.drawCirclesEnabled = true
chartDataSet.circleRadius = 16
chartDataSet.circleColors = [red]
chartDataSet.circleHoleRadius = 12
chartDataSet.circleHoleColor = UIColor.white
chartDataSet.lineWidth = 4
chartDataSet.drawValuesEnabled = false
chartView.animate(yAxisDuration: 1)
chartView.setVisibleXRangeMaximum(4)
// Set bar chart data
chartView.data = chartData
setChart(dataPoints: xValues, values: yValues)
}
func setChart(dataPoints: [String], values: [Double]) {
chartView.noDataText = "You need to provide data for the chart."
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(values: dataEntries, label: "")
let chartData = LineChartData(dataSets: [chartDataSet])
chartDataSet.colors = [red]
chartDataSet.drawCirclesEnabled = true
chartDataSet.circleRadius = 16
chartDataSet.circleColors = [red]
chartDataSet.circleHoleRadius = 12
chartDataSet.circleHoleColor = UIColor.white
chartDataSet.lineWidth = 4
chartView.data = chartData
}
}`
A: You can change your setChart method to this:
func setChart(dataPoints: [String], values: [Double]) {
chartView.noDataText = "You need to provide data for the chart."
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i)+0.5, y: values[i])
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(values: dataEntries, label: "")
let chartData = LineChartData(dataSets: [chartDataSet])
chartDataSet.colors = [red]
chartDataSet.drawCirclesEnabled = true
chartDataSet.circleRadius = 16
chartDataSet.circleColors = [red]
chartDataSet.circleHoleRadius = 12
chartDataSet.circleHoleColor = UIColor.white
chartDataSet.lineWidth = 4
chartView.data = chartData
}
Result:
update:
chartView.xAxis.axisMinimum = 0.0 //I changed this from 1 to 0
let xvalues = ["MAR 10"," MAR 15", "APR 7", "APR 8", "APR 15", "APR 30", "MAY 14", "MAY 21","MAY 31", "MAY 31"]
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xvalues)
class MyIndexFormatter: IndexAxisValueFormatter {
open override func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
return "\(value)"
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44740453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Error when trying to push code to nexus maven I have found out that in order to add my code to my nexus repo I have to use mvn deploy
When ran I get this error:
https://hastebin.com/wikisohuni.pas
I have searhced ALL over stackoverflow and online guides, but NOTHING has worked!
settings.xml:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://192.168.0.145/nexus/content/groups/public</url>
</mirror>
</mirrors>
<proxies></proxies>
<pluginGroups>
<pluginGroup>org.codehaus.modello</pluginGroup>
</pluginGroups>
<profiles>
<profile>
<id>nexus</id>
<!--Enable snapshots for the built in central repo to direct -->
<!--all requests to nexus via the mirror -->
<repositories>
<repository>
<id>central</id>
<url>http://central</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://central</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
<servers>
<server>
<id>nexus</id>
<username>admin</username>
<password>removed</password>
</server>
</servers>
</settings>
My pom can be found at: https://github.com/PhanaticGames/PhanaticSpigotCore/blob/master/pom.xml
EDIT: I edited my settings a bit and got that error to go away, however, I now get this error: https://hastebin.com/ohukowohud.sql
However, these are what run my jar. I am making a central API for other plugins ran by these jars.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48304461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unicorn: do I need to disconnect from database in before_fork block? There is a comment that explains why you don't need to (and shouldn't) disconnect from DB and Redis in before_fork:
By disconnecting in before_fork, you are closing the connection at the parent process every time you spawn a child, which is only needed once - you're beating a dead horse. Connection handling is a child's concern (after_fork) rather than a parent's concern (before_fork).
ActiveRecord's connection pool is now keyed by Process.pid, so it's always safe to call ActiveRecord::Base.establish_connection in after_fork - the connection will never be shared with the parent, no need to disconnect at the master anyway.
On Unicorn, the master process is a singleton and can be used in many ways - spawn a thread and run EventMachine loop inside it to run scheduled / background jobs, etc. And there it's useful to keep the AR connection open. Only main thread will be inherited to a child (on linux systems at least) so it's safe to have threads.
Is that true?
A: It definitely isn't required, but I prefer to do it anyway - we run a ton of application servers and if we didn't disconnect the master process from the DB we'd be holding a lot of connections open for no reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29918475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Set A Methods For A Class In Vue.js you know that we can use on events for a class in JQuery.
for instance
$(".example").click(function(){
//the process
})
I am new on Vue.js and I am working on methods in vue.js
Vue use v-on attr to set a method for a element. But I dont want to define attr for all elements whichs use same function.
For Example
<ul class="container">
<li v-on="click:Menu" >Menu 1</li>
</ul>
<ol class="click">
<li v-on="click:Menu" >Menu 1</li>
<li v-on="click:Menu" >Menu 2</li>
</ol>
You must saw, I used v-on attr for all li elements. For li elements it is not problem, I can solve it v-repeat but for some cases, I have to set same function for lots of divs or form. I want to set a class for a function and set a method for the class.
Is there any solution for it?
A: David's answer is good. But if you don't want to use Jquery, you can use document.querySelectorAll instead of $(this.el).find("li") and then add the click handlers with addEventListener in the directive.
Having said that, you don't have to add event listeners to all the elements in a directive (even though a directive might be the best solution for this). Another approach would be to do what you suggest, put the handlers on the parent elements, and then implement some logic depending on which element the function was called from. Example:
https://jsfiddle.net/q7xcbuxd/33/
<div id="app">
<ul class="UL_items" v-on="click:Menu(1)">
<li>Menu 1 item 1</li>
</ul>
<ol class="OL_items" v-on="click:Menu(2)">
<li>Menu 2 item 1</li>
<li>Menu 2 item 2</li>
<li>Menu 2 item 3</li>
</ol>
<div class="DIV_items" v-on="click:Menu(3)">
lots<br/>
of<br/>
items<br/>
</div>
</div>
var vue = new Vue({
el: '#app',
methods: {
Menu: function(id){
console.log('You invoked function Menu' + id + ' ' +
'by clicking on ' + event.path[0].innerHTML + ' ' +
'which is of type ' + event.srcElement.nodeName + '.\n' +
'The parent element\'s class name is \'' + event.srcElement.parentElement.className + '\' ' +
'which is of type ' + event.srcElement.parentElement.nodeName + '.');
}
}
});
A: I would write a directive for <ol> and <ul> that adds click handlers for all <li> children.
Something like:
Vue.directive('menu', {
bind: function () {
$(this.el).find("li").on("click", function (event) {
this.menu_click(event);
});
},
update: function (value) {
this.menu_click = value;
},
unbind: function () {
$(this.el).find("li").off("click", this.menu_click);
}
})
And use it like this:
<ul class="container" v-menu="container_click">
<li>Menu 1</li>
</ul>
<ol class="click" v-menu="click">
<li>Menu 1</li>
<li>Menu 2</li>
</ol>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31574581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to deploy Angular cli 7 app on Azure using Visual Studio code? I created an Angular app using angular-cli(node 8.12) and build it:
npm install -g @angular/cli7
ng new my-app
ng build --prod //inside folder
i connect my visual studio code to my azure account then i create the service app and then just right click on my project and select Publish Web App then select my dist folder and deploy it.
VS say that all is completed and i see my dist folder but if i browse there i see the default page.
how can I solve this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56362684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: vc++ 6.0 testing an unlicensed Activex ctrl by dlg application I am using vc++ 6.0. I Have made an unlicensed activex ctrl application from app wizard (MFC activeX ctrl wizard for generating random drawing). When I am testing this Activex by ActiveX control test container, all functions are working fine, but when I am testing it with dialog application, On calling any method of ActiveX it is giving error debug assertion failed.
Program ......
File: winocc.cpp;
line: 345
I am making an object of this ActiveX ctrl wrapper class in my testing dialog application and then calling method defined in this ActiveX ctrl.
My code:
CNewSquiggleAcX m_ClNewSquigg;
CFileDialog m_ldFile(TRUE);
// Show the File open dialog and capture the result
if(m_ldFile.DoModal()== IDOK)
{
CString m_sResults;
m_sResults = m_ldFile.GetFileName();
//m_ClNewSquigg.GetSquiggleLength();
m_ClNewSquigg.LoadDrawing(m_sResults); // Error comes in this line
calling any activex function
}
Please help me thanks in advance
A: The control needs to be instanciated. If you placed it on a dialog template then opening the dialog will create the control. The other approach is to call the CreateControl method, which you can find in the h file of the control's wrapper class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17148410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Refreshing the Cursor from SQLiteCursorLoader My project uses the SQLiteCursorLoader library from commonsguy to load data from a database into a ListView. Among that data is a simple boolean (as so far as SQLite supports booleans... that is, a number that only ever is 0 or 1) that tells the state of a checkbox. If I change the state of a checkbox in a list and then scroll the item off the list, the list item returns to the state it has when the cursor was passed in, despite the fact that the underlying database has changed. If I change the state of a bunch of checkboxes and then activate the list's MultiChoiceMode, all the items displayed will revert back to the state they were in when the cursor was originally passed in, despite the fact that the underlying database has changed.
Is there a way to refresh the cursor? Cursor.requery() is deprecated, and I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot. I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.
A:
Is there a way to refresh the cursor?
Call restartLoader() to have it reload the data.
I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot
Used properly, a ListView maintains the checked state for you. You would do this via android:choiceMode="multipleChoice" and row Views that implement Checkable. The objective is to not modify the database until the user has indicated they are done messing with the checklist by one means or another (e.g., "Save" action bar item).
I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.
Don't call it several times. Ideally, call it zero times, by not updating the database until the user is done, at which point you are probably transitioning to some other portion of your UI. Or, call it just once per requested database I/O (e.g., at the point of clicking "Save"). Or, switch from using a CursorAdapter to something else, such as an ArrayAdapter on a set of POJOs you populate from the Cursor, so that the in-memory representation is modifiable in addition to being separately persistable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16824750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIButton not working on the first tap I made a custom switch to turn on and off sound effects in my game Optic Combat, but for some reason the button that when tapped, animates the switch moving to a different position, is not working on the first tap. Subsequent taps work, just not the first one.
In the IBAction for the button I have:
- (IBAction)theSwitch:(id)sender {
NSUserDefaults *toggle = [NSUserDefaults standardUserDefaults];
if (_toggle == 1) {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
_toggle ++;
[toggle setInteger:_toggle forKey:@"toggleState"];
[toggle synchronize];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];
}
else {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
_toggle --;
[toggle setInteger:_toggle forKey:@"toggleState"];
[toggle synchronize];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];
}
}
And in the viewDidLoad, checking the state of the switch and adjusting it to show the correct position (on or off):
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
[audioToggle setFrame:CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
_toggle = 2;
}
else {
[audioToggle setFrame:CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
_toggle = 1;
}
Edit: I used this to solve my problem, in the IBAction for the button:
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];
}
else {
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];
}
A: In your viewDidLoad
if _toggle = 2;
frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)
and
if _toggle = 1;
frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)
But in your buttonAction it is different. Interchange in viewDidLoad if buttonAction is correct.
A: I suspect Anusha got it. But I also suspect you would easily have found it yourself if you'd chosen a slightly different style. The toggle is either on or off, in other words a perfect match for a boolean. If you had a BOOL named swicthedOn you'd have checks reading if (switchedOn) which would improve readability a lot.
Something like this perhaps:
- (IBAction)theSwitch:(id)sender { // Not using the sender for anything (?)
NSUserDefaults *toggle = [NSUserDefaults standardUserDefaults];
BOOL audioOn = NO;
float toggleX = 924.0f;
if (_switchIsOn) {
toggleX = 985.0f;
audioOn = NO; // not strictly necessary but improves readability
}
else {
toggleX = 924.0f; // not strictly necessary but improves readability
audioOn = YES;
}
_switchIsOn = audioOn;
[UIView animateWithDuration:0.3 animations:^{
audioToggle.frame = CGRectMake(toggleX, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
}];
[toggle setBool:_switchIsOn forKey:@"toggleState"];
[toggle synchronize];
[[NSUserDefaults standardUserDefaults] setBool:audioOn forKey:@"audioOn"]; // Not being synchronized
}
Yes, I refactored it (and probably introduced a couple of new bugs). Sorry, couldn't help myself...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14374442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the path to global node_modules folder in Travis CI I need to pass the path for the node_modules global installation folder to the mink-zombie-driver, but I can't find anywhere in the docs what's the path for it.
MinkExtension requires you to pass the node_modules folder in the configuration file for Behat.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39756387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Column-image hover text Hello everybody out there reading my question :)
I am currently working on website with a "Masonry-lookalike" home screen.
There are 4x4 images with 2 different sizes and 1 image in every column is hidden.
So far it went pretty good but now I am stuck on the text-effect when hovering one of the images.
When the cursor is hovering over an image, a small text-box should appear on the bottom of it.
*
*How do i get them one above the other without ruining the Masonry?
*Where do i place the Text in the html code?
Sorry for my English, its not the best since I am from Austria ;)
HTML:
<!DOCTYPE html>
<!-- HTML -->
<html>
<!-- HEAD -->
<head>
<!-- STYLESHEET -->
<link href="style.css" rel="stylesheet" type="text/css" />
<!-- UTF-8 -->
<meta charset="utf-8">
</head>
<!-- HEAD END -->
<!-- --------------------------------------------------------------- -->
<!-- BODY -->
<body>
<div id="img-container">
<ul id="content">
<li><img class="img_a" src="data/placeholder_a.png" alt="" />
</li>
<li><img class="img_c" src="data/placeholder_c.png" alt="" />
</li>
<li><img class="img_b" src="data/placeholder_b.png" alt="" />
</li>
<li><img class="img_a" src="data/placeholder_a.png" alt="" />
</li>
<li><img class="img_a" src="data/placeholder_a.png" alt="" />
</li>
<li><img class="img_a" src="data/placeholder_a.png" alt="" />
</li>
<li><img class="img_c" src="data/placeholder_c.png" alt="" />
</li>
<li><img class="img_b" src="data/placeholder_b.png" alt="" />
</li>
<li><img class="img_c" src="data/placeholder_c.png" alt="" />
</li>
<li><img class="img_a" src="data/placeholder_a.png" alt="" />
</li>
<li><img class="img_a" src="data/placeholder_a.png" alt="" />
</li>
<li><img class="img_c" src="data/placeholder_c.png" alt="" />
</li>
<li><img class="img_b" src="data/placeholder_b.png" alt="" />
</li>
</ul>
</div>
</body>
<!-- BODY END -->
</html>
<!-- HTML END -->
CSS:
body {
margin: 0;
padding: 0;
}
#img-container {
width: 1200px;
margin: 0 auto;
font-size: 0;
}
#content {
column-count: 4;
column-gap: 10px;
}
#content li img {
margin-bottom: 10px;
width: 100%;
display: block;
}
/* --------------------- HOVER EFFECTS --------------------- */
.img_a:hover {
opacity: 0.5;
}
.img_b:hover {
opacity: 0.5;
}
.img_c:hover {
opacity: 0.5;
}
I will append some zip.-file with .css .html and images.
Link to Dropbox
A: The following writeup might help you:
http://geekgirllife.com/place-text-over-images-on-hover-without-javascript/
It is one of the simplest methods I came across. Place the div tag containing text right below the img tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39047325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AS3 undefined property stageVideos I have an AS3 Mobile AIR project targeting iOS and Android. For some reason when I try to access stageVideos i.e. stage.stageVideos[0]...there is NO stageVideos property available on stage?? Very strange as I've done it before. My app is using Starling and Features UI framework, and my class is extending Screen. I'm fairly new to both frameworks but have been AS veteren. Thanks!
A: Should be hardware problem. When StageVideo is not available on particular device stage.stageVideos property is empty, so to make sure you should make check like this.
var stageVideo:StageVideo;
if ( stage.stageVideos.length >= 1 ) {
stageVideo = stage.stageVideos[0];
}
or register StageVideoAvailabilityEvent on stage
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, stageVideoChange);
private function stageVideoChange(e:StageVideoAvailabilityEvent):void
{
if(e.availability == AVAILABLE)
{
// (stage.stageVideos.length >= 1) is TRUE so we can use stageVideo[0]
}
else
{
// StageVideo become unavailable for example after going from fullscreen
// back to wmode=normal, wmode=opaque, or wmode=transparent
}
}
Of course second approach is more acceptable because you are notified every time StageVideo becomes available or negative. Note if stage video is available at the moment of registering Listener on StageVideoAvailabilityEvent then listener function (stageVideoChange) is called immediately.
A: Turns out Starling runs on Stage3D on TOP of the actual flash display stage. So in order to do this, you need to hide the Starling Stage3D first:
Starling.current.stage3D.visible = false
Then you can access and show...etc stageVideos and add to the flash display stage:
_stageVideo = Starling.current.nativeStage.stageVideos[0];
So basically, the native flash display stage is on the Starling.current.nativeStage property, however, can not be visible unless you first hide the Starling.current.stage3D FIRST.
Thanks for the responses! Hope this helps anyone else with the same problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13000407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: regex breaks when I use a colon(:) I just started working with elastic search. By started working I mean I have to query an already running elastic database. Is there a good documentation of the regex they follow. I know about the one on their official site, but its not very helpful.
The more specific problem is that I want to query for lines of the sort:
10:02:37:623421|0098-TSOT {TRANSITION} {ID} {1619245525} {securityID} {} {fromStatus} {NOT_PRESENT} {toStatus} {WAITING}
or
01:01:36:832516|0058-CT {ADD} {0} {3137TTDR7} {23} {COM} {New} {0} {0} {52} {1}
and more of a similar structure. I don't want a generalized regex. If possible, could someone give me a regex expression for each of these that would run with elastic?
I noticed that it matches if the regexp matches with a substring too when I ran with:
query = {"query":
{"regexp":
{
"message": "[0-9]{2}"
}
},
"sort":
[
{"@timestamp":"asc"}
]
}
But it wont match anything if I use:
query = {"query":
{"regexp":
{
"message": "[0-9]{2}:.*"
}
},
"sort":
[
{"@timestamp":"asc"}
]
}
I want to write regex that are more specific and that are different for the two examples given near the top.
A: turns out my message is present in the tokenized form instead of the raw form, and : is one of the default delimiters of the tokenizer, in elastic. And as a reason, I can't use regexp query on the whole message because it matches it with each token individually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55968036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add groups to asp.net dropdownlist control? I have to implement groups in asp.net dropdownlist.
eg: I have a classname as dropdownlist group and students in the class as its options.
How can I implement this using JqueryUI Multiselect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22657207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Select-Object with output from 2 cmdlets Suppose I have the following PowerShell script:
Get-WmiObject -Class Win32_Service |
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU
This will:
Line 1: Get all services on the local machine
Line 2: Create a new object with the DisplayName and PID.
Line 3: Call Get-Process for information about each of the services.
Line 4: Create a new object with the Process Name and CPU usage.
However, in Line 4 I want to also have the DisplayName that I obtained in Line 2 - is this possible?
A: One way to do this is to output a custom object after collecting the properties you want. Example:
Get-WmiObject -Class Win32_Service | foreach-object {
$displayName = $_.DisplayName
$processID = $_.ProcessID
$process = Get-Process -Id $processID
new-object PSObject -property @{
"DisplayName" = $displayName
"Name" = $process.Name
"CPU" = $process.CPU
}
}
A: A couple of other ways to achieve this:
Add a note property to the object returned by Get-Process:
Get-WmiObject -Class Win32_Service |
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
% {
$displayName = $_.DisplayName;
$gp = Get-Process;
$gp | Add-Member -type NoteProperty -name DisplayName -value $displayName;
Write-Output $gp
} |
Select DisplayName, Name,CPU
Set a script scoped variable at one point in the pipeline, and use it at a later point in the pipeline:
Get-WmiObject -Class Win32_Service |
Select @{n='DisplayName';e={($script:displayName = $_.DisplayName)}},
@{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select @{n='DisplayName';e={$script:displayName}}, Name,CPU
A: Using a pipelinevariable:
Get-CimInstance -ClassName Win32_Service -PipelineVariable service |
Select @{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU,@{Name='DisplayName';Expression={$service.DisplayName}}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18255126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to insert a existing json data into new object? I have a json data is in this form
[ { id: '1', name: 'Plant Director', parentJobID: -1 },
{ id: '19', name: 'Operations Director', parentJobID: 1 },
{ id: '16',
name: 'Financial planning and costs Manager',
parentJobID: 19 },
{ id: '14', name: 'Cost Analyst', parentJobID: 16 },
{ id: '15', name: 'Head of Costs', parentJobID: 16 },
{ id: '17', name: 'Manufacturing Manager', parentJobID: 19 },
{ id: '2', name: 'Head of Security', parentJobID: 17 },
{ id: '3', name: 'Asistente Ejecutiva', parentJobID: 2 },
{ id: '8', name: 'Jefe de Mantenimiento', parentJobID: 2 },
{ id: '27',
name: 'Jefe Aseguramiento de Calidad',
parentJobID: 2 },
{ id: '28', name: 'Jefe Seguridad Alimentaria', parentJobID: 27 },
{ id: '33', name: 'Operario Fabricación A (2)', parentJobID: 28 },
{ id: '34', name: 'Operario Fabricación B (2)', parentJobID: 28 },
{ id: '29',
name: 'Especialista Aseguramiento de Calidad',
parentJobID: 27 },
{ id: '30',
name: 'Especialista en Microbiología',
parentJobID: 27 },
{ id: '31',
name: 'Especialista en Evaluación Sensorial',
parentJobID: 27 },
{ id: '32',
name: 'Técnico Aseguramiento de Calidad',
parentJobID: 27 },
{ id: '4', name: 'Production Manager', parentJobID: 17 },
{ id: '5', name: 'Head of Maintenance', parentJobID: 17 },
{ id: '6', name: 'Quality Control Manager', parentJobID: 17 },
{ id: '7', name: 'Técnico Medio Ambiente', parentJobID: 6 },
{ id: '23',
name: 'Quality Control Technician 1',
parentJobID: 6 },
{ id: '25', name: 'Operario Fabricación B', parentJobID: 23 },
{ id: '26', name: 'Operario Fabricación D', parentJobID: 23 },
{ id: '24',
name: 'Quality Control Technician 2',
parentJobID: 6 },
{ id: '9', name: 'Warehouse Manager', parentJobID: 17 },
{ id: '10', name: 'Head of Planning', parentJobID: 17 },
{ id: '20', name: 'Operario Mtto A (2)', parentJobID: 10 },
{ id: '11',
name: 'Head of Continuous Improvement',
parentJobID: 17 },
{ id: '21', name: 'Operario Servicios A (2)', parentJobID: 11 },
{ id: '12', name: 'Head of Supplies', parentJobID: 17 },
{ id: '13', name: 'Process Manager', parentJobID: 17 },
{ id: '18', name: 'IT Manager', parentJobID: 17 },
{ id: '35', name: '[ LINEA DE PRODUCCION ]', parentJobID: 1 },
{ id: '22', name: 'Extrusion Area', parentJobID: -1 } ]
then i change it into hierarchy form like:
[ { id: '1',
name: 'Plant Director',
parentJobID: -1,
children: [ [Object], [Object] ] },
{ id: '22',
name: 'Extrusion Area',
parentJobID: -1,
children: [] } ]
i want to show like this
http://www.jqueryscript.net/demo/jQuery-Plugin-To-Create-Checkbox-Tree-View-highchecktree/
but in this they used item label which is not in my response i need to change the josn in this form
item:{
id: '1',
label: 'Plant Director',
checked: false
},
children: [{
item:{
id: '19',
label: 'Operations Director',
checked: false
}
},{
item:{
id: '35',
label: '[ LINEA DE PRODUCCION ]',
checked: false
}
}
}]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37608143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TypeError: Cannot interpret feed_dict key as Tensor, need to understand sessions and graphs I'm new to tensorflow and posting this using mobile. I actually wanted the session to alive so used the following way of coding. However, in one place I can see Placeholder node existing, but error comes up saying the node doesn't exist. I doubt on the same graph being used.
class Model(object):
def __init__(self, model_path):
self.sess = tf.Session()
self.graph = tf.Graph()
self.graph_def = tf.GraphDef()
with open(model_path, "rb") as f:
self.graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as self.graph:
tf.import_graph_def(self.graph_def)
self.input_operation = self.graph.get_operation_by_name('import/Placeholder')
self.output_operation = self.graph.get_operation_by_name('import/final_result')
def predict(self, images):
dims_expander = tf.expand_dims(images, 0)
resized = tf.image.resize_bilinear(dims_expander, [299, 299])
normalized = tf.divide(tf.subtract(resized, [0]), [255])
print(normalized)
for op in self.graph.get_operations():
print(op.name)
results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
results = np.squeeze(results)
top_k = results.argsort()[-5:][::-1]
labels = ['1','0']
print(labels[top_k[0]], results[top_k[0]])
And then making an object.
model = Model('identification_model.pb').predict(img_from_openCV)
The following is the output error including the print statement that printed the first node to be import/Placeholder
Tensor("truediv_13:0", shape=(1, 299, 299, 3), dtype=float32)
import/Placeholder
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1091 subfeed_t = self.graph.as_graph_element(
-> 1092 subfeed, allow_tensor=True, allow_operation=False)
1093 except Exception as e:
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
3489 with self._lock:
-> 3490 return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
3491
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
3568 if obj.graph is not self:
-> 3569 raise ValueError("Tensor %s is not an element of this graph." % obj)
3570 return obj
ValueError: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
----> 1 model = Model('identification_model.pb').predict(img)
32 for op in self.graph.get_operations():
33 print(op.name)
---> 34 results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
35 results = np.squeeze(results)
36 top_k = results.argsort()[-5:][::-1]
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
927 try:
928 result = self._run(None, fetches, feed_dict, options_ptr,
--> 929 run_metadata_ptr)
930 if run_metadata:
931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1093 except Exception as e:
1094 raise TypeError(
-> 1095 'Cannot interpret feed_dict key as Tensor: ' + e.args[0])
1096
1097 if isinstance(subfeed_val, ops.Tensor):
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.
A: When you create the session, the default graph is launched by default, which does not contain the operations you are looking for (they are all in self.graph). You should do something like this:
with tf.Session(self.graph) as sess:
sess.run(...)
Now, sess will have access to self.input_operation and self.output_operation. In your code, this means you should create the session after you create self.graph. By the way, most of the time it is more convenient to just use the default graph (exactly to avoid problems like these). May be this post will also help you in this regard.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54865209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fragment crash: IndexOutOfBoundsException: Invalid index x, size is x after updating my database Im making an app where i download the data from an api. The data is downloaded every X minutes. When the data has been downloaded, it is stored in my DB. However, the problem i have is that whenever i update the db, the generateData() method in FragmentTrend crashes when i switch to another tab and comeback again. I get the the index out of bound exception as seen below. It crashes at line:
int y = Integer.parseInt(listDatastream.get(i).getCurrent_value());
Ive tried to test out that whenever the count != getNumberOfElementsInDatabase() then just return the value to see whether or not it would help, however, i end up with another error which is similar to this thread: DB error code 14
Any help would be appreciated! Ive been stuck with this problem for more than 3 days now! Thank you!
Additional information: I have 4 tabs and use FragmentStatePagerAdapter to navigate. Ive noticed one thing while navigating. Whenever i navigate to the neighboring tab (such as tab1 to tab2), the previous tab is not terminated. It is still on the run. I found this out by printing an endless forloop with text. The for loop stops only when im 2 tabs away (such as from tab1 to tab3 / tab4 or tab 2 to tab4 etc). So the app crashes only when i select tab3 or tab4 then reselect tab1 or tab2 respectively.
Error:
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: FATAL EXCEPTION: main
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: Process: com.thesis.dell.MaterialTest2, PID: 2618
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 166, size is 166
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:308)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.generateData(FragmentTrend.java:166)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.drawGraphVolt(FragmentTrend.java:112)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.onCreateView(FragmentTrend.java:86)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
FragmentTrend.java
package com.thesis.dell.MaterialTest2.fragments;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.thesis.dell.MaterialTest2.MyApplication;
import com.thesis.dell.MaterialTest2.R;
import com.thesis.dell.MaterialTest2.log.L;
import com.thesis.dell.MaterialTest2.pojo.Datastream;
import java.util.ArrayList;
public class FragmentTrend extends Fragment {
private static final String STATE_DATASTREAM2 = "state_datastream2";
private ArrayList<Datastream> listDatastream = new ArrayList<>();
//private SwipeRefreshLayout mSwipeRefreshLayout;
private View view;
private LineGraphSeries<DataPoint> mVolt;
private int count;
public FragmentTrend() {
// Required empty public constructor
}
public static FragmentTrend newInstance(String param1, String param2) {
FragmentTrend fragment = new FragmentTrend();
Bundle args = new Bundle();
//put any extra arguments that you may want to supply to this fragment
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.tab_trend,container,false);
count = getNumberOfElementsInDatabase();
//setupSwipe();
//printAllValuesInDatastream();
if (savedInstanceState != null) {
//if this fragment starts after a rotation or configuration change,
// load the existing data from a parcelable
L.t(getActivity(), "savedInstanceState not null");
listDatastream = savedInstanceState.getParcelableArrayList(STATE_DATASTREAM2);
}
else {
//if this fragment starts for the first time, load the list of data from a database
//get a reference to our DB running on our main thread
L.t(getActivity(), "savedInstanceState is null");
listDatastream = MyApplication.getWritableDatabase().readDatastreams();
}
if (listDatastream != null && !listDatastream.isEmpty()) {
drawGraphVolt();
}
return view;
}
public void drawGraphVolt () {
// Setting up and drawing volt graph
GraphView graph = (GraphView) view.findViewById(R.id.graph);
mVolt = new LineGraphSeries<>(generateData());
graph.addSeries(mVolt);
// styling grid/labels
graph.getGridLabelRenderer().setGridColor(getResources().getColor(R.color.colorGraphGrid));
graph.getGridLabelRenderer().setHorizontalLabelsColor(getResources().getColor(R.color.colorGraphText));
graph.getGridLabelRenderer().setVerticalLabelsColor(getResources().getColor(R.color.colorGraphText));
graph.getGridLabelRenderer().setTextSize(45);
graph.getGridLabelRenderer().reloadStyles();
// styling series
mVolt.setColor(getResources().getColor(R.color.colorAccent));
mVolt.setThickness(4);
//series.setDrawBackground(true);
//series.setBackgroundColor(getResources().getColor(R.color.gridGraphColor));
graph.getViewport().setYAxisBoundsManual(true);
graph.getViewport().setMinY(graph.getViewport().getMinY(false));
graph.getViewport().setMaxY(graph.getViewport().getMaxY(false));
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(graph.getViewport().getMinX(true));
graph.getViewport().setMaxX(graph.getViewport().getMaxX(true));
mVolt.setTitle("Volt");
graph.getLegendRenderer().setVisible(true);
graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
graph.getLegendRenderer().setTextSize(45);
graph.getLegendRenderer().setBackgroundColor(getResources().getColor(R.color.colorPrimary));
graph.getLegendRenderer().setTextColor(getResources().getColor(R.color.colorPrimaryText));
graph.getLegendRenderer().setPadding(15);
graph.getLegendRenderer().setMargin(0);
graph.getViewport().setScrollable(true);
}
private DataPoint[] generateData() {
DataPoint[] values = new DataPoint[count];
for (int i = 0; i < count; i++) {
// if (count != getNumberOfElementsInDatabase()) {
//
// return values;
// }
int x = i;
int y = Integer.parseInt(listDatastream.get(i).getCurrent_value());
DataPoint v = new DataPoint(x, y);
values[i] = v
}
return values;
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_DATASTREAM2, listDatastream);
}
public int getNumberOfElementsInDatabase() {
int countListDatastream = MyApplication.getWritableDatabase().getTotalNumberOfElements();
return countListDatastream;
}
}
My Database:
package com.thesis.dell.MaterialTest2.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import com.thesis.dell.MaterialTest2.pojo.Datastream;
import com.thesis.dell.MaterialTest2.log.L;
import java.util.ArrayList;
import java.util.Date;
public class MyDatabase {
private MyHelper mHelper;
private SQLiteDatabase mDatabase;
public MyDatabase(Context context) {
mHelper = new MyHelper(context);
mDatabase = mHelper.getWritableDatabase();
//mDatabase.close();
}
public void insertValues(ArrayList<Datastream> listValues, boolean clearPrevious) {
if (clearPrevious) {
deleteData();
}
//beginTransaction(null /* transactionStatusCallback */, true); allowed to comment like this?
//create a sql prepared statement
String sql = "INSERT INTO " + MyHelper.TABLE_NAME + " VALUES (?,?,?);";
//compile the statement and start a transaction
SQLiteStatement statement = mDatabase.compileStatement(sql);
mDatabase.beginTransaction();
for (int i = 0; i < listValues.size(); i++) {
Datastream currentData = listValues.get(i);
statement.clearBindings();
//for a given column index, simply bind the data to be put inside that index
statement.bindString(2, currentData.getCurrent_value());
statement.bindLong(3, currentData.getCurrent_valueAt() == null ? -1 : currentData.getCurrent_valueAt().getTime());
L.m("Inserting entry " +i);
statement.execute();
}
//set the transaction as successful and end the transaction
mDatabase.setTransactionSuccessful();
mDatabase.endTransaction();
}
public int getTotalNumberOfElements() {
int numberOfElements = -1;
//get a list of columns to be retrieved, we need all of them
String[] columns = {MyHelper.COLUMN_VALUE, MyHelper.COLUMN_DATE_AT};
//make a simple query with dbname, columns and all other params as null
Cursor cursor = mDatabase.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
numberOfElements = cursor.getCount();
return numberOfElements;
}
return numberOfElements;
}
public ArrayList<Datastream> readDatastreams()
{
//init an empty array list
ArrayList<Datastream> listDatastream = new ArrayList<>();
//get a list of columns to be retrieved, we need all of them
String[] columns = {MyHelper.COLUMN_VALUE, MyHelper.COLUMN_DATE_AT};
//make a simple query with dbname, columns and all other params as null
Cursor cursor = mDatabase.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
//create a new Datastream object and retrieve the data from the cursor to be stored in this Datastream object
Datastream datastream = new Datastream();
//each step is a 2 part process, find the index of the column first, find the data of that column using
//that index and finally set our blank Datastream object to contain our data
datastream.setCurrent_value(cursor.getString(cursor.getColumnIndex(MyHelper.COLUMN_VALUE)));
long valueAtMilliseconds = cursor.getLong(cursor.getColumnIndex(MyHelper.COLUMN_DATE_AT));
datastream.setCurrent_valueAt(valueAtMilliseconds != -1 ? new Date(valueAtMilliseconds) : null);
//add the datastream to the list of datastream objects which we plan to return
listDatastream.add(datastream);
}
while (cursor.moveToNext());
}
return listDatastream;
}
//delete all rows from our table
public void deleteData() {
mDatabase.delete(MyHelper.TABLE_NAME, null, null);
}
public long insertData(String value, String valueDate) {
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(MyHelper.COLUMN_VALUE, value);
cv.put(MyHelper.COLUMN_DATE_AT, valueDate);
//ID indicates the row id that was inserted if successfull
long id = db.insert(MyHelper.TABLE_NAME, null, cv);
return id;
}
public String getColumnValueLast() {
SQLiteDatabase db = mHelper.getWritableDatabase();
String[] columns = {MyHelper.COLUMN_VALUE};
Cursor cursor = db.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null );
String lastValue = "-1";
if (cursor.moveToLast()) {
int index1 = cursor.getColumnIndex(MyHelper.COLUMN_VALUE);
String value = cursor.getString(index1);
lastValue = value;
}
return lastValue;
}
static class MyHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "MyDB";
private static final String TABLE_NAME = "TableValue";
private static final int DB_VERSION = 2;
private static final String COLUMN_UID = "_id";
private static final String COLUMN_VALUE = "current_value";
private static final String COLUMN_DATE_AT = "at";
private static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME
+ " ("
+ COLUMN_UID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_VALUE
+ " VARCHAR(100), "
+ COLUMN_DATE_AT
+ " VARCHAR(100));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context; //mContext;
public MyHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
// or mContext = context
this.context = context;
L.t(context, "constructor called");
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
L.t(context, "onCreate called");
} catch (SQLException e) {
L.t(context, "" + e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
L.t(context, "onUpgrade called");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
L.t(context, "" + e);
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33422624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: why the output of the expression --- 'a' and 'e' and 'i' and 'o' and 'u' in 'eiou' --- is true? 'a' and 'e' and 'i' and 'o' and 'u' in 'eiou'
true
However,
'a' and 'e' and 'i' and 'o' and 'u' in 'aeio'
false
what is the problem?
A: if 'a' and 'e' and 'i' and 'o' and 'u' in 'eiou'
is equivalent to
if ('a') and ('b') and ('i') and ('o') and ('u' in 'eiou')
in which all the first 4 expressions 'a', 'b', 'i' and 'o' evaluate to True.
The final expression ('u' in 'eiou') is True for the first statement, whereas 'u' in 'aeio' is False
A: emm... It is the way python evaluates conditional expressions. This is how it works:
'a' and 'e' and 'i' and 'o' and 'u' in 'eiou'
'a' -> a non-empty string always evaluates to True, so we got True.
and -> if the expression before 'and' evaluates to True, evaluate the next expression.
'e' -> True
and -> continue evaluation
'i' -> True
and -> continue evaluation
'o' -> True
and -> continue evaluation
'u' in 'eiou' -> True
So you got True.
The next expression:
'a' and 'e' and 'i' and 'o' and 'u' in 'aeio'
'a' -> True
and -> continue evaluation
'e' -> True
and -> continue evaluation
'i' -> True
and -> continue evaluation
'o' -> True
and -> continue evaluation
'u' in 'aeio' -> False
so you got a False.
If what you want is to check if all letters are in the string, you either 'a' in 'aeio' and 'e' in 'aeio' and ... or more efficiently: if set('aeiou').issuperset(('a', 'e', 'i', 'o', ...)).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66502553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: @register.filter in my code from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload"
}
@register.filter#<--------
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter#<--------
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
field.field.widget.attrs['class'] += " %s" % class_name
else:
field.field.widget.attrs['class'] = class_name
return unicode(field)
and register.filter function is:
def filter(self, name=None, filter_func=None):
if name == None and filter_func == None:
# @register.filter()
return self.filter_function
elif filter_func == None:
if(callable(name)):
# @register.filter
return self.filter_function(name)
else:
# @register.filter('somename') or @register.filter(name='somename')
def dec(func):
return self.filter(name, func)
return dec
elif name != None and filter_func != None:
# register.filter('somename', somefunc)
self.filters[name] = filter_func
return filter_func
else:
raise InvalidTemplateLibrary("Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func))
so
@register.filter
def a():
pass
is Equal
register.filter(name=None,filter_func=a)
yes??
A: Not exactly. The decorator syntax:
@register.filter
def a():
pass
is syntactic sugar for:
def a():
pass
a = register.filter(a)
So register.filter in this case will be called with the first positional argument, 'name' being your function. The django register.filter function handles that usage however and returns the right thing even if the filter is sent as the first argument (see the if callable(name) branch)
It's more common to make decorators that can take multiple arguments do so with the function to be decorated being the first positional argument (or alternately being function factories/closures), but I have a feeling the reason django did it this way was for backwards-compatibility. Actually I vaguely remember it not being a decorator in the past, and then becoming a decorator in a later django version.
A: No. Simple decorators take the function they decorate as a parameter, and return a new function.
a = register.filter(a)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2080296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create a dialog with custom content like android in Zebble for Xamarin? I want to create a dialog for editing some field and I need to make custom content for dialog and get the response from it to reload the Data. So, I read all content about dialog and popup in link below
http://zebble.net/docs/alerts-and-dialogs
And then I test this code:
In another page I want to show the popup:
await Nav.ShowPopUp<CustomeDialogPage>();
My custom Zebble page:
<z-Component z-type="CustomeDialogPage"
z-base="Page"
z-namespace="UI.Pages"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../.zebble-schema.xml">
<Stack CssClass="customedialog">
<Button Text="OK" />
</Stack>
</z-Component>
And then I create stylesheet for that
.customedialog {
width: 300px;
height: 100px;
background: #ffffff;
border: 2px;
padding: 5px;
margin-top: 100px;
}
but, I could not able to close the popup or add a title section for it and I do not know how I can get the result of it.
And it is a sample dialog I want to use it like below:
A: Zebble provides you with other overloads of the Nav pop-up methods to help you achieve that.
Host page:
var result = await Nav.ShowPopup<TargetPage, SomeType>();
// Now you can use "result".
Pop-up page's close button:
...
await Nav.HidePopup(someResultValue);
Notes:
*
*"SomeType" can be a simple type such as boolean or string, or it can be a complex class.
*The type of the object returned by the pop-up must match the one expected by the host parent page.
You can check out the full spec here: http://zebble.net/docs/showing-popup-pages
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43413299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to double click any where on web page? Actions actions = new Actions(getDriver());
actions.moveByOffset(700,700);
actions.click().build().perform();
actions.moveByOffset(40,0);
actions.click().build().perform();
actions.moveByOffset(0,40);
actions.click().build().perform();
actions.moveByOffset(0,0);
actions.doubleClick().build().perform();
I can make it click but can't make it double click.
Do you have any idea ? How can i change this part of code .I need to double click any where on web page. Just a double click action .
actions.moveByOffset(0,0);
actions.doubleClick().build().perform();
A: As per the Java Docs of current build of Selenium Java Client v3.8.1 you cannot use public Actions doubleClick() as the documentation clearly mentions that DoubleClickAction is Deprecated. Here is the snapshot :
Hence you may not be able to invoke doubleClick() from Package org.openqa.selenium.interactions
Solution :
If you need to execute doubleClick() two possible solutions are available as follows :
*
*Use Actions.doubleClick(WebElement)
*Use JavascriptExecutor to inject a script defining doubleClick().
A: You have to pass element argument to doubleClick() menthod.
actions.doubleClick(anyClickableWebElement).build().perform();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47978658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to detect the cases that fulfill A ∈ B, but B ∉ A I have a dataset that looks like this:
It show the relationship among the dataset.
1). for col1, it means: all the variables in cy1.CSV are also in the dataset "cy1.CSV", "cy24.CSV", "cy6.CSV".
2) dov.CSV: all the variables in dov.CSV are also in the dataset "dov.CSV", "dov_1.CSV"
2) dov_1.CSV: all the variables in dov_1.CSV can only be found in the dataset "dov_1.CSV"
df<-structure(list(cy1.CSV = c("cy1.CSV", "cy24.CSV", "cy6.CSV"),
cy2.CSV = c("cy2.CSV", NA, NA), cy24.CSV = c("cy1.CSV", "cy24.CSV",
"cy6.CSV"), cy3.CSV = c("cy3.CSV", NA, NA), cy6.CSV = c("cy1.CSV",
"cy24.CSV", "cy6.CSV"), dlt.CSV = c("dlt.CSV", NA, NA), dm.CSV = c("dm.CSV",
NA, NA), dov.CSV = c("dov.CSV", "dov_1.CSV", NA), dov_1.CSV = c("dov_1.CSV",
NA, NA), ds.CSV = c("ds.CSV", "ds_1.CSV", NA), ds_1.CSV = c("ds.CSV",
"ds_1.CSV", NA)), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))
Is it way we can find cases that fulfill: A ∈ B, but B ∉ A, in out example. dov.CSV belong to dov_1.CSV, dov_1.SCV not belong to dov.CSV. Maybe find a way to put what we find into a list or data.frame.
A: We can use the column names of df to check whether each file is %in% each column inside an sapply. This will give us a square matrix which tells us whether each file contains every other file.
This way, it is straightforward to use array indexing to get the files which contain other files:
tab <- `rownames<-`(sapply(df, function(x) names(df) %in% x), names(df))
ind <- which(tab, arr.ind = TRUE)
AinB <- data.frame(item = names(df)[ind[,2]], contains = names(df)[ind[,1]])
AinB
#> item contains
#> 1 cy1.CSV cy1.CSV
#> 2 cy1.CSV cy24.CSV
#> 3 cy1.CSV cy6.CSV
#> 4 cy2.CSV cy2.CSV
#> 5 cy24.CSV cy1.CSV
#> 6 cy24.CSV cy24.CSV
#> 7 cy24.CSV cy6.CSV
#> 8 cy3.CSV cy3.CSV
#> 9 cy6.CSV cy1.CSV
#> 10 cy6.CSV cy24.CSV
#> 11 cy6.CSV cy6.CSV
#> 12 dlt.CSV dlt.CSV
#> 13 dm.CSV dm.CSV
#> 14 dov.CSV dov.CSV
#> 15 dov.CSV dov_1.CSV
#> 16 dov_1.CSV dov_1.CSV
#> 17 ds.CSV ds.CSV
#> 18 ds.CSV ds_1.CSV
#> 19 ds_1.CSV ds.CSV
#> 20 ds_1.CSV ds_1.CSV
To find instances in which A is in B but not vice versa, we do the same thing except we are looking for the indices where tab is different from its transpose:
ind2 <- which(tab & !t(tab), arr.ind = TRUE)
AinBnotBinA <- data.frame(item = names(df)[ind2[,2]],
contains = names(df)[ind2[,1]])
AinBnotBinA
#> item contains
#> 1 dov.CSV dov_1.CSV
Created on 2020-11-25 by the reprex package (v0.3.0)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65009819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WkHtmlToPdf Unreadable Fonts I installed wkhtmltopdf in a VPS/Centos .
But it seems that it cannot find the fonts (I have all type1 and fonts-75dpi installed).
In php, this is the result of
exec(wkhtmltopdf http://www.google.com test.pdf);
A: This is the solution for Cento6
yum install libXext libXrender fontconfig libfontconfig.so.1
yum install urw-fonts
A: For if anyone interested, I solved my problems by installing true type fonts. After that wkhtmltopdf was able to display these fonts.
Ubuntu (18.04)
apt install fonts-droid-fallback ttf-dejavu fonts-freefont-ttf fonts-liberation ttf-ubuntu-font-family
Alpine Linux (3.9)
apk add ttf-dejavu ttf-droid ttf-freefont ttf-liberation ttf-ubuntu-font-family
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30738963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: App icon is not showing in CallKit UI I have configured my Provider Configuration for CallKit iOS. In which I have also set 'iconTemplateImageData' for displaying app icon in CallKit UI. But app icon is not showing. It shows a white square box.
Provider Configuration Code:
CXProviderConfiguration *configuration = [[CXProviderConfiguration alloc] initWithLocalizedName:[NSString stringWithFormat:@"%@\n", _title]];
configuration.maximumCallGroups = 1;
configuration.maximumCallsPerCallGroup = 1;
UIImage *callkitIcon = [UIImage imageNamed:@"AppIcon"];
configuration.iconTemplateImageData = UIImagePNGRepresentation(callkitIcon);
_callKitProvider = [[CXProvider alloc] initWithConfiguration:configuration];
[_callKitProvider setDelegate:self queue:nil];
_callKitCallController = [[CXCallController alloc] initWithQueue:dispatch_get_main_queue()];
I have used AppIcon images in 'Images.xcassets' with sizes: -
1x: 40*40, 2x: 80*80, 3x: 120*120
Please help why my app icon is not showing.
Thanks in advance.
A: This is likely because you are using your AppIcon image, which is a fully opaque image, i.e. no part of that image is transparent or has alpha=0.
To get the desired effect, you have to use a different image which is partly (or mostly) transparent. The native in-call UI will only use the alpha channel of the image you provide, so it ignores colors. I suggest following the example in the Speakerbox sample app and providing a secondary PNG image in your image asset catalog with transparency.
A: You need to use below code in order to set app name and app icon for incoming VOIP calls
let localizedName = NSLocalizedString("App-Name", comment: "Name of application")
let providerConfiguration = CXProviderConfiguration(localizedName: localizedName)
providerConfiguration.iconTemplateImageData = UIImage.init(named: "appicon-Name")?.pngData()
Note: Your app icon must be transparent. result will be like in below image
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45581940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: SSIS package fails when run as scheduled job but succeeds if run stand alone I've a Master package which has the scheduling of all the Jobs to run on a daily basis. Couple of my packages are failing when deployed on the server (its a file system deployment). The SSIS packages runs fine on my development machine or if run stand alone on the server., but strangely they fail when run as part of the scheduled job. I've SQL logging enabled and the error is pretty straightforward to interpret and sort out, however when I try to debug in the development environment it runs fine. I have an environment variable which holds the connection string and the SSIS package deployment is a file deployment with SQL logging enabled for all the Jobs. The problem is Im unable to replicate the error on my dev machine as the import takes place without any issue but its only when it runs as part of the scheduled job when it fails. Also it truncates the table fine but while importing the data it fails with data truncation error.
I'm unable to figure out what I'm missing here, any help will be very much appreciated.
SSIS sql error log from dbo.sysssislog table :
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 Beginning of package execution.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 Data conversion failed. The data conversion for column "vcrFlgActive" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 Data conversion failed. The data conversion for column "vcrFlgActive" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 The "output column "vcrFlgActive" (71)" failed because truncation occurred, and the truncation row disposition on "output column "vcrFlgActive" (71)" specifies failure on truncation. A truncation error occurred on the specified object of the specified component.
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 The "output column "vcrFlgActive" (71)" failed because truncation occurred, and the truncation row disposition on "output column "vcrFlgActive" (71)" specifies failure on truncation. A truncation error occurred on the specified object of the specified component.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 An error occurred while processing file "\Svrau530csm02.oceania.corp.anz.com\infra\Markets Finance\CFV IN\tblRefSD_GPL_Hierachy_BU_20141114.csv" on data row 2.
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 An error occurred while processing file "\Svrau530csm02.oceania.corp.anz.com\infra\Markets Finance\CFV IN\tblRefSD_GPL_Hierachy_BU_20141114.csv" on data row 2.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 SSIS Error Code DTS_E_PRIMEOUTPUTFAILED. The PrimeOutput method on component "Flat File Source" (1) returned error code 0xC0202092. The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing. There may be error messages posted before this with more information about the failure.
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 SSIS Error Code DTS_E_PRIMEOUTPUTFAILED. The PrimeOutput method on component "Flat File Source" (1) returned error code 0xC0202092. The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing. There may be error messages posted before this with more information about the failure.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 End of package execution.
A: The error message "The data conversion for column "vcrFlgActive" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page." would point to a data related problem: I would assume on the server, there is some data that is larger than the target column allows, but this is not there in your development environment.
E. g. a string of length 23 and your column crFlgActive has an SSIS DT_STR data type of length 20.
One way to find the data causing problems would be to configure the destination component to redirect records causing problems instead of failing. The redirection could be to a table, or maybe even just a CSV or Excel file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26920345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mongo join two collections and use aggregation im trying to get only those products for whom no order exists, so each product has an order id, these audit tables were linked to orders, but those orders are now deleted, i need to locate those products with no orders.
I know when doing aggregates if the joining collection has no records its not returning anything as "docs", but how can i get it to return me docs == empty or null only..
db.products.aggregate([
{
$match: {
$and: [
{ "docs": { $exists: false } }
]
}
},
{
$lookup: {
from: "orders",
localField: "orderId",
foreignField: "orderId",
as: "docs"
}
},
{
$unwind:
{
path: "$docs",
preserveNullAndEmptyArrays: true
}
},
{ $limit: 10 }
]).pretty()
A: db.products.aggregate([
{
$lookup: {
from: "orders",
localField: "orderId",
foreignField: "orderId",
as: "docs"
}
},
{ $match: { docs: [] },
{ $limit: 10 }
]).pretty()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67808764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Nginx rewrites parent rules with same key in sub-files? Accessing the /etc/nginx/nginx.conf file I have the following rule:
server {}
http {
access_log logs/access.log main;
error_log logs/error.log error;
include /etc/nginx/conf.d/*.conf;
In another file, called etc/nginx/conf.d/custom.conf, I have the code:
http {
blablabla …
When NGINX loads the settings, will the HTTP code block that was inside NGINX.CONF be “merged” with the settings included below or will it simply be replaced?
In this scenario for example, will the LOGS continue to be saved in the folder even if CUSTOM.CONF doesn't implement anything about it?
My current issue:
I can't see the logs that should be printed in the error/access.log files, remembering that my application is generating a 500 HTTP error.
A: Even if you can have more then a single http block you should not do it. But having an http block in another http block IS NOT ALLOWED and will raise an error on startup. Just tested this on my instance. So you should check the output of nginx -T and check the configuration.
The NGINX configuration works in an hierarchical order. Means a directive you set in the http context can be overwritten in the server or location context if supported.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69858552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is a controller not printing to console, when everything is most certainly running properly I have a main ViewController. I then added an extension (custom keyboard), and made a KeyboardViewController. In the viewDidLoad() method, I have tons of functions that are 100% running, and working properly. If I try t print anything to console using print() it doesn't work however, and I am stumped as to why it wouldn't.
Assuming it might have something to do with extension?
A: use (lldb) and po to print or display anything you want to console.
A: In case anyone runs into this, the problem is that the logging is happening from the main app, one solution is to run the extension, and all the print logs work as expected. Otherwise, you can also change debug settings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41754937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wp-admin list only parent posts When admin creates a post with five custom fields I creates 5 posts with post_parent id to main post. But these 5 posts are also showing in posts listing table which I want to hide.
In /wp-admin/edit.php where wordpress shows all posts (parent & child) under All/Publish I want to show only Parent posts having post_type = post because I am using other post types as well but only want to change view where post_type = post.
I knows for this I must need to edit core file, no matter I can. After searching in wp-admin/includes/class-wp-list-table.php I found
/**
* Generate the <tbody> part of the table
*
* @since 3.1.0
* @access protected
*/
function display_rows_or_placeholder() {
if ( $this->has_items() ) {
$this->display_rows();
} else {
list( $columns, $hidden ) = $this->get_column_info();
echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">';
$this->no_items();
echo '</td></tr>';
}
}
which creates rows for posts list table but I can not found where to set condition & custom query :
IF (post_type == 'post'){
// list only parent posts
}else{
// do default behavior
}
I searched almost 3hrs but no solution found. Okay if it is not possible then can we show same Hierarchy for posts like for Pages parent/child relation.
A: After approx 4hrs research I found wordpress: how to add hierarchy to posts
which seem that wordpress need to implement such feature.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20043345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XSLT: define node id I want to output some nodes. And some of them are defined as target nodes. Some are source nodes.
Input is like
<?xml version="1.0" encoding="UTF-8"?>
<Element type="node" id="Node-a" name="a"/>
<Element type="node" id="Node-b" name="b"/>
<Element type="node" id="Node-c" name="c"/>
......
First I tried this
<source node id="{generate-id()}"/>
<target node id="{generate-id()}"/>
It can output all of the nodes. But the problem is there are double nodes.
So I tried like this
<source node id="{generate-id(@source)}"/>
<target node id="{generate-id(@target)}"/>
However, after that I found the result could only output two nodes.
I want to ask how can I define the right node id, then I can separate them. Or should I define some variables? Please help me. Thanks.
A: First,
this is not valid:
<source node id="{generate-id()}"/>
the attribute node must have a value.
To answer your question, I would use the generate-id and position() functions on the target element to get a unique id. Something like this. Since I dont have a good input document, I created a sample:
<data>
<Element type="node" id="Node-a" name="a"/>
<Element type="node" id="Node-b" name="b"/>
<Element type="node" id="Node-c" name="c"/>
</data>
XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="data">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:for-each>
</xsl:template>
<xsl:template match="Element">
<xsl:element name="source">
<xsl:attribute name="node">
<xsl:value-of select="@type"/>
</xsl:attribute>
<xsl:attribute name="id">
<xsl:value-of select="generate-id(.)"/>
</xsl:attribute>
</xsl:element>
<xsl:element name="target">
<xsl:attribute name="node">
<xsl:value-of select="@type"/>
</xsl:attribute>
<xsl:attribute name="id">
<xsl:value-of select="concat(generate-id(.), '-', position())"/>
</xsl:attribute>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22812753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSIS powershell freezes installer I nedd to add ssl certificate to https binding in IIS inside NSIS installer. Inside powershell command works perfectly:
Get-ChildItem -path cert:\LocalMachine\My | Where-Object {$_.Subject -eq 'CN=WIN2012'} | New-Item 0.0.0.0!44334
But NSIS installer freezes when reach this script. I've tryed diffrent execution methods:
1) Like discribed in article
${PowerShellExec} "Get-ChildItem -path cert:\LocalMachine\My | Where-Object {$_.Subject -eq 'CN=WIN2012'} | New-Item 0.0.0.0!44334"
2)
nsExec::ExecToStack 'powershell -Command "Get-ChildItem -path cert:\LocalMachine\My | Where-Object {$_.Subject -eq \"CN=WIN2012\"} | New-Item 0.0.0.0!44334"'
Where is the problem? Any other powershell scripts works great.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39640747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Monotouch how do i implement a UITabBarController as my RootViewController I'm totally new to iOS programming using Monotouch... I'm using this code to create my navigation root view.
window = new UIWindow(UIScreen.MainScreen.Bounds);
UINavigationController rootNavController = new UINavigationController ();
window.RootViewController = rootNavController;
UIViewController tabView = new TabContainer ();
rootNavController.PushViewController (tabView, false);
My TabContainer class inherits the UITabBarController class and I have several UIViewControllers being added to the UITabBarController class.
var tabs = new UIViewController[] {
tab1, tab2, tab3, tab4, tab5
};
base.ViewControllers = tabs;
After clicking on one of the tabs, my ViewController will load with a UITableView inside it and i can still see the TabBarController at the bottom. If i now click on any of the table cells i am pushing a new view and the TabBarController is hidden.
tblSource.OnRowSelected += (object sender, TableSourceStationGroup.RowSelectedEventArgs e) => {
e.tableView.DeselectRow (e.indexPath, true);
stationView = new viewStation (itemList[e.indexPath.Row].Name, itemList[e.indexPath.Row].Id, itemList[e.indexPath.Row].Stations);
this.NavigationController.PushViewController(stationView, true);
How can i keep the TabBarController from hiding when I push a new view? I think i am missing something fundamental here about the structure of my application.
A: You want to setup your hierarchy like this:
Tab1 -> Nav1 -> View
Root --> Tab Controller -> Tab2 -> Nav2 -> View
Tab3 -> Nav3 -> View
So each tab will have it's own Nav controller, which will have an initial view pushed onto it.
In your example you have your Nav controller as the root, containing the Tab controller. This is backwards - you want the Tab controller to contain the Nav controllers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19453273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Undefined reference to a local class I've just played with qjson library and got "undefined reference" error. This is the code:
#include <qjson/qobjecthelper.h>
#include <qjson/serializer.h>
class Person: public QObject {
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(Gender gender READ gender WRITE setGender)
Q_ENUMS(Gender)
public:
Person(QObject *parent = 0);
~Person();
QString name() const;
void setName(const QString &name);
enum Gender{Male, Female};
Gender gender() const;
void setGender(Gender gender);
private:
QString m_name;
Gender m_gender;
};
int main ()
{
Person person;
QJson::Serializer serializer;
person.setName("Nick");
person.setGender(Person::Male);
QVariantMap person_map = QJson::QObjectHelper::qobject2qvariant(&person);
QByteArray json = serializer.serialize(person_map);
return 0;
}
So, compiler says that undefined reference to Person::Person and all other functions in Person class. Why?
A: You have only declared the methods of the class. You also need to define (i.e. implement) them. At the moment, how should the compiler know the constructor of Person is supposed to do?
A: You need to link with the library or object file that implements class Person.
If you have a libqjson.a file on a Unix variant, you need to add -lqjson to your link command line. If you're on Windows with qjson.lib, you need to link with qjson.lib. If you have a .cpp file that implements Person, you need to compile it and link it with your executable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3717839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Struts 2 redirect to another jsp I use struts 2 in my java web project. I want to redirect Action success to another jsp but it's not working.
Here is my code:
public class ConfigurerDureeStockageAction extends ActionSupport implements ServletRequestAware{
private final static Logger logger = Logger.getLogger(ConfigurerDureeStockageAction.class);
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request){
this.request = request;
}
public String execute()throws Exception{
logger.debub("Execute SUCCESS");
return SUCCESS;
}
public String savePeriod(){
logger.debub("savePeriod SUCCESS");
return SUCCESS;
}
}
My struts.xml is
<action name="AdminIndex" class="fr.si2m.occ.web.actions.admin.AdminIndexAction"
method="execute">
<result name="success">adminIndex.jsp</result>
</action>
<action name="ConfigurerDureeStockageSave" class="fr.si2m.occ.web.actions.admin.ConfigurerDureeStockageAction"
method="savePeriod">
<result name="success">adminIndex.jsp</result>
</action>
I try this
<action name="ConfigurerDureeStockageSave" class="fr.si2m.occ.web.actions.admin.ConfigurerDureeStockageAction"
method="savePeriod">
<result name="success" type="redirect">
<param name="location">adminIndex.jsp</param >
</result>
</action>
and this
<action name="ConfigurerDureeStockageSave" class="fr.si2m.occ.web.actions.admin.ConfigurerDureeStockageAction"
method="savePeriod">
<result name="success" type="redirect">
<param name="actionName">AdminIndex</param>
</result>
</action>
This last configuration gives me the following error:
Caught OgnlException while setting property 'actionName' on type 'org.apache.struts2.dispatcher.ServletRedirectResult'.
Caught OgnlException while setting property 'actionName' on type 'org.apache.struts2.dispatcher.ServletRedirectResult'. - Class: ognl.ObjectPropertyAccessor
File: ObjectPropertyAccessor.java
Method: setProperty
Line: 166 - ognl/ObjectPropertyAccessor.java:166:-1
at com.opensymphony.xwork2.ognl.OgnlUtil.internalSetProperty(OgnlUtil.java:430)
at com.opensymphony.xwork2.ognl.OgnlUtil.setProperty(OgnlUtil.java:160)
at com.opensymphony.xwork2.ognl.OgnlReflectionProvider.setProperty(OgnlReflectionProvider.java:91)
at com.opensymphony.xwork2.ObjectFactory.buildResult(ObjectFactory.java:233)
at com.opensymphony.xwork2.DefaultActionInvocation.createResult(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:368)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:278)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:236)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:236)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:662)
Caused by: ognl.NoSuchPropertyException: org.apache.struts2.dispatcher.ServletRedirectResult.actionName
at ognl.ObjectPropertyAccessor.setProperty(ObjectPropertyAccessor.java:166)
at com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.setProperty(ObjectAccessor.java:27)
at ognl.OgnlRuntime.setProperty(OgnlRuntime.java:2315)
at ognl.ASTProperty.setValueBody(ASTProperty.java:127)
at ognl.SimpleNode.evaluateSetValueBody(SimpleNode.java:220)
at ognl.SimpleNode.setValue(SimpleNode.java:301)
at ognl.Ognl.setValue(Ognl.java:737)
at com.opensymphony.xwork2.ognl.OgnlUtil.setValue(OgnlU
12:12:06,608 INFO [STDOUT] til.java:217)
at com.opensymphony.xwork2.ognl.OgnlUtil.setValue(OgnlUtil.java:209)
at com.opensymphony.xwork2.ognl.OgnlUtil.internalSetProperty(OgnlUtil.java:423)
... 72 more
Always not working.
My questions are:
1- Why the configuration <result name="success">adminIndex.jsp</result> does not work ?
2- Why the configuration
<result name="success" type="redirect">
<param name="location">adminIndex.jsp</param >
</result>
does not work ?
3- Why i am getting the error with the configuration
<result name="success" type="redirect">
<param name="actionName">AdminIndex</param>
</result>
?
The AdminIndex action is declared in struts.xml. I am confused.
Someone could help me please ?
A: your problem is that you shouldn't use property <param name="actionName">AdminIndex</param>, here is the solution:
<result name="success" type="redirectAction">
<param name="actionName">AdminIndex</param>
</result>
regarding to the doc Struts2 Redirect Action Result Type, you should use redirectAction instead redirect
Answer to your questions:
*
*please give us more detail.
*try this (assuming that your namespace config is correct):
<action name="ConfigurerDureeStockageSave" class="fr.si2m.occ.web.actions.admin.ConfigurerDureeStockageAction" method="savePeriod">
<result name="success" type="redirect">
<param name="location">adminIndex.action</param >
</result>
</action>
or
<action name="ConfigurerDureeStockageSave" class="fr.si2m.occ.web.actions.admin.ConfigurerDureeStockageAction" method="savePeriod">
<result name="success">
<param name="location">adminIndex.jsp</param >
</result>
</action>
*because result type redirect doesn't have property actionName, you should use redirectAction result type, which has this property
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12492785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible for a proxy server to forge it's certificate SSL Pinning? If a client receives a server's certificate typically during handshake, why can't a man in the middle attack proxy client just use the same certificate that will be sent from an authentic server?
Certificates are meant to be public, if I'm not mistaken?
like twitter https://dev.twitter.com/overview/api/ssl
A: Simply because the server doesn't only send the certificate; it also proves that its the "owner" of the certificate; speaking simplified here:
The server encrypts something that you can decrypt using the certificate, but only the owner of the certificate could encrypt that way.
Assuming you know the public/private key crypto pattern, the certificate contains a public key that can decrypt data that was encrypted with the server's private key. The server will never ever hand out the private key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32931224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Joint query across 2 models (has_many) Hi I need help and all insight appreciated. I have two models Auctions and Bids and I want to retrieve the All auctions current_user won, the ones s/he has been outbid on and the ones s/he's winning
Here are the two models:
class Auction < ActiveRecord::Base
extend FriendlyId
friendly_id :guid, use: :slugged
before_save :populate_guid
mount_uploaders :images, ImageUploader
belongs_to :client
has_many :bids, dependent: :destroy
has_one :order, dependent: :destroy
validates_presence_of :title, :lien_price,
:end_time, :collateral_value,
:redemption_date, :current_interest_rate,
:additional_tax, :collateral_details,
:location, :client_id, :starting_bid
validate :end_time_in_the_future, :on => :update
validates_uniqueness_of :guid, case_sensitive: false
def end_time_in_the_future
errors.add(:end_time, "can't be in the past") if self.end_time && self.end_time < Time.now
end
def self.get_active_auctions
where("end_time > ?", Time.now)
end
def self.closed_auctions
where("end_time < ?", Time.now)
end
def highest_bid
self.bids.maximum("amount")
end
def highest_bid_object
self.bids.order(:amount => :desc).limit(1).first
end
def highest_bidder
self.highest_bid_object.user if highest_bid_object
end
def closed?
self.end_time < Time.now
end
private
def populate_guid
if new_record?
while !valid? || self.guid.nil?
self.guid = SecureRandom.random_number(1_000_000_000).to_s(36)
end
end
end
end
and
class Bid < ActiveRecord::Base
extend FriendlyId
friendly_id :guid, use: :slugged
belongs_to :auction
belongs_to :user
before_save :populate_guid
validates_presence_of :amount, :user_id,
:auction_id
#validate :higher_than_current?
validates :amount, :numericality => true
validates_uniqueness_of :guid, case_sensitive: false
def higher_than_current?
if !Bid.where("amount > ? AND auction_id = ?", amount, self.auction.id).empty?
errors.add(:amount, "is too low! It can't be lower than the current bid, sorry.")
end
end
private
def populate_guid
if new_record?
while !valid? || self.guid.nil?
self.guid = SecureRandom.random_number(1_000_000_000).to_s(36)
end
end
end
end
I thought
@auctions = Auction.closed_auctions.where(highest_bidder: current_user)
or
@auctions = Auction.closed_auctions.joins(:bids).where(highest_bidder: current_user)
would work but they both raise an error.
Edit this works
@auctions = Auction.closed_auctions.references(highest_bidder: current_user)
But there's probably a better way.
A: You probably can't access current_user from controller (devise?). So you need to pass the user as a parameter to the class or instance method. What you should look into are scopes and especially scopes that accept parameters. Scopes could really help you refactor your Auction model (you really don't need any methods that only return a where()), but also solve the inaccessible current_user.
Use it like this in your Auction model:
scope: :highest_bidder -> (current_user) { where(highest_bidder: current_user) }
And call it like this from your controller:
@auctions = Auction.closed_auctions.highest_bidder(current_user)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34143556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Poi-ooxml-schema source or jar for document only I am doing the document conversion using the poi.
For that i am using poi-ooxml-schemas-3.9.jar which is contains sheet and powerpoint classes and beans. I want separate the document classes and bean.
There is no source for poi-ooxml-schemas-3.9 so that I can't separate the package and beans.
How to generate the build.xml or any source for generate the document classes and beans?
Simply I want generate the poi-ooxml-schema as my wish.
A: There is source available for the ooxml schemas! It's covered in the POI FAQ
The schema classes are auto-generated by xmlbeans from the specification, but you can get the auto-generated sources if you want. Depending on your needs, you can either use the ant build file to generate them, or download the pre-generated ones from Maven central. The FAQ covers both options
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18628795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Url based wildcard redirect with exempted url I'm no PHP expert. Just want to know if this is possible.
I'm trying to exempt a url from a php wildcard redirect but I am not able to add the exemption.
I used php case switch
Here's my current code.
$uri = $_SERVER['REQUEST_URI'];
switch($uri)
{
case '/admin':
header('Location: https://'. $_SERVER['HTTP_HOST'] . '/admin-page?Redirect');
break;
case $uri != '/':
header('Location: https://'. $_SERVER['HTTP_HOST'] . '/index.php');
break;
}
Was hoping exempt the url/admin from the wildcard redirect but even that gets redirected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57675546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Memory Leak in QWebEngineView I am trying to make a window with a QWebEngineView, and delete the QWebEngineView after the window closes. However, the QWebEngineView never seems to get deleted, and keeps running any QUrl I have loaded (e.g. a YouTube video). In my program, I have a QMainWindow with a Line Edit and a Push Button, that creates a window that loads the URL entered by the user. Here is my code:
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "subwindow.h"
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
void init();
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
SubWindow *sub;
};
#endif // MAINWINDOW_H
SubWindow.h
#ifndef SUBWINDOW_H
#define SUBWINDOW_H
#include <QMainWindow>
#include <QtWebEngineWidgets/qwebengineview.h>
#include <QTimer>
namespace Ui
{
class SubWindow;
}
class SubWindow : public QMainWindow
{
Q_OBJECT
public:
explicit SubWindow(QWidget *parent = 0);
void doWeb(QString link);
~SubWindow();
private:
Ui::SubWindow *ui;
QWebEngineView *web;
private slots:
void on_pushButton_clicked();
};
#endif // SUBWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
void MainWindow::init()
{
this->showMaximized();
sub = new SubWindow(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
sub->doWeb(ui->lineEdit->text());
}
SubWindow.cpp
#include "subwindow.h"
#include "ui_subwindow.h"
SubWindow::SubWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SubWindow)
{
ui->setupUi(this);
}
void SubWindow::doWeb(QString link)
{
this->show();
web = new QWebEngineView(this);
ui->verticalLayout->addWidget(web);
web->load(QUrl(link, QUrl::TolerantMode));
web->show();
}
SubWindow::~SubWindow()
{
delete web; //Doesn't seem to work, since memory is still allocated in task manager
delete ui;
}
void SubWindow::on_pushButton_clicked()
{
this->close(); //Artifact for testing purposes.
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.init();
return a.exec();
}
I have also tried using "web->close();" (which I put on the line where I have the testing artifact) in conjunction with
"web->setAttribute(Qt::WA_DeleteOnClose);" (which I put after "web = new QWebEngineView(this);"), but that didn't solve my issue either. Anyone know what I am doing wrong?
A: OK, apparently I needed to call "web->deleteLater();" before calling
"this->close();". The "delete web;" was uneeded. Still, I'd like to know why delete doesn't work in this case...
A: You are creating QWebEngineView with parent "this" (owner) so you don't have to delete it yourself, it will be automatically deleted when it parent will. See Qt documentation about memory management :
http://doc.qt.io/qt-5/objecttrees.html
it is also dangerous doing that, because if you don't create the QWebEngineView object using doWeb(QString link), you will try to delete something that doesn't exist and therefore it can lead you to undefined behavior.
remove delete web from your destructor and see if you always have the problem.
Edit :
The reason why it is not destroyed : you aren't destroying SubWindow Object (the owner of QWebEngineView Object). You can Verify it yourself by printing something in the destructor.
If you were destroying SubWindow object, the second time you push the button in MainWindow, your application will crashes. Since you aren't creating the SubWindow object inside your function on_push_button, but inside MainWindow::init. Your SubWindow Object is only hidden and not destroyed. It is destroyed only when you close the MainWindow. You are also Creating an instance of QWebEngineview each time you show sub (SubWindow Object), so if you show sub 3 times you will have 3 QWebEngineView inside your Subwindow.
the changes i would do to the code :
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "subwindow.h"
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
SubWindow* sub;
};
#endif
mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow), sub(new SubWindow(this))
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
sub->show();
sub->doWeb(ui->lineEdit->text());
}
subWindow.h
#ifndef SUBWINDOW_H
#define SUBWINDOW_H
#include <QMainWindow>
#include <QtWebEngineWidgets/qwebengineview.h>
#include <QTimer>
namespace Ui
{
class SubWindow;
}
class SubWindow : public QMainWindow
{
Q_OBJECT
public:
explicit SubWindow(QWidget *parent = 0);
void doWeb(QString link);
~SubWindow();
private:
Ui::SubWindow *ui;
QWebEngineView *web;
private slots:
void on_pushButton_clicked();
};
#endif // SUBWINDOW_H
subWindow.cpp
#include "subwindow.h"
#include "ui_subwindow.h"
SubWindow::SubWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SubWindow),
web(new QWebEngineView(this))
{
ui->setupUi(this);
ui->verticalLayout->addWidget(web);
}
void SubWindow::doWeb(QString link)
{
web->load(QUrl(link, QUrl::TolerantMode));
}
SubWindow::~SubWindow()
{
delete ui;
}
void SubWindow::on_pushButton_clicked()
{
this->close(); //Artifact for testing purposes.
}
Note that i am also not destroying subWindow object, but i m not creating QWebView each time i call the method SubWindow::doWeb(String).
If it was up to me i would use a Subclassed Dialog that is not a member of MainWindow, the object would be created inside MainWindow::on_pushButton_clicked() and destroyed when i finish using it.
A: Looks like something was not closed correctly.
I was using Qt 5.15 using the kit MSVC2019 32bit compiler. But Visual Studio 2017 (and not 2019) was installed on my computer. Thus, the compiler detected in Qt creator -> project -> manage kit -> compiler was the one of MSVC2017 i.e : Microsoft visual C++ compiler 15.8 (x86).
The solution is to install visual Studio 2019 and then replace Qt creator by the correct compiler (2019) i.e: Microsoft visual c++ compiler 16.7 (X86).
Then I could compile without any leak of memory anymore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42463581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: passing argument to DialogFragment I need to pass some variables to DialogFragment, so I can perform an action. Eclipse suggests that I should use
Fragment#setArguments(Bundle)
But I don't know how to use this function. How can I use it to pass variables to my dialog?
A: So there is two ways to pass values from fragment/activity to dialog fragment:-
*
*Create dialog fragment object with make setter method and pass value/argument.
*Pass value/argument through bundle.
Method 1:
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
dialog.setValue(header, body);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
public void setValue(String header, String body) {
this.header = header;
this.body = body;
}
// use above variable into your dialog fragment
}
Note:- This is not best way to do
Method 2:
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
Bundle bundle = new Bundle();
bundle.putString("header", "Header");
bundle.putString("body", "Body");
dialog.setArguments(bundle);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
header = getArguments().getString("header","");
body = getArguments().getString("body","");
}
}
// use above variable into your dialog fragment
}
Note:- This is the best way to do.
A: as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle.
the built-in method for that in the Fragment class is setArguments(Bundle) and getArguments().
basically, what you do is set up a bundle with all your Parcelable items and send them on.in turn, your Fragment will get those items in it's onCreate and do it's magic to them.
the way shown in the DialogFragment link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually.
A: Using newInstance
public static MyDialogFragment newInstance(int num) {
MyDialogFragment f = new MyDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
And get the Args like this
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("num");
...
}
See the full example here
http://developer.android.com/reference/android/app/DialogFragment.html
A: I used to send some values from my listview
How to send
mListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Favorite clickedObj = (Favorite) parent.getItemAtPosition(position);
Bundle args = new Bundle();
args.putString("tar_name", clickedObj.getNameTarife());
args.putString("fav_name", clickedObj.getName());
FragmentManager fragmentManager = getSupportFragmentManager();
TarifeDetayPopup userPopUp = new TarifeDetayPopup();
userPopUp.setArguments(args);
userPopUp.show(fragmentManager, "sam");
return false;
}
});
How to receive inside onCreate() method of DialogFragment
Bundle mArgs = getArguments();
String nameTrife = mArgs.getString("tar_name");
String nameFav = mArgs.getString("fav_name");
String name = "";
// Kotlin upload
val fm = supportFragmentManager
val dialogFragment = AddProgFargmentDialog() // my custom FargmentDialog
var args: Bundle? = null
args?.putString("title", model.title);
dialogFragment.setArguments(args)
dialogFragment.show(fm, "Sample Fragment")
// receive
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (getArguments() != null) {
val mArgs = arguments
var myDay= mArgs.getString("title")
}
}
A: Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:
so you have to create a companion objet to create new newInstance function
you can set the paremter of the function whatever you want.
using
val args = Bundle()
you can set your args.
You can now use args.putSomthing to add you args which u give as a prameter in your newInstance function.
putString(key:String,str:String) to add string for example and so on
Now to get the argument you can use
arguments.getSomthing(Key:String)=> like arguments.getString("1")
here is a full example
class IntervModifFragment : DialogFragment(), ModContract.View
{
companion object {
fun newInstance( plom:String,type:String,position: Int):IntervModifFragment {
val fragment =IntervModifFragment()
val args = Bundle()
args.putString( "1",plom)
args.putString("2",type)
args.putInt("3",position)
fragment.arguments = args
return fragment
}
}
...
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fillSpinerPlom(view,arguments.getString("1"))
fillSpinerType(view, arguments.getString("2"))
confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int) {
val datep= DateT(year,monthOfYear,dayOfMonth)
updateDateInView(datep.date)
}
}
}
...
}
Now how to create your dialog you can do somthing like this in another class
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
like this for example
class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.btn_update!!.setOnClickListener {
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
}
...
}
..
}
A: In my case, none of the code above with bundle-operate works; Here is my decision (I don't know if it is proper code or not, but it works in my case):
public class DialogMessageType extends DialogFragment {
private static String bodyText;
public static DialogMessageType addSomeString(String temp){
DialogMessageType f = new DialogMessageType();
bodyText = temp;
return f;
};
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] choiseArray = {"sms", "email"};
String title = "Send text via:";
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title).setItems(choiseArray, itemClickListener);
builder.setCancelable(true);
return builder.create();
}
DialogInterface.OnClickListener itemClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
prepareToSendCoordsViaSMS(bodyText);
dialog.dismiss();
break;
case 1:
prepareToSendCoordsViaEmail(bodyText);
dialog.dismiss();
break;
default:
break;
}
}
};
[...]
}
public class SendObjectActivity extends FragmentActivity {
[...]
DialogMessageType dialogMessageType = DialogMessageType.addSomeString(stringToSend);
dialogMessageType.show(getSupportFragmentManager(),"dialogMessageType");
[...]
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15459209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "134"
} |
Q: Records don't load into edit page after update query I'm stumped on this one... I'm using the following code to load a record into a form for editing. The record loads fine into the fields etc. I click submit and the record doesn't reload. If I use edit_link.php?link_pk=50 in the url, the record doesn't load. If I change the value to an unedited record it loads fine into the form, but if I edit that record, the same thing happens. The data looks exactly the same in the database as it did before it was edited (ie I'm not changing anything before I submit):
$link_pk = $_GET['link_pk'];
$author_pk = $_GET['author_pk'];
$title = $_POST['title'];
$url = mysql_real_escape_string($_POST['url']);
$url_for_link = $_POST['url'];
$alt = $_POST['alt'];
$credit = $_POST['credit'];
$sub_discipline_fk = $_POST['sub_discipline'];
$link_category_fk = $_POST['category'];
$icon = $_POST['icon'];
$query_link = "SELECT * FROM link, sub_discipline, link_category, link_icon WHERE link.sub_discipline_fk = sub_discipline.sub_discipline_pk AND link.link_category_fk = link_category.link_category_pk AND link.link_icon_fk = link_icon.link_icon_pk AND link.link_pk = '$link_pk'";
$result_link = mysql_query($query_link, $connection) or die(mysql_error());
$row_link = mysql_fetch_assoc($result_link);
switch ($icon) {
case '1':
$link = mysql_real_escape_string("<a class='text' href='" . $url_for_link . "' target='_blank' alt='" . $alt . "' >" . $title . "</a>");
break;
case '2':
$link = mysql_real_escape_string("<a class='video' href='" . $url_for_link . "' target='_blank' alt='" . $alt . "' >" . $title . "</a>");
break;
case '3':
$link = mysql_real_escape_string("<a class='interactive' href='" . $url_for_link . "' target='_blank' alt='" . $alt . "' >" . $title . "</a>");
break;
case '4':
$link = mysql_real_escape_string("<a class='microscope' href='" . $url_for_link . "' target='_blank' alt='" . $alt . "' >" . $title . "</a>");
break;
}
if(isset($_POST['submit'])){
$query = "UPDATE link SET link_title = '$title', url = '$url', link = '$link', alt = '$alt', credit = '$credit', sub_discipline_fk = '$sub_discipline_fk', updated = NOW(), updated_by = '$author_pk', link_category_fk = '$link_category_fk', link_icon_fk = '$link_icon_fk' WHERE link_pk = '$link_pk'";
$result = mysql_query($query, $connection) or die(mysql_error());
if($result){
$query_link = "SELECT * FROM link, sub_discipline, link_category, link_icon WHERE link.sub_discipline_fk = sub_discipline.sub_discipline_pk AND link.link_category_fk = link_category.link_category_pk AND link.link_icon_fk = link_icon.link_icon_pk AND link.link_pk = '$link_pk'";
$result_link = mysql_query($query_link, $connection) or die(mysql_error());
$row_link = mysql_fetch_assoc($result_link);
$message = '- The link has been updated';
}
}
Please do not remind me that the above is depricated, I'm aware of that.
Thanks
A: Stupid mistake...I changed a variable name and didntt change it in the query... link_icon_fk = '$link_icon_fk' should have been link_icon_fk = '$icon' - trying to work too fast...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14679538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Even if a state has been changed, but the view has not been rendered again in React / Next.js Even if a state has been changed, but the view has not been rendered again in React / Next.js.
Here is my code and console.log result.
As a prerequisite, I think I understand the behavior of useState, useEffect, Promise, and async/await, but I couldn't figure it out any more on my own.
The return value of GetGithubData is Promise, so I'm wondering if that's the reason why the update doesn't run simply because I can't access the object inside. However, if that is the case, in order to resolve Promise, I have to add "await", and in order to do so, I have to change to the function to "async" function, and when I change it to the async function, I get an error if the "return" returns an object, and the radar chart is not displayed in the first place.
Can someone please tell me how to fix this? I've seen a few similar questions, but none of them seemed to fit.
Radarchart.tsx code is below, which is a component drawing a radarchart graph like this. And this graph itself is successfully drawn in my browser but the number of commit to Github is still 20 instead of 12, which means the result of useEffect is not rendered again.
import React, { useEffect, useState } from "react";
import {
Chart,
LineElement,
PointElement,
RadialLinearScale,
} from "chart.js";
import { Radar } from "react-chartjs-2";
import GetGithubData from "../services/githubService";
const RadarChart = () => {
const [githubData, setGithubData] = useState({});
useEffect(() => {
setGithubData(GetGithubData());
}, []);
const randomNumber1 = githubData["total"] ? githubData["total"] : 20;
console.log(githubData);
console.log(randomNumber1);
const randomNumber2 = 35;
const randomNumber3 = 45;
const randomNumber4 = 75;
const randomNumber5 = 85;
const data = {
datasets: [
{
data: [
randomNumber1,
randomNumber2,
randomNumber3,
randomNumber4,
randomNumber5,
],
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "rgba(255, 99, 132, 1)",
},
],
};
Chart.register(
LineElement,
PointElement,
RadialLinearScale,
);
return <Radar data={data} options={options} />;
};
export default RadarChart;
githubService.tsx is a service file to fetch data that I want to fetch from Github API.
const GetGithubData = async () => {
const owner = "aaaa";
const repo = "bbbb";
const url = `https://api.github.com/repos/${owner}/${repo}/stats/contributors`;
const response = await fetch(url);
const data = await response.json();
return data[0];
};
export default GetGithubData;
The result of console.log are below.
A: GetGithubData is an async function, meaning it implicitly returns a Promise. You are saving the Promise object into the githubData state.
useEffect(() => {
setGithubData(GetGithubData());
}, []);
You are correct that you need to await it resolving.
You can chain from the returned promise and call setGithubData in the .then block with the returned value:
useEffect(() => {
GetGithubData()
.then(data => {
setGithubData(data);
});
}, []);
Or create an async function in the useEffect hook and await the value.
useEffect(() => {
const getGitHubData = async () => {
const data = await GetGithubData();
setGithubData(data);
};
getGitHubData();
}, []);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70811783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't add CefSharp to my toolbox I'm currently trying to add CefSharp to my tools so that I can drag and drop a webbrowser onto my form.
I installed CefSharp via NuGet in Visual Studio 2013.
I then right-clicked the tools section and selected "Choose Items"
In the ".NET Framework Components" I selected browse and click on CefSharp.wpf.dll
I then get this error
How can I add the CefSharp browser to my toolbox in Visual Studio 2013?
A: Not supported, see this FAQ item: https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#Wpf_designer
You have to edit the small bit of XAML that's needed by hand in Visual Studio.
Apart from the projects MinimalExample repository on GitHub there is also a tutorial taking you through the initial steps at http://www.codeproject.com/Articles/881315/Display-HTML-in-WPF-and-CefSharp-Tutorial-Part
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29999542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Detect speaker/headset using AudioUnit on Mac OS X Using AudioUnit and kAudioUnitSubType_HALOutput how do I detect if the output is Speaker or Headset?
A: bool usingInternalSpeakers()
{
AudioDeviceID defaultDevice = 0;
UInt32 defaultSize = sizeof(AudioDeviceID);
const AudioObjectPropertyAddress defaultAddr = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultAddr, 0, NULL, &defaultSize, &defaultDevice);
AudioObjectPropertyAddress property;
property.mSelector = kAudioDevicePropertyDataSource;
property.mScope = kAudioDevicePropertyScopeOutput;
property.mElement = kAudioObjectPropertyElementMaster;
UInt32 data;
UInt32 size = sizeof(UInt32);
AudioObjectGetPropertyData(defaultDevice, &property, 0, NULL, &size, &data);
return data == 'ispk';
}
int main(int argc, const char * argv[])
{
if (usingInternalSpeakers())
printf("I'm using the speakers!");
else
printf("i'm using the headphones!");
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15728513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alternative to onActivityResult for startUpdateFlowForResult What is the alternative to get callback for startUpdateFlowForResult in InAppUpdates instead of onActivityResult since it is deprecated?
A: We have to wait for Google Play team to migrate away from the deprecated APIs. You can follow this issue on Google's Issue Tracker.
A: Create this result launcher
private val updateFlowResultLauncher =
registerForActivityResult(
ActivityResultContracts.StartIntentSenderForResult(),
) { result ->
if (result.resultCode == RESULT_OK) {
// Handle successful app update
}
}
After that try to launch your intent like this
val starter =
IntentSenderForResultStarter { intent, _, fillInIntent, flagsMask, flagsValues, _, _ ->
val request = IntentSenderRequest.Builder(intent)
.setFillInIntent(fillInIntent)
.setFlags(flagsValues, flagsMask)
.build()
updateFlowResultLauncher.launch(request)
}
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
AppUpdateType.FLEXIBLE,
starter,
requestCode,
)
Give it a try!
A: You can use below code snippet alternative of onActivityResult()
First Activity
Step 1
private val openActivity =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
handleActivityResult(REQUEST_CODE, it)
}
Step 2
openActivity.launch(
Intent(this, YourClass::class.java).apply {
putExtra(ANY_KEY, data) // If any data you want to pass
}
)
Step 3
private fun handleActivityResult(requestCode: Int, result: ActivityResult?) {
Timber.e("========***handleActivityResult==requestActivty==$requestCode====resultCode=========${result?.resultCode}")
if (requestCode == REQUEST_CODE) {
when (result?.resultCode) {
Activity.RESULT_OK -> {
val intent = result.data // received any data from another avtivity
}
Activity.RESULT_CANCELED->{
}
}
}
}
In second class
val intent = Intent()
intent.putExtra(ANY_KEY, data)
setResult(Activity.RESULT_OK, intent)
finish()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69739094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Access POST vars - Java EE Servlet How can i access my POST vars in my servlet ?
I tried
String login = (String) request.getAttribute("login");
String password = (String) request.getAttribute("password");
My HTML form
<form action="login" class="form-group" method="POST" style="width: 300px;">
Nom d'utilisateur <input type="text" name="login" class="form-control" />
Mot de passe <input type="password" name="password" class="form-control"/>
<input type="submit" class="btn btn-primary" value="Login"/>
</form>
A: They are parameters, not attributes, use ServletRequest#getParameter instead:
String login = request.getParameter("login");
String password = request.getParameter("password")
A: You can use the getParameter method getParameter
String login = request.getParameter("login");
String password = request.getParameter("password");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22183655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accordion in Asp.Net MVC using html, css and JS Trying to implement an accordion in my application. The accordion itself displays correctly but upon clicking the '+' to open up the description, this is where nothing happens. When user clicks on each '+' , the tab should open to display the corresponding description. Can anyone see whats causing it to not work? see below code.
HTML (Just a snippet of one of the tabs)
<div class="accord-tab-box">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="accordion-box">
<div class="accord-elem">
<div class="accord-title">
<h5><i class="fa fa-money fa-fw"></i>Software Development</h5>
<a class="accord-link" href="#"></a>
</div>
<div class="accord-content">
<p>IT related have a team of software developers who are skilled in Open source Java, Spring, Hibernate, Struts, GWT; DotNet framework and have written many web based systems:<br />• Requisition system<br />• Tender management system <br />•
Invoice tracking system<br />• Our team has more than 20 years experience in Software development life cycle. Reference sites: <br />• KZN Department of Works;<br />• KZN Department Of Education;<br />• EC DEDEAT;<br /><br />• Neha Shipping;<br
/><br />• SJS Consulting<br /> </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
CSS
.container .content {}
hr,
.borderedbox {
border-color: #D7D7D7;
}
.inspace-5 {
padding: 5px;
}
.imgl {
margin: 0 15px 10px 0;
clear: left;
}
.imgr {
margin: 0 0 10px 15px;
clear: right;
}
.fl_left,
.imgl {
float: left;
}
.fl_right,
.imgr {
float: right;
}
.borderedbox {
border: 1px solid;
border-color: darkgray;
}
.accord-tab-box {
padding-top: 40px;
padding-bottom: 20px;
}
.accordion-box {
margin-bottom: 20px;
}
.accord-elem {
margin-bottom: 20px;
}
.accord-title {
padding: 16px 14px;
border: 1px solid #dbdbdb;
position: relative;
}
.accord-title h5 {
padding-right: 48px;
}
.accord-title h5 i {
color: #007aff;
font-size: 20px;
vertical-align: middle;
margin-right: 12px;
}
a.accord-link {
display: inline-block;
position: absolute;
width: 46px;
height: 100%;
top: 0;
right: 0;
border-left: 1px solid #dbdbdb;
background: url('/Content/MyTemplate/images/add.png') center center no-repeat;
transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-webkit-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
}
.accord-elem.active a.accord-link {
background: url('/Content/MyTemplate/images/substract.png') center center no-repeat;
}
a.accord-link.opened {
background: url('/Content/MyTemplate/images/substract.png') center center no-repeat;
}
.accord-content {
display: none;
padding: 22px;
border: 1px solid #dbdbdb;
border-top: none;
overflow: hidden;
}
.accord-content span.image-content {
display: inline-block;
float: left;
width: 68px;
height: 68px;
border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-o-border-radius: 50%;
margin-right: 22px;
background: #007aff;
}
.accord-content span.logo-content {
display: inline-block;
float: left;
width: 110px;
margin-right: 15px;
}
.accord-content span.image-content i {
color: #fff;
font-size: 30px;
text-align: center;
width: 100%;
line-height: 68px;
vertical-align: middle;
}
.accord-content span.logo-content i {
color: #fff;
font-size: 30px;
text-align: center;
width: 100%;
line-height: 68px;
vertical-align: middle;
}
.accord-elem.active .accord-content {
display: block;
}
.why-convertible-box {
padding-top: 60px;
}
.why-convertible-box h1 {
margin-bottom: 10px;
}
.why-convertible-box h1 span {
font-weight: 600;
}
.why-convertible-box h1 i {
color: #0a9dbd;
margin-left: 10px;
}
.why-convertible-box p {
margin-bottom: 15px;
}
.why-convertible-box p a {
color: #0076f9;
font-weight: 700;
}
JS
var clickElem = $('a.accord-link');
clickElem.on('click', function (e) {
e.preventDefault();
var $this = $(this),
parentCheck = $this.parents('.accord-elem'),
accordItems = $('.accord-elem'),
accordContent = $('.accord-content');
if (!parentCheck.hasClass('active')) {
accordContent.slideUp(400, function () {
accordItems.removeClass('active');
});
parentCheck.find('.accord-content').slideDown(400, function () {
parentCheck.addClass('active');
});
} else {
accordContent.slideUp(400, function () {
accordItems.removeClass('active');
});
}
});
A: maybe you forgot to link jquery
jQuery(document).ready(function(){
var clickElem = $('a.accord-link');
clickElem.on('click', function (e) {
e.preventDefault();
var $this = $(this),
parentCheck = $this.parents('.accord-elem'),
accordItems = $('.accord-elem'),
accordContent = $('.accord-content');
if (!parentCheck.hasClass('active')) {
accordContent.slideUp(400, function () {
accordItems.removeClass('active');
});
parentCheck.find('.accord-content').slideDown(400, function () {
parentCheck.addClass('active');
});
} else {
accordContent.slideUp(400, function () {
accordItems.removeClass('active');
});
}
});
});
.container .content {}
hr,
.borderedbox {
border-color: #D7D7D7;
}
.inspace-5 {
padding: 5px;
}
.imgl {
margin: 0 15px 10px 0;
clear: left;
}
.imgr {
margin: 0 0 10px 15px;
clear: right;
}
.fl_left,
.imgl {
float: left;
}
.fl_right,
.imgr {
float: right;
}
.borderedbox {
border: 1px solid;
border-color: darkgray;
}
.accord-tab-box {
padding-top: 40px;
padding-bottom: 20px;
}
.accordion-box {
margin-bottom: 20px;
}
.accord-elem {
margin-bottom: 20px;
}
.accord-title {
padding: 16px 14px;
border: 1px solid #dbdbdb;
position: relative;
}
.accord-title h5 {
padding-right: 48px;
}
.accord-title h5 i {
color: #007aff;
font-size: 20px;
vertical-align: middle;
margin-right: 12px;
}
a.accord-link {
display: inline-block;
position: absolute;
width: 46px;
height: 100%;
top: 0;
right: 0;
border-left: 1px solid #dbdbdb;
background: url('/Content/MyTemplate/images/add.png') center center no-repeat;
transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-webkit-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
}
.accord-elem.active a.accord-link {
background: url('/Content/MyTemplate/images/substract.png') center center no-repeat;
}
a.accord-link.opened {
background: url('/Content/MyTemplate/images/substract.png') center center no-repeat;
}
.accord-content {
display: none;
padding: 22px;
border: 1px solid #dbdbdb;
border-top: none;
overflow: hidden;
}
.accord-content span.image-content {
display: inline-block;
float: left;
width: 68px;
height: 68px;
border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-o-border-radius: 50%;
margin-right: 22px;
background: #007aff;
}
.accord-content span.logo-content {
display: inline-block;
float: left;
width: 110px;
margin-right: 15px;
}
.accord-content span.image-content i {
color: #fff;
font-size: 30px;
text-align: center;
width: 100%;
line-height: 68px;
vertical-align: middle;
}
.accord-content span.logo-content i {
color: #fff;
font-size: 30px;
text-align: center;
width: 100%;
line-height: 68px;
vertical-align: middle;
}
.accord-elem.active .accord-content {
display: block;
}
.why-convertible-box {
padding-top: 60px;
}
.why-convertible-box h1 {
margin-bottom: 10px;
}
.why-convertible-box h1 span {
font-weight: 600;
}
.why-convertible-box h1 i {
color: #0a9dbd;
margin-left: 10px;
}
.why-convertible-box p {
margin-bottom: 15px;
}
.why-convertible-box p a {
color: #0076f9;
font-weight: 700;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accord-tab-box">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="accordion-box">
<div class="accord-elem">
<div class="accord-title">
<h5><i class="fa fa-money fa-fw"></i>Software Development</h5>
<a class="accord-link" href="#"></a>
</div>
<div class="accord-content">
<p>IT related have a team of software developers who are skilled in Open source Java, Spring, Hibernate, Struts, GWT; DotNet framework and have written many web based systems:<br />• Requisition system<br />• Tender management system <br />•
Invoice tracking system<br />• Our team has more than 20 years experience in Software development life cycle. Reference sites: <br />• KZN Department of Works;<br />• KZN Department Of Education;<br />• EC DEDEAT;<br /><br />• Neha Shipping;<br
/><br />• SJS Consulting<br /> </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49894190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PageViewController crashes on rotation Hi I have a pageViewcontroller with some viewcontrollers inside. There ara blank controllers with one label inside
Problem is that it crashes when I try to rotate it
Here is the code
class FAPageViewController: UIPageViewController , UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var pages = ["one", "two"]
var pageViewController = UIPageViewController()
override func viewDidLoad() {
super.viewDidLoad()
pages.removeAll()
for (var i = 0; i < 4; i++) {
var obj = "child"
pages.append(obj)
}
pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
pageViewController.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 64, self.view.frame.width, self.view.frame.height - 64)
addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
pageViewController.delegate = self
pageViewController.dataSource = self
pageViewController.setViewControllers([viewcontrollerAtIndex(0)], direction: .Forward, animated: true, completion: nil)
pageViewController.didMoveToParentViewController(self)
print(pages)
}
func viewcontrollerAtIndex(index: Int) -> UIViewController {
let vc = storyboard?.instantiateViewControllerWithIdentifier(pages[index])
return vc!
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
if let index = pages.indexOf(viewController.restorationIdentifier!) {
if index < pages.count - 1 {
return viewcontrollerAtIndex(index + 1)
}
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
if let index = pages.indexOf(viewController.restorationIdentifier!) {
if index > 0 {
return viewcontrollerAtIndex(index - 1)
}
}
return nil
}
}
Here is console log
2016-03-13 14:19:16.743 FacebookAlbums[7550:1624956] * Assertion failure in -[FacebookAlbums.FAPageViewController willAnimateRotationToInterfaceOrientation:duration:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.30.14/UIPageViewController.m:1062
2016-03-13 14:19:16.748 FacebookAlbums[7550:1624956] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'No view controllers'
A: I had the same problem. This is how I solved it: I set up the UIPageViewController once again (exactly like when we did the first time) in the event of device rotation by adding the following method to UIPageViewController implementation file:
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
Because most of the time, UIPageViewController is modally presented, so on device rotation, this controller will be called again.
A: I also had an app that subclassed UIPageViewController. I had been using it for years but we had always limited it to Portrait mode. I recently began another project that started with this as a base but in this case we DID want to allow landscape modes. The app has a Navigation Controller and a couple of initial screens and then pushes to the PageViewController. The rotations would work with the conventional VC's on the Top of the Navigation Controller but if I tried rotation with the PageViewController displaying, I'd get an exception:
2020-07-24 19:33:01.440876-0400 MAT-sf[68574:12477921] *** Assertion failure in -[MAT_sf.SurveyVC willAnimateRotationToInterfaceOrientation:duration:], /Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3920.31.102/UIPageViewController.m:1055
2020-07-24 19:33:01.454443-0400 MAT-sf[68574:12477921] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'No view controllers'
It turns out that all I had to do was add an override to my subclass:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
All it does is call the same function in the superclass. I'm guessing that this should be a required method if you subclass PageViewController.
Hope this helps someone. This one cost me about a day of research until I stumbled on the solution.
A: Thanks HSH, I had the same problem in Xamarin.
I implemented:
public override void WillAnimateRotation(UIInterfaceOrientation toInterfaceOrientation, double duration)
{
}
Leaving it empty, prevents it from calling the base method. Which apparently does something that makes it crash.
Implementing this override method without calling the base method, works for me. I had a similar exception when changing the orientation quickly.
(MonoTouchException) Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: No view controllers
Native stack trace:
0 CoreFoundation 0x0000000113e3302e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x0000000114b7cb20 objc_exception_throw + 48
2 CoreFoundation 0x0000000113e32da8 +[NSException raise:format:arguments:] + 88
3 Foundation 0x00000001113a3b61 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 191
4 UIKitCore 0x00000001208b32c6 -[UIPageViewController willAnimateRotationToInterfaceOrientation:duration:] + 3983
5 UIKitCore 0x0000000120960d3e -[_UIViewControllerTransitionCoordinator _applyBlocks:releaseBlocks:] + 294
6 UIKitCore 0x000000012095d060 -[_UIViewControllerTransitionContext __runAlongsideAnimations] + 263
7 UIKitCore 0x000000012148862a +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 528
8 UIKitCore 0x0000000121488bd9 +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 99
9 UIKitCore 0x0000000120975276 __58-[_UIWindowRotationAnimationController animateTransition:]_block_invoke_2 + 278
10 UIKitCore 0x000000012148c788 +[UIView(Internal) _performBlockDelayingTriggeringResponderEvents:forScene:] + 174
11 UIKitCore 0x0000000120975004 __58-[_UIWindowRotationAnimationController animateTransition:]_block_invoke + 164
12 UIKitCore 0x000000012148862a +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 528
13 UIKitCore 0x0000000121488bd9 +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 99
14 UIKitCore 0x0000000120974edc -[_UIWindowRotationAnimationController animateTransition:] + 491
15 UIKitCore 0x0000000120fefef9 -[UIWindow _rotateToBounds:withAnimator:transitionContext:] + 525
16 UIKitCore 0x0000000120ff293c -[UIWindow _rotateWindowToOrientation:updateStatusBar:duration:skipCallbacks:] + 2331
17 UIKitCore 0x0000000120ff2f2f -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:] + 633
18 UIKitCore 0x0000000120ff1e83 -[UIWindow _setRotatableViewOrientation:updateStatusBar:duration:force:] + 119
19 UIKitCore 0x0000000120ff0d00 __57-[UIWindow _updateToInterfaceOrientation:duration:force:]_block_invoke + 111
20 UIKitCore 0x0000000120ff0c29 -[UIWindow _updateToInterfaceOrientation:duration:force:] + 455
21 Foundation 0x0000000111426976 __NSFireDelayedPerform + 420
22 CoreFoundation 0x0000000113d96944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
23 CoreFoundation 0x0000000113d96632 __CFRunLoopDoTimer + 1026
24 CoreFoundation 0x0000000113d95c8a __CFRunLoopDoTimers + 266
25 CoreFoundation 0x0000000113d909fe
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35969610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Comparing two columns of CSV files I have a csv file with two columns. first column contains 2676 entries of host names and second column has 964 entries of host names.I want to compare these columns and print the data which is there in column 2 but not in column 1
Here is the code
import re
from csv import DictReader
with open("devices.csv") as f:
a1 = [row["Device Name"] for row in DictReader(f)]
#print a1
#print len(a1)
## the code below given me the data for column 2
with open('dump_data', 'r') as f:
for line in f:
line = re.split(': |, |\*|\n', line)
listOdd = line[1::2]
for i in listOdd:
print i
result[]
# print listOdd
for i in a1:
for j in listOdd:
if i != j:
result.append(i)
# print i
break
else:
pass
print result
print len(result)
I did try other approaches like using sets and pandas
The output is not accurate, basically each element in column 2 have to be compared with each element with column 1 . I am getting few duplicate entries as differences
A: Sets would appear to be the obvious solution. The following approach reads each column into its own set(). It then simply uses the difference() function to give you entries that are in col1 but not in col2 (which is the same as simply using the - operator):
import csv
col1 = set()
col2 = set()
with open('input.csv') as f_input:
for row in csv.reader(f_input):
if len(row) == 2:
col1.add(row[0])
col2.add(row[1])
elif len(row) == 1:
col1.add(row[0])
print col1
print col2
print sorted(col2 - col1)
So if your CSV file had the following entries:
aaa,aaa
bbb,111
ccc,bbb
ddd,222
eee
fff
The required output would be:
['111', '222']
The data in your CSV file might need sanitizing before being added to the set, for example EXAMPLE.COM and example.com would currently be considered different.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42617864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image is not drawing on canvas (HTML5) I am trying to draw an image on a canvas, in HTML5. For some reason, the image simply isn't drawn onto the canvas, and there are no errors in the console. Here is my code:
<!DOCTYPE html>
<html>
<body>
<img id="image" src="Images/player.png"></img>
<canvas id="canvas" width="1000" height="750"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = document.getElementById("image");
context.fillStyle = "lightblue";
context.fillRect(0, 0, 1000, 750);
context.drawImage(image, 0, 0);
</script>
</body>
</html>
Can somebody help? Thanks.
A: You need to add an event listener to the img tag called load. Then in the callback you can call drawImage with the provided img element.
You can do something like this - I have added one stackoverflow image for representation:
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const image = document.getElementById("image");
context.fillStyle = "lightblue";
context.fillRect(0, 0, 1000, 750);
image.addEventListener('load', e => context.drawImage(image, 0, 0));
<img id="image" src="https://stackoverflow.blog/wp-content/themes/stackoverflow-oct-19/images2/header-podcast.svg" height="100px"></img>
<canvas id="canvas" width="1000" height="750"></canvas>
From the documentation: Drawing an image to the canvas
I hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59443295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring Boot fully reactive Kafka processing Is there any fully reactive, production ready Kafka support within Spring Boot ecosystem? By fully reactive I mean respecting backpressure / polling, concurrent message processing (flatMap) and handles possible failures (out of order processing errors). I did my research and there are several promising options (spring-cloud-stream with reactor based spring-cloud-function support, spring-integration with KafkaMessageSource and Reactor Kafka project), but I am not sure if they meet all the requirements and it is actually kinda confusing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58457368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Find longest subarray whose sum divisible by 3 with O(N) Complexity i have big question here , if you can see below the code you will see code with O(N) complexity. im only try to decrease it to O(N^2),
Im treid to do it with O(N) but without any secces .
private static int f (int[]a, int low, int high)
{
int res = 0;
for (int i=low; i<=high; i++)
res += a[i];
return res;
}
public static int what (int []a)
{
int temp = 0;
for (int i=0; i<a.length; i++)
{
for (int j=i; j<a.length; j++)
{
int c = f(a, i, j);
if (c%3 == 0)
{
if (j-i+1 > temp)
temp = j-i+1;
}
}
}
return temp;
}
A: couple of exemple :
int[] a={1,2,4,1}; output : 2 ==> if you can see (1+2= 3 ) ,(2+4=6) so those is %3=0 ==> beacuse that the number is 2 beacuse is two subarray that giving me %3 to be =0.
int[] a={3,4,4,2}; output : 2
int[] a={3,3,3,3,0,1}; output : 5
int[] a={3,2,7,6,6,1}; output : 5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41890051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to ignore only certain error codes for entire files in Flake8? I'm editing a Django settings file that looks similar to the following:
# flake8: noqa
from lucy.settings.base import *
from lucy.settings.staging_production import *
# This ensures that errors from staging are tagged accordingly in Airbrake's console
AIRBRAKE.update(environment='staging')
LOGGING['handlers'].update(console={
'class': 'logging.StreamHandler'
})
This setting lucy/settings/staging.py, extends two other ones and I'd like to keep the 'star imports', so I'd like to ignore error codes E403 and E405 for this file.
However, the only way I see to do that is to add the #noqa: E403, E405 comment to every line that it applies; by writing # flake8: noqa at the top of the file, it ignores all errors.
As far as I can tell from http://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html, it isn't possible to do this, or have I overlooked something?
A: Starting with Flake8 3.7.0, you can ignore specific warnings for entire files using the --per-file-ignores option.
Command-line usage:
flake8 --per-file-ignores='project/__init__.py:F401,F403 setup.py:E121'
This can also be specified in a config file:
[flake8]
per-file-ignores =
__init__.py: F401,F403
setup.py: E121
other/*: W9
A: There is no way of specifying that in the file itself, as far as I'm concerned - but you can ignore these errors when triggering flake:
flake8 --ignore=E403,E405 lucy/settings/staging.py
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50918965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to allow web requests when using VCR / WebMock? I'm currently using RSpec2, Cucumber and VCR (via WebMock), and everything's working great.
With VCR normally all requests are recorded and then replayed against the recorded cassettes.
Now I want to allow real web requests in some scenarios:
*
*In Cucumber, I've setup a "live" profile which runs any test tagged with @live. For these tests – and these tests only – I'd like to allow real web requests.
*I want from time to time run the tests against the real api and ignore the recordings
A: You can do this with cucumber's Before and After hooks. Just disable VCR using something like this:
Before('@live') do
VCR.eject_cassette
VCR.turn_off!
end
This may be dependent on exactly how you are integrating VCR with your cucumber tests though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6875701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: c# : How to Monitor Print job Using winspool_drv Recently I am making a system monitoring tool. For that I need a class to monitor print job.
Such as when a print started, is it successful or not, how many pages.
I know that I can do it using winspool.drv. But dont how. I've searched extensively but having no luck. Any code/suggestion could be very helpful.
Thanks.
A: Well I don't know about the winspool.drv, but you can use the WMI to get the status of the printer. Here is an example of the using Win32_Printer.
PrintDialog pd = new PrintDialog();
pd.ShowDialog();
PrintDoc.PrinterSettings = pd.PrinterSettings;
PrintDoc.PrintPage += new PrintPageEventHandler(PrintDoc_PrintPage);
PrintDoc.Print();
object status = Convert.ToUInt32(9999);
while ((uint)status != 0) // 0 being idle
{
ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_Printer where Name='" + pd.PrinterSettings.PrinterName + "'");
foreach (ManagementObject service in mos.Get())
{
status = service.Properties["PrinterState"].Value;
Thread.Sleep(50);
}
}
If you don't use the PrintDialog object (to choose a printer) you can run the WMI query and it will return all the printers in the system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3645120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parsing XML from a website to a String array in Android please help me Hello I am in the process of making an Android app that pulls some data from a Wiki, at first I was planning on finding a way to parse the HTML, but from something that someone pointed out to me is that XML would be much easier to work with. Now I am stuck trying to find a way to parse the XML correctly. I am trying to parse from a web address right now from:
http://zelda.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Games&cmlimit=500&format=xml
I am trying to get the titles of each of the games into a string array and I am having some trouble. I don't have an example of the code I was trying out, it was by using xmlpullparser. My app crashes everytime that I try to do anything with it. Would it be better to save the XML locally and parse from there? or would I be okay going from the web address? and how would I go about parsing this correctly into a string array? Please help me, and thank you for taking the time to read this.
If you need to see code or anything I can get it later tonight, I am just not near my PC at this time. Thank you.
A: Whenever you find yourself writing parser code for simple formats like the one in your example you're almost always doing something wrong and not using a suitable framework.
For instance - there's a set of simple helpers for parsing XML in the android.sax package included in the SDK and it just happens that the example you posted could be easily parsed like this:
public class WikiParser {
public static class Cm {
public String mPageId;
public String mNs;
public String mTitle;
}
private static class CmListener implements StartElementListener {
final List<Cm> mCms;
CmListener(List<Cm> cms) {
mCms = cms;
}
@Override
public void start(Attributes attributes) {
Cm cm = new Cm();
cm.mPageId = attributes.getValue("", "pageid");
cm.mNs = attributes.getValue("", "ns");
cm.mTitle = attributes.getValue("", "title");
mCms.add(cm);
}
}
public void parseInto(URL url, List<Cm> cms) throws IOException, SAXException {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try {
parseInto(new BufferedInputStream(con.getInputStream()), cms);
} finally {
con.disconnect();
}
}
public void parseInto(InputStream docStream, List<Cm> cms) throws IOException, SAXException {
RootElement api = new RootElement("api");
Element query = api.requireChild("query");
Element categoryMembers = query.requireChild("categorymembers");
Element cm = categoryMembers.requireChild("cm");
cm.setStartElementListener(new CmListener(cms));
Xml.parse(docStream, Encoding.UTF_8, api.getContentHandler());
}
}
Basically, called like this:
WikiParser p = new WikiParser();
ArrayList<WikiParser.Cm> res = new ArrayList<WikiParser.Cm>();
try {
p.parseInto(new URL("http://zelda.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Games&cmlimit=500&format=xml"), res);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (SAXException e) {}
Edit: This is how you'd create a List<String> instead:
public class WikiParser {
private static class CmListener implements StartElementListener {
final List<String> mTitles;
CmListener(List<String> titles) {
mTitles = titles;
}
@Override
public void start(Attributes attributes) {
String title = attributes.getValue("", "title");
if (!TextUtils.isEmpty(title)) {
mTitles.add(title);
}
}
}
public void parseInto(URL url, List<String> titles) throws IOException, SAXException {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try {
parseInto(new BufferedInputStream(con.getInputStream()), titles);
} finally {
con.disconnect();
}
}
public void parseInto(InputStream docStream, List<String> titles) throws IOException, SAXException {
RootElement api = new RootElement("api");
Element query = api.requireChild("query");
Element categoryMembers = query.requireChild("categorymembers");
Element cm = categoryMembers.requireChild("cm");
cm.setStartElementListener(new CmListener(titles));
Xml.parse(docStream, Encoding.UTF_8, api.getContentHandler());
}
}
and then:
WikiParser p = new WikiParser();
ArrayList<String> titles = new ArrayList<String>();
try {
p.parseInto(new URL("http://zelda.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Games&cmlimit=500&format=xml"), titles);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (SAXException e) {}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10767184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTTP Event Collector not working with Azure DevOps I have created a free account on splunk to test sending data to it. I am using HTTP Event Collector to send data.
When I try to execute my PowerShell script on my local computer, everything is fine, but when I copy the code and I try to execute this on Azure DevOps I am getting error with certificates.
Error:
Line |
14 | Invoke-RestMethod -Method 'POST' -Body $body -Headers $headers -Uri …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| The remote certificate is invalid according to the validation
| procedure: RemoteCertificateNameMismatch,
| RemoteCertificateChainErrors
Code:
$body='{ "event":"'
$body=$body+ "createdByName=xyz"
$body=$body+'", "source": "Azure Devops pipeline validation","sourcetype": "Invoke-RestMethod"}'
$auth_header="Splunk XYZ-XYZ"
$headers = @{"Authorization" = $auth_header}
$server = "XYZ.splunkcloud.com"
$port = "8088"
$url = "https://${server}:${port}/services/collector" # braces needed b/c the colon is otherwise a scope operator
$SearchResults = Invoke-RestMethod -Method Post -Uri $url -Body $body -TimeoutSec 300 -Headers $headers
return $SearchResults
Does anyone know how to fix this issue?
UPDATE
This issue was caused by wrong URI
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73933246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Converting VARCHAR to Date using TO_DATE I have a set of data where the col is VARCHAR() but I need it to be in DATE format.
I was trying to do it as follows:
CREATE OR REPLACE TABLE df_new
AS SELECT
col1 AS NAME
col2 AS first_name
col3 AS last_name
,TO_DATE(col4, 'yyyymmdd') AS date
FROM df_old
but I am getting an error "Can't parse '' as date with format 'yyyymmdd'".
I have tried messing with the input for the date format (such as 'yyyy/mm/dd') but I am pretty new to SQL so I am unsure of how to proceed.
A: Just use TRY_TO_DATE, it will return NULL for values where it can't parse the input.
A: If you are certain that all of your values other than NULLs are of the string 'yyyymmdd' then the following will work in snowflake.
TO_DATE(TO_CHAR(datekey),'yyyymmdd')
A: Sounds like some of your col4 entries are NULL or empty strings. Try maybe
... FROM df_old WHERE col4 ~ '[0-9]{8}'
to select only valid inputs. To be clear, if you give the format as 'YYYYMMDD' (you should use uppercase) an entry in col4 has to look like '20190522'.
A: All dates are stored in an internal format.
You cannot influence how a date is STORED. However you have it format it the way you want when you pull the data from the database via query.
A: I was able to resolve by the following:
CREATE OR REPLACE TABLE df_new
AS SELECT
,col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN "col4" = '' then NULL ELSE TO_DATE(col4, 'YYYYMMDD') AS date
FROM df_old
A: I resolved the issue as follows:
CREATE OR REPLACE TABLE df_new
AS SELECT
col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN col4 = '' THEN NULL ELSE TO_DATE(col4, 'YYYY-MM-DD') END AS date
FROM df_old
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56246908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.