text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: pass current browser url address to bean I want to send the browser url address to bean,I found this
HttpServletRequest requestObj = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String url = requestObj.getRequestURL();
I did not get the right browser address,so I will use javasript window.location to get the browser address,but how can I send this to back bean?Every answers will be helpful,any ideas?
A: Use
FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("referer")
in the back bean, you can have the request url. This bothers me for a long long time, hope this will help someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46065600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to upload an artifact to an Azure DevOps build using the API Can anyone shed some light on how to use the ADO API to upload an artifact to a build. I can't find an example that shows how to do this.
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/artifacts/create
I know there is the vso task: ##vso[artifact.upload]local file path
But, I need to do this from another script and the vso task isn't available.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75259572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tkinter - the button I made doesn't work I have tried to make a following program: when opening the program, it shows an entry and a button labeled as '9'. Character '9' is added at the end of the entry when clicking the button '9'.
The code given below is I have written, but it doesn't work as I intended. The button doesn't work and the entry shows '09' rather than '0'.
# -*- coding : utf-8 -*-
import Tkinter as Tk
class calculator:
def __init__(self, master):
self.num = Tk.StringVar()
self.opstate = None
self.tempvar = 0
# entry
self.entry = Tk.Entry(root, textvariable = self.num, justify=Tk.RIGHT, width = 27)
self.entry.pack(side = Tk.TOP)
self.num.set("0")
# Buttons
self.numbuts = Tk.Frame(master)
self.ins9 = Tk.Button(self.numbuts, text = "9", width = 3, command = self.fins(9))
self.ins9.pack()
self.numbuts.pack(side = Tk.LEFT)
##### Functions for Buttons #####
def fins(self, x):
self.entry.insert(Tk.END, str(x))
root = Tk.Tk()
calc = calculator(root)
root.mainloop()
I guess the part command = self.fins(9) is problematic but I don't know how to resolve it. Thanks for any help.
A: The code is passing the return value of the method call, not the method itself.
Pass a callback function using like following:
self.ins9 = Tk.Button(self.numbuts, text="9", width=3, command=lambda: self.fins(9))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31097722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How I can access Class method variable in instance method OR Use a common variable for both? I have this Class method to create a hero object.
+(id)hero
{
NSArray *heroWalkingFrames;
//Setup the array to hold the walking frames
NSMutableArray *walkFrames = [NSMutableArray array];
//Load the TextureAtlas for the hero
SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
//Load the animation frames from the TextureAtlas
int numImages = (int)heroAnimatedAtlas.textureNames.count;
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
[walkFrames addObject:temp];
}
heroWalkingFrames = walkFrames;
//Create hero sprite, setup position in middle of the screen, and add to Scene
SKTexture *temp = heroWalkingFrames[0];
Hero *hero = [Hero spriteNodeWithTexture:temp];
hero.name =@"Hero";
hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
hero.physicsBody.categoryBitMask = heroCategory;
hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
return hero;
}
and I have another instance method to perform run animation for my hero.
-(void)Start
{
SKAction *incrementRight = [SKAction moveByX:10 y:0 duration:.05];
SKAction *moveRight = [SKAction repeatActionForever:incrementRight];
[self runAction:moveRight];
}
now heroWalkingFrames variable in Start method so I can perform animation, I want to add this line in Start method
[SKAction repeatActionForever:[SKAction animateWithTextures:heroWalkingFrames timePerFrame:0.1f resize:NO restore:YES]];
Is there any way I can use this variable for both ?
A: Sure, in Hero.h add:
@property (nonatomic, retain) NSArray *walkingFrames;
Then, in your +(id)hero method, instead of declaring a new array NSArray *heroWalkingFrames, use:
+(id)hero
{
//Setup the array to hold the walking frames
NSMutableArray *walkFrames = [NSMutableArray array];
//Load the TextureAtlas for the hero
SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
//Load the animation frames from the TextureAtlas
int numImages = (int)heroAnimatedAtlas.textureNames.count;
for (int i=1; i <= numImages/2; i++) {
NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
[walkFrames addObject:temp];
}
//We set hero texture to the first animation texture:
Hero *hero = [Hero spriteNodeWithTexture:walkFrames[0]];
// Set the hero property "walkingFrames"
hero.walkingFrames = walkFrames;
hero.name =@"Hero";
hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
hero.physicsBody.categoryBitMask = heroCategory;
hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;
return hero;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31740027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Function template argument deduction with variadic class template as function call parameter All the examples are from here and here.
Specifically,
template<class...> struct Tuple { };
template< class... Types> void g(Tuple<Types ...>); // #1
// template<class T1, class... Types> void g(Tuple<T1, Types ...>); // #2
template<class T1, class... Types> void g(Tuple<T1, Types& ...>); // #3
g(Tuple<>()); // calls #1
g(Tuple<int, float>()); // calls #2
g(Tuple<int, float&>()); // calls #3
g(Tuple<int>()); // calls #3
With #2 uncommented, g()'s are resolved as described in the comments. What surprises me is that if I comment out the #2 line, the g()'s calls are resolved as follows:
g(Tuple<>()); // calls #1
g(Tuple<int, float>()); // calls **#1 ???? why not #3????**
g(Tuple<int, float&>()); // calls #3
g(Tuple<int>()); // calls #3
From the following examples and explanations below I can't see why g(Tuple<int, float>()); can't resolved to #3. It is the direction application of the following two rules:
If a parameter pack appears as the last P, then the type P is matched against the type A of each remaining argument of the call. Each match deduces the template arguments for the next position in the pack expansion.
template<class ... Types> void f(Types& ...);
void h(int x, float& y) {
const int z = x;
f(x, y, z); // P=Types&..., A1=x: deduces the first member of Types... to int
// P=Types&..., A2=y: deduces the second member of Types... to float
// P=Types&..., A3=z: deduces the third member of Types... to const int
// calls f<int, float, const int>
If P has one of the forms that include a template parameter list <T> or <I>, then each element Pi of that template argument list is matched against the corresponding template argument Ai of its A. If the last Pi is a pack expansion, then its pattern is compared against each remaining argument in the template argument list of A. A trailing parameter pack that is not otherwise deduced, is deduced to an empty parameter pack.
A: There's a misconception here between your two examples. In the 2nd example with f, you are deducing reference arguments to a function. In the 1st example with g, you are deducing reference template parameters to an argument to a function. The latter must match exactly, but the former is deduced against the referred types. They are not the same.
In your fist example,
g(Tuple<int, float>());
cannot call g(Tuple<T1, Types&...>). The template deduction process is about picking a deduced argument type that is identical to the called argument type. There are some exceptions (for referenced cv-qualifications, pointers, derived classes, arrays, functions), but none of those apply here. We simply need to pick T1 and Types... such that Tuple<T1, Types&...> is the same type as Tuple<int, float>. This is impossible as there is no such pack Types... for which Types&... is {float}, since float is not a reference!
So once you comment out (2), there's only one viable candidate: (1).
On the other hand,
template<class ... Types> void f(Types& ...);
void h(int x, float& y) {
const int z = x;
f(x, y, z);
}
Here, Types&... is actually the type of the parameter itself (rather than a template argument of it), so (temp.deduct.call):
If P is a reference type, the type referred to by P is used for type deduction.
We deduce Types... to match the arguments. This succeeds because all the arguments are lvalues, and we simply pick {int, float, const int}.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33426328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xamarin ListView item click animation For some reason, i have this animation/effect by default when I press any items of my ListView (chat). I dont have any codes for that, it is just present/default.
Why is that? How can I turn it off or on?
A: It called "Ripple effect".
there are many related question in SO, see this https://stackoverflow.com/a/27237195/3814729 .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48047343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: R - Looping through Values in Variable and Dropping Duplicates Based on Condition I would like to loop through each unique value in the variable "Item" (i.e. A, B, C), and only keep the rows with the lowest ID number for each item, deleting the other rows for each corresponding item.
So, I have a data frame that looks like this right now:
Item Cost ID
A 4 1
A 3
B 39 10
B 18
B 21
C 290 15
C
And I want something that looks like this:
Item Cost ID
A 4 1
B 39 10
C 290 15
How do I do this?
(Thanks in advance - I'm new to R!)
A: your task is quite easy with dplyr, but there is a variety of approaches.
library(dplyr)
df %>% group_by(Item) %>% filter(ID == min(ID, na.rm = TRUE))
Source: local data frame [3 x 3]
Groups: Item [3]
Item Cost ID
<fctr> <dbl> <dbl>
1 A 4 1
2 B 39 10
3 C 290 15
Data used:
structure(list(Item = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L), .Label = c("A",
"B", "C"), class = "factor"), Cost = c(4, NA, 39, NA, NA, 290,
NA), ID = c(1, 3, 10, 18, 21, 15, NA)), .Names = c("Item", "Cost",
"ID"), row.names = c(NA, -7L), class = "data.frame")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43711069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery image change doesnt work The following code should work but I cant seem to find the problem why it doesnt work, I am testing it with google chrome
<html>
<head>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
<script type="text/javascript">
$('#unos').click(function() {
$("#tre").attr('src', '/012/11/image2.jpg');
});
</script>
</head>
<body>
<img id="tre" class="aligncenter" title="images" src="/012/11/image1.jpg" alt="" width="940" height="207" />
<input id="unos" type="submit" name="change_src" value="change image" />
</body>
</html>
A: <html>
<head>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#unos').click(function() {
$("#tre").attr('src', '/012/11/image2.jpg');
});
});
</script>
</head>
<body>
<img id="tre" class="aligncenter" title="images" src="/012/11/image1.jpg" alt="" width="940" height="207" />
<input id="unos" type="submit" name="change_src" value="change image" />
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13434500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to enable (or set up) MySQL to use "group commit"? I've read a lot of good reviews of MySQL Group Commit, which was broken in MySQL 4.x but was fixed in 5.1 and 5.5. See http://dev.mysql.com/doc/innodb/1.1/en/innodb-performance-group_commit.html
But I could not find any document showing how to enable (or set up) Group Commit in MySQL 5.5. The above link only says sync_binlog needs to be set to 0 for group commit to support binary log. But it does not mention any config variable to turn on group commit.
Maybe Group Commit is an internal optimization in MySQL that's always "enabled" without a user doing any explicit config change?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7650575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using MDX Correlation() function to find correlation of 2 dimentional members I'm trying to find the Pearson correlation of a single measure between two members of a dimension, but the msdn docs are a bit sparse. Specifically I have a cube with a fact count measure, a date dimension, and a tool dimension and I'd like to find the correlation of tool X and tool Y over the date dimension.
A: take a look at the following script (Adventure Works DW 2008 R2):
It will return correlation of [Internet Sales Amount] measure for two different product subcategories ("Mountain Bikes"/"RoadBikes") for months of current date member on rows (Calendar Year 2007 quarters and Calendar Year 2007). I have left other comparable members in comments.
with
member ActualMeasure AS [Measures].[Internet Sales Amount]
member m1 AS
(
[Product].[Product Categories].[Subcategory].&[1] -- Mountain Bikes
-- [Sales Territory].[Sales Territory].[Group].&[North America]
-- [Customer].[Gender].&[F]
,ActualMeasure
)
member m2 AS
(
[Product].[Product Categories].[Subcategory].&[2] -- Road Bikes
-- [Sales Territory].[Sales Territory].[Group].&[Europe]
-- [Customer].[Gender].&[M]
, ActualMeasure
)
member x as
Correlation
(
{Descendants([Date].[Calendar].CurrentMember,[Date].[Calendar].[Month]) } as dates
, m1
, m2
), Format_String="Standard"
select
{ x,m1,m2 } on 0,
{
Descendants
(
[Date].[Calendar].[Calendar Year].&[2007]
, [Date].[Calendar].[Calendar Quarter]
)
,[Date].[Calendar].[Calendar Year].&[2007]
} on 1
from [Adventure Works]
HTH,
Hrvoje Piasevoli
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4028470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: find and replace string on a line I'm trying to make a find and replace on strings
?version(.*) -> ?versionMyVersionHere
ex :
<script src="js/script.js?versionSomeVersionHere"></script>
<script src="js/messages.js?version"></script>
<script src="js/script.js?versionMyVersionHere"></script>
<script src="js/messages.js?versionMyVersionHere"></script>
I've tried something like :
sed -i -e "s/\?version/?versionMyVersionHere/g" index.html
But it append the text to the one already present...
Thank you for taking the time to help me with this !
A: sed 's#\?version.*\"#\?versionMyVersionHere\"#g'
Demo :
$echo -e '<script src="js/script.js?versionSomeVersionHere"></script>
<script src="js/messages.js?version"></script>' | sed 's#\?version.*\"#\?versionMyVersionHere\"#g'
<script src="js/script.js?versionMyVersionHere"></script>
<script src="js/messages.js?versionMyVersionHere"></script>
$
A: You may use:
sed -i 's/?version"/?versionMyVersionHere"/' index.html
Details:
*
*? doesn't need to be escaped in default BRE.
*Make sure to match trailing " in order to avoid matching partial word.
A: If you want to substitute all all occurrences of ?version for substitute in your file index.html, then execute the following command:
sed -i 's/?version"/?versionMyVersionHere"/' index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61074627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: order_products column connected with Google Checkout transaction in osCommerce I am using Google Checkout with osCommerce and want to know which column of the order_products database table is connected with the transaction.
Google Checkout displays the price details of every product and I want to know from where in the code this detail comes from.
A: In osCommerce the payment modules have a method called process_button().
This method draws a form with the hidden fields the payment method needs. In the case of Google Checkout it will draw the fields needed by Google to show the information.
You can check in catalog/includes/modules/payment/<your Google Checkout module>.php that function to see which fields are sent to Google Checkout to show the information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3537131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSIS - Detect drivers available and let the user decide where to install an specific file (the license of the software) What I need is:
After the software is installed, I need to identify the drivers available (Hard Disks, Pen Drives, etc), and the user can chose in which drive he wants to install the license of the software. When he chooses, a .txt file is created and it's written there the drive he choose (Example: C:).
My code without that feature is here:
!include "MUI2.nsh"
!define NOME "S-Monitor"
Name "${NOME}"
OutFile "${NOME}.exe"
InstallDir "C:\${NOME}"
ShowInstDetails show
;--- Paginas ---
!define MUI_ICON Labels\SetupICO.ico
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_RIGHT
!define MUI_HEADERIMAGE_BITMAP Labels\Header.bmp
!define MUI_WELCOMEFINISHPAGE_BITMAP Labels\Left.bmp
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!define MUI_FINISHPAGE_NOAUTOCLOSE
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_CHECKED
!define MUI_FINISHPAGE_RUN_TEXT "Criar atalho na Área de Trabalho"
!define MUI_FINISHPAGE_RUN_FUNCTION "AtalhoDesktop"
!insertmacro MUI_PAGE_FINISH
;--- Idiomas ---
!insertmacro MUI_LANGUAGE "Portuguese"
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Spanish"
Function .onInit
!insertmacro MUI_LANGDLL_DISPLAY
FunctionEnd
;--------------------------------
;Arquivos a serem instalados
Section "Instalacao"
SetShellVarContext all
SetOutPath "$INSTDIR"
File /r Ficheiros\*.* ; LOCALIZACAO DA APLICACAO DO S-MONITOR
SectionEnd
Function AtalhoDesktop
createShortCut "$DESKTOP\S-Monitor.lnk" "C:\SMonitor.exe"
FunctionEnd
A: The user smilepleeeaz helped me at another question, and that can also be used to answered this.
The code with the feature that I wanted is down below:
!include "MUI2.nsh"
!include FileFunc.nsh
!insertmacro GetDrives
var newCheckBox
!define NOME "S-Monitor"
Name "${NOME}"
OutFile "${NOME}.exe"
InstallDir "C:\${NOME}"
ShowInstDetails show
AllowRootDirInstall true
;--- Paginas ---
!define MUI_ICON Labels\SetupICO.ico
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_RIGHT
!define MUI_HEADERIMAGE_BITMAP Labels\Header.bmp
!define MUI_WELCOMEFINISHPAGE_BITMAP Labels\Left.bmp
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
Page Custom CustomCreate CustomLeave
!define MUI_FINISHPAGE_NOAUTOCLOSE
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_CHECKED
!define MUI_FINISHPAGE_RUN_TEXT "Criar atalho na Área de Trabalho"
!define MUI_FINISHPAGE_RUN_FUNCTION "AtalhoDesktop"
!define MUI_PAGE_CUSTOMFUNCTION_SHOW showNewCheckbox
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE launchNewLink
!insertmacro MUI_PAGE_FINISH
;--- Idiomas ---
!insertmacro MUI_LANGUAGE "Portuguese"
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Spanish"
Function .onInit
!insertmacro MUI_LANGDLL_DISPLAY
InitPluginsDir
GetTempFileName $0
Rename $0 '$PLUGINSDIR\custom.ini'
FunctionEnd
;--------------------------------
;Arquivos a serem instalados
Section "Instalacao"
SetShellVarContext all
SetOutPath "$INSTDIR"
File /r Ficheiros\*.* ; LOCALIZACAO DA APLICACAO DO S-MONITOR
MessageBox MB_OK "O software BDE (Borland Database Engine) será instalado agora"
ExecWait "Ficheiros\bde_install_Win7_32_e_64.exe"
FileOpen $1 '$INSTDIR\S-monitor.cpy' w
FileWrite $1 "CPY Location=C:\S-Monitor.cpy"
FileClose $1
writeUninstaller $INSTDIR\uninstall.exe
SectionEnd
Section "Uninstall"
MessageBox MB_YESNO "Deseja desinstalar o S-Monitor?" IDYES true IDNO false
true:
SetShellVarContext all
delete $INSTDIR\uninstall.exe
RMDir /R /REBOOTOK $INSTDIR
Goto +2
false:
MessageBox MB_OK "Desinstalação cancelada."
SectionEnd
Function AtalhoDesktop
createShortCut "$DESKTOP\S-Monitor.lnk" "C:\SMonitor.exe"
FunctionEnd
Function showNewCheckbox
${NSD_CreateCheckbox} 120u 110u 100% 10u "&Iniciar o S-Monitor ao terminar a instalação"
Pop $newCheckBox
FunctionEnd
Function launchNewLink
${NSD_GetState} $newCheckBox $0
${If} $0 <> 0
Exec "C:\S-Monitor\Smonitor.exe"
${EndIf}
FunctionEnd
Function CustomCreate
WriteIniStr '$PLUGINSDIR\custom.ini' 'Settings' 'NumFields' '6'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Type' 'Label'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Left' '5'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Top' '5'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Right' '-6'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Bottom' '17'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 1' 'Text' \
'Selecione o drive a ser instalada a licensa do S-Monitor:'
StrCpy $R2 0
StrCpy $R0 ''
${GetDrives} "HDD+FDD" GetDrivesCallBack
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Type' 'DropList'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Left' '30'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Top' '26'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Right' '-31'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Bottom' '100'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'Flags' 'Notify'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'State' '$R1'
WriteIniStr '$PLUGINSDIR\custom.ini' 'Field 2' 'ListItems' '$R0'
push $0
InstallOptions::Dialog '$PLUGINSDIR\custom.ini'
pop $0
pop $0
FunctionEnd
Function CustomLeave
ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Settings' 'State'
StrCmp $0 '2' 0 next
ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State'
strcpy $R0 $0
StrCpy $0 $0 3
FileOpen $1 '$INSTDIR\S-monitor.cpy' w
FileWrite $1 "CPY Location=$R0S-Monitor.cpy"
FileClose $1
Abort
next:
ReadIniStr $0 '$PLUGINSDIR\custom.ini' 'Field 2' 'State'
StrCpy '$INSTDIR' '$0'
FunctionEnd
Function GetDrivesCallBack
StrCmp $R2 '0' 0 next
StrCpy $R3 '$R4'
StrCpy $R1 '$9'
IntOp $R2 $R2 + 1
next:
StrCpy $R0 '$R0$9|'
Push $0
FunctionEnd
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16566707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to measure distance between apple watch and iPhone? I know that core bluetooth is not available in watchOS2 so there is no way to read RSSI. But app like lookout released watch app that has a distance indicator. How did they do that? Any thought?
A: Using interactive messing pass mobile location to apple watch and calculate distance to shown on watch
Refer below apple link for communicating with the counterpart app
https://developer.apple.com/documentation/watchconnectivity/wcsession
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37220005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to have make a div take a minumum of 50% space but if no sibling is present take 100% Simply put I have:
#Container {
display:'flex';
flex-wrap:'wrap';
}
.item {
flex-basis: '50%'
}
Scenario one:
<div id=Container>
<div class="item"></div> 33 %
<div class="item"></div> 33 %
<div class="item"></div> 33%
</div>
Scenario 2
<div id=Container>
<div class="item"></div> 50 %
<div class="item"></div> 50 %
</div>
scenario 3:
<div id=Container>
<div class="item"></div> 100 %
</div>
What I want in general tems is this to be fluid, the more items I put in the less space each item will have but if there is only 1 then I want it to take full space.
A: First you have to add display: flex; to #Container
#Container{
display: flex;
}
If you want to equally distribute the space between children then you can use flex property as
.item{
flex: 1;
}
Above CSS is minimum required styles, rest is for demo
#Container {
display: flex;
margin-top: 1rem;
}
.item {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
}
.item:nth-child(1) {
background-color: red;
}
.item:nth-child(2) {
background-color: blueviolet;
}
.item:nth-child(3) {
background-color: aquamarine;
}
<div id="Container">
<div class="item">33 %</div>
<div class="item">33 %</div>
<div class="item">33 %</div>
</div>
<div id=Container>
<div class="item"> 50 % </div>
<div class="item"> 50 % </div>
</div>
<div id=Container>
<div class="item">100 %</div>
</div>
A: I think that this example could give you an idea of how to achieve what you want:
https://codepen.io/Eylen/pen/vYJBpMQ
.Container {
display: flex;
flex-wrap: wrap;
margin-bottom: 8px;
}
.item {
flex-grow: 1;
margin: 0 12px;
background: #f1f1f1;
}
Your main issue in the code that you gave, is that you're missing the flex item behaviour. I have just set that the item can grow to fill the space with the flex-grow:1.
A: You can make sure a flex child covers up the space if it can, you can provide flex-grow: 1
#Container {
display:flex;
}
.item {
width: 100%;
flex-grow: 1;
border: 1px solid;
text-align: center;
}
<h1> Scenario 1 </h1>
<div id=Container>
<div class="item">33 %</div>
<div class="item">33 %</div>
<div class="item">33%</div>
</div>
<h1> Scenario 2 </h1>
<div id=Container>
<div class="item">50 %</div>
<div class="item">50 %</div>
</div>
<h1> Scenario 3 </h1>
<div id=Container>
<div class="item">100 %</div>
</div>
A: Added a demo below.
$( document ).ready(function() {
$( "#add" ).click(function() {
$('#container').append('<div class="item"></div>');
});
$( "#remove" ).click(function() {
$('#container').children().last().remove();
});
});
#container {
width:100%;
height:500px;
background-color:#ebebeb;
display:flex;
flex-direction: column;
}
.item {
width:100%;
display: flex;
flex: 1;
border-bottom:1px solid #007cbe;
}
.item1 {
background:#007cbe;
}
.item2 {
background: #d60000;
}
.item3 {
background: #938412
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="item item1">1</div>
<div class="item item2">2</div>
<div class="item item3">3</div>
</div>
<button id="add"> Add </div>
<button id="remove"> Remove </div>
A: Apply to the below CSS to fulfill your requirement.
#Container {
display: flex;
}
.item {
width: 100%;
min-height: 100px;
border: 1px solid;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69495155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Good practice for finding existing instance of a class from another class that is not a child I'm trying to develop simple TowerDefense game but
it seems like I miss the very basics of OOP as I encountered problem
must be somehow fixable as everyone programming in OOP must have
enountered it.
Here's very very basic structure
Game
|__ Map
Player
|__ UnitController
+ Block
+ Unit
So basically Map() controller creates 100 new Block() passing x and y coordinates to it
and stores information about those Blocks() inside a List<>. One of those Block is starting
position (it's still a Block object).
Now UnitController() has SpawnUnit() method. It creates new Unit() and it (here comes the problem)
has to put this unit instance ON the starting block. In order to do that, UnitController will have to
ask Map for starting position (that is a variable stored by Map) but.. How does the UnitController
can contact Map instance. The only way I see is that Map is a singleton and I simply can do Map.getStartingPos
otherwise if Map is not a singleton (thus instance) then how UnitController will find this instance?
I could pass this instance to UnitController when I was instantiating UnitController but that's not an option I guess
because there'll be tons of other examples in this game (for example Towers which attacks units, it has to find a unit and ...)
and I can't simply throw those instances all around the code?
thanks
A: Why are you against giving the UnitController a reference to its Map?
public UnitController {
private final Map map;
public UnitController(Map map) {
this.map = map;
}
}
Now your UnitController has a reference to the Map. And this makes sense, if you think about it. What units can be controlled without a map? Shouldn't all UnitControllers have a Map on which they are controlling units? It makes sense as a property, does it not?
You certainly don't want to make Map a singleton, as you suggest, as this sort of breaks the elegant object-orientedness of your model. The whole point is to be able to have multiple Maps, on which multiple UnitControllers can be acting. Restricting this to one run at a time, one Map at a time, makes the code much more procedural than object-oriented.
No matter what you do, the Map and the UnitController will have to have something in common in order to share data, even if you don't want them to have direct references to each other.
As far as "towers which attack the nearest unit" being a reason not to use this model, it doesn't make sense; a Tower ought to simply request the nearest unit from the Map object (i.e., map.getNearestUnit(int x, int y)). No need for any more convoluted references, as long as everything can push and pull information from the Map.
For a more complicated example of the threaded Tower you're concerned with:
public class Tower extends Unit implements ActionListener {
private final Timer fireTimer;
private final Map map;
private int damage;
private int range;
public Tower(Map map, int damage, int range, int fireRate) {
this.map = map;
this.damage = damage;
this.range = range;
fireTimer = new Timer(fireRate, this);
fireTimer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == fireTimer) {
map.damageNearestUnit(this, range, damage);
}
}
}
... where the signature for map.damageNearestUnit is something like damageNearestUnit(Unit unit, int range, int damage). This should essentially take the passed in Unit, get its coordinates, and find the nearest unit in the int range. If one exists in range, deal the int damage to that other unit. Then if the damaged Unit has less than 1 health, it should be removed from the Map, trigger a UI change, etc.
Actually, if I had simple getters and setters in my Tower and had my damageNearestUnit method assume that one unit was damaging another, I could simply have its signature be damageNearestUnit(Unit attacker).
I hope this shows how the Map is the fabric that binds everything else together and controls that which exists on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20502724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to check if x-staticmap-api-warning response header exists? I'm working on a project for school using the google static map api. There is a table with a list of locations. When you click on a location it brings up a modal window with the google map. If the api cannot find the location it just shows a map of water with an error. I noticed in the developer console under network there is a response header under the staticmap call titled x-staticmap-api-warning which contains the error.
Is there a way in javascript that can check if this response header exists so I can display a "Location unknown" message instead?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51971250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Swift 3 CollectionView scaling I recently implemented a collection view in a app, the only problem I'm experiencing is that the collection view goes from 2 column to 1 column on smaller devices with a lot of padding on both sides
heres on a display smaller then a iPhone 6:
and heres how it looks on a display bigger or equal to a iPhone 6:
I did try several method where if the display width was smaller then a certain number it would scale up the cells, but it failed to work out because the cells where indeed scaled up but where not centered and over-lapping themselves.
A: You need to calculate your sizes depending on the phone size - if two cell's width are larger then screen size ( including all offsets between them ) they will layout as in the first picture.
You have two options:
One is to deal with sizes and rescale cells according to device size
Two leave it as is - Make small changes for iphone6/6s/7.
If you opt out for first one, you will need to set up constraint for these sizes - aspect ratio or center horizontally ( which could crop the image a little ).
For changing sizes dynamically, take a look at:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout
More specific:
https://developer.apple.com/reference/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview
A:
You need to calculate the cell width.Try this code.
class YourClass: UIViewController {
//MARK:-Outlets
@IBOutlet weak var yourCollectionView: UICollectionView!
//Mark:-Variables
var cellWidth:CGFloat = 0
var cellHeight:CGFloat = 0
var spacing:CGFloat = 12
var numberOfColumn:CGFloat = 2
//MARK:-LifeCycle
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourCollectionView.contentInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
if let flowLayout = yourCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
cellWidth = (yourCollectionView.frame.width - (numberOfColumn + 1)*spacing)/numberOfColumn
cellHeight = cellWidth //yourCellHeight = cellWidth if u want square cell
flowLayout.minimumLineSpacing = spacing
flowLayout.minimumInteritemSpacing = spacing
}
}
extension YourClass:UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: cellWidth, height: cellHeight)
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40822239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: R How to take Median of Rows in Dataframe I am wondering if there is any way to a median of the rows in a data frame. I understand the function rowmeans exists, but I do not believe there is a row median function. I would like to store the results in a new column in the dataframe. Here is my example
I tried to look online. There was one mention of row medians, but I could not find the function in R.
C1<-c(3,2,4,4,5)
C2<-c(3,7,3,4,5)
C3<-c(5,4,3,6,3)
DF <- data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)
DF
# This is as far as I have gotten, but not streamlined
MA <- median(C(3, 3, 5). na.rm = T) # A
MB <- median(C(2, 7, 4). na.rm = T) # B
MC <- median(C(4, 3, 3). na.rm = T) # C
MD <- median(C(4, 4, 6). na.rm = T) # 4
ME <- median(C(5, 5, 3). na.rm = T) # E
CM <- c(MA, MB, MC, MD, ME)C1<-c(3,2,4,4,5)
ID C1 C2 C3
1 A 3 3 5
2 B 2 7 4
3 C 4 3 3
4 D 4 4 6
5 E 5 5 3
ID C1 C2 C3 CM
1 A 3 3 5
2 B 2 7 4
3 C 4 3 3
4 D 4 4 6
5 E 5 5 3
Is there anyway I can streamline the process so it would be like DF$CM <- median(...
A: If you would like to use dplyr, you can find an example here, especially mpalanco's answer. Briefly, after using rowwise to indicate that the operation should be applied by row (rather than to the entire data frame, as by default), you can use mutate to calculate and name a new column off of a selection of existing columns. Check out the documentation on each of those functions for more details.
E.g.,
library(dplyr)
DF %>%
rowwise() %>%
mutate(CM = median(c(C1, C2, C3), na.rm = TRUE))
will yield the output:
# A tibble: 5 x 5
ID C1 C2 C3 CM
<fct> <dbl> <dbl> <dbl> <dbl>
1 A 3 3 5 3
2 B 2 7 4 4
3 C 4 3 3 3
4 D 4 4 6 4
5 E 5 5 3 5
A: Just a little bit more flexible and up to date. We use c_across with rowwise function and it allows to use tidy-select semantics. Here we choose where to specify we only want the numeric column to calculate the median.
library(dplyr)
DF %>%
rowwise() %>%
mutate(med = median(c_across(where(is.numeric)), na.rm = TRUE))
# A tibble: 5 x 5
# Rowwise:
ID C1 C2 C3 med
<chr> <dbl> <dbl> <dbl> <dbl>
1 A 3 3 5 3
2 B 2 7 4 4
3 C 4 3 3 3
4 D 4 4 6 4
5 E 5 5 3 5
A: To calculate the median of df, you can do the following
df$median = apply(df, 1, median, na.rm=T)
A: Oneliner that allows you to pick your desired columns:
apply(DF[, c("C1", "C2", "C3")], 1, median)
ID C1 C2 C3 CM
1 A 3 3 5 3
2 B 2 7 4 4
3 C 4 3 3 3
4 D 4 4 6 4
5 E 5 5 3 5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54366592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Akka-http: How do I map response to object Not sure if I'm getting this whole routing DSL thing right but here's the question. I want to do a post to external service such as:
val post = pathPrefix("somePath") {
post {
//get the response mapped to my Output object
}
}
Then I want the response (which is a Json) to be mapped to an object matching the fields for example Output (assuming I have my JsonProtocol set up). How is this done?
A: You are using HTTP server directives to "retrieve" something "externally". This is what typically an HTTP client does.
For this sort of things, you can use akka http client api.
For example:
val response = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
response onComplete {
case Success(res) =>
val entity = Unmarshal(res.entity).to[YourDomainObject]
// use entity here
case Failure(ex) => // do something here
}
However, this requires some Unmarshaller (to deserialize the received json). Take also a look at Json Support, as it helps you define marshallers easily:
case class YourDomainObject(id: String, name: String)
implicit val YourDomainObjectFormat = jsonFormat2(YourDomainObject)
A: I think what you are trying to ask is how to get the body i.e in JSOn format to the Case class that you have
Here is a quick example:
path("createBot" / Segment) { tag: String =>
post {
decodeRequest {
entity(as[CaseClassName]) { caseclassInstance: CaseClassName =>
val updatedAnswer = doSomeStuff(caseclassInstance)
complete {
"Done"
}
}
}
You can find more detailed example from here : https://github.com/InternityFoundation/Stackoverflowbots/blob/master/src/main/scala/in/internity/http/RestService.scala#L56
I hope it answers your question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48241925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading CSV file through Flask I'm currently trying to read through a CSV file that is being provided through Flask-WTF(orms) and I continue to run into issues when trying to load it through csv.DictReader or pandas.
The file (a FileStorage object) is not actually being uploaded anywhere, and I am trying to grab the data within the CSV to use within my code.
This is how I'm trying to grab it now using pandas
f = form.upload.data
data = pandas.read_csv(f.stream)
logger.debug(data)
However this returned the error pandas.errors.EmptyDataError: No columns to parse from file
When I tried grabbing it through csv.reader this way:
reader = csv.reader(f.read(), delimeter=',')
for row in reader:
logger.debug(row)
I got this error instead: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
I received a similar error when trying out csv.DictReader as well.
Has anyone tried to do anything similar to this, or know if this is even possible without uploading the file anywhere? I've looked around but I can't seem to find a proper solution.
For reference, my CSV file has a pretty basic format:
C1,C2
Data,Data
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48435033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Create Resource Group with Azure Management C# API Is there a way to create a Resource Group with the Azure Management C# API?
Basically this REST API call:
https://msdn.microsoft.com/en-us/library/azure/dn790525.aspx
I found a way to create an Affinity Group by using client.AffinityGroups.Create, but that's the closest thing I've found.
A: I found the API call was hidden in a library which is only in preview mode at the moment. It's found in the following NuGet package, enable include prerelease in Visual Studio to find it in the NuGet client.
https://www.nuget.org/packages/Microsoft.Azure.Management.Resources/
Then to create a resource group I can use
var credentials = new TokenCloudCredentials("", "");
var client = new Microsoft.Azure.Management.Resources.ResourceManagementClient(credentials);
var result = c.ResourceGroups.CreateOrUpdateAsync("MyResourceGroup", new Microsoft.Azure.Management.Resources.Models.ResourceGroup("West US"), new System.Threading.CancellationToken()).Result;
There is another stack overflow post explaining how to do the authentication:
How to get Tags of Azure ResourceManagementClient object
The following blog post explains how to set up TokenCloudCredentials, required for the authentication part, in more detail, but only for command line apps:
http://www.bradygaster.com/post/using-windows-azure-active-directory-to-authenticate-the-management-libraries
If you want to use something other than a command line app the following can work for authentication:
http://www.dushyantgill.com/blog/2015/05/23/developers-guide-to-auth-with-azure-resource-manager-api/
A: Go to https://resources.azure.com - the ARMExplorer shows both the REST and the PowerShell commands to create a resource group. All the APIs are REST based. In C#, send a WebClient request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31189931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Download handler (php code) is called multiple times for a single request I have a PHP script which handles the download requests. this script can be accessed by the client using a GET request like this (Javascript):
if (true)
{
window.open('/download?mode=paper&fid=' + fid, '_blank');
return;
}
And here is the (simplified) handler:
function downloadPaper($fid)
{
// Adds a record to the database, but it seems to be called multiple times
Daban\PaperTools::addPaperDownloadRecord($fid);
header('Content-Description: File Transfer');
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$fakeFileName");
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Length: " . filesize($file));
$fh = fopen($file, "rb");
while (!feof($fh))
{
echo fgets($fh);
flush();
}
fclose($fh);
}
The problem is that according to the database, there are multiple download records for each download. In other words, the handler is called multiple times for a single request (or at least that is what I believe).
P.S. addPaperDownloadRecord() is jsut some piece of SQL code and it is not the culprit. I also checked the client side, it sends only once.
A: I managed to find the reason. If anyone has a similar problem, this may help. Since I had a download manager in my system, it sent multiple requests to divide the file in order to expedite the download process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59209198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: User Generated Hyperlinks to Files Hosted on a Network Share My ultimate goal is to allow users to select a file from a dialog as if they are uploading a file. Instead of file being saved to the server, a hyperlink will be generated from the file's path. This hyperlink will then be used on our intranet page in order to open the file located on our network share. Is there any practical way to accomplish this?
I have tried both an HTML file type insert and .Net's FileUpload Control but neither will work since for security reasons the full path of the file is never accessible.
The intranet site is built in VB.Net.
A: You would not be able to do this through a regular web page, since a web site gaining access to a file's path would be a gross security violation. One thing you could do is have a control on your page where the server creates a file tree from browsing the network share. Then the user would select the file path from this server-generated tree.
A: suppose your network share drive is the S: drive
if you use plain old file:// style URI's the links will auto open to your files on the share drive.
i.e. file://s:\techfiles\myfile.txt
in order to put the file on the share drive, you must be running that webapp on the share drive server(or have access to it), so just save that file off to the share server, then generate the path. The fact that the webapp server temporarily holds on to the file before storing it shouldn't bother you too much...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1627419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php group array together based on key value being the same I have the following array
Array
(
[0] => Array
(
[id_product_option] => 1
[id_option] => 1
[id_product] => 3
[option_value] => White
[option_name] => color
)
[1] => Array
(
[id_product_option] => 2
[id_option] => 2
[id_product] => 3
[option_value] => 9oz
[option_name] => size
)
[2] => Array
(
[id_product_option] => 3
[id_option] => 1
[id_product] => 3
[option_value] => Blue
[option_name] => color
)
)
What i need to do is loop through it and find the ones where the id_option values match and group them into a new array that should look like
Array
(
[0] => Array
[0] => Array
(
[id_product_option] => 1
[id_option] => 1
[id_product] => 3
[option_value] => White
[additional_cost] => 0
[is_active] => 1
[created_on] => 2014-11-15 01:29:35
[option_name] => color
[option_text] => Color
)
[1] => Array
(
[id_product_option] => 3
[id_option] => 1
[id_product] => 3
[option_value] => Blue
[additional_cost] => 0
[is_active] => 1
[created_on] => 2014-11-15 01:29:35
[option_name] => color
[option_text] => Color
)
[1] => Array
(
[id_product_option] => 2
[id_option] => 2
[id_product] => 3
[option_value] => 9oz
[additional_cost] => 0
[is_active] => 1
[created_on] => 2014-11-15 01:29:35
[option_name] => size
[option_text] => Size
)
)
where the options with id_option 1 are grouped together
I tried the following but no luck
$groupOptions = array();
$prev = "";
foreach($productOptions as $key=>$options) {
$id_option = $options['id_option'];
if($id_option != $prev) {
$groupOptions[] = $productOptions[$key];
}
$prev = $id_option;
}
A: You should use that id_option as the key in your new array, otherwise you're stuck having to hunt through the new array to find where the matching items are, which you're ALREADY doing in the first loop
$newarray = array();
foreach($oldarray as $item) {
$newarray[$item['id_option']][] = $item;
}
A: I have tested with you example and seems to work fine :
$notFactored; # you should provide here your input array
$factored = array();
foreach($notFactored as $nf) {
$found = FALSE;
foreach($factored as &$f) { # passed by address !
if(!empty($f[0]) && $nf['id_option'] == $f[0]['id_option']) {
$f[] = $nf;
$found = TRUE;
break;
}
}
if(!$found) {
$factored[count($factored)][] = $nf;
}
}
print 'my factored array : ' . print_r($factored);
Hope that Helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27024299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change Icon on Bootstrap 4.6 accordion I want to have a 'plus' icon when the accordion is collapsed, and a 'minus' icon when the accordion is 'expanded'.
I have checked other answers on the internet, but what am I asking is can't I do something simple like this? (For learning purposes)
Say I place both the plus and minus icons on the accordion
<i class="fa-plus"> <i class="fa-minus">
As I see, when the accordion is collapsed, it has a collapsed class, so I'd like to hide and show both the icons as the collapsed class gets toggled on click. Why doesn't it work as the DOM gets updated when the accordion is clicked?
if(document.getElementById('candidateName').classList.contains('collapsed')) {
document.querySelector('.fa-minus').style.display = 'none';
document.querySelector('.fa-plus').style.display = 'block';
}
else {
document.querySelector('.fa-plus').style.display = 'none';
document.querySelector('.fa-minus').style.display = 'block';
}
Please note that this is just for learning purposes. I want to understand this, please don't get offended. Thankyou
A: Glad you are learning. Apologies if my response comes across in a different plane than your current level.
When you run JS, you're executing the code in the current state of the content. It appears that you are hoping for the icon to change from a + to a - and vice verse when the accordion is expanded/collapsed.
What you need to do, is watch the page for changes to the accordion - these are called event listeners. Bootstrap has some really convenient ones that you can use for this. Since the Accordion uses collapse events API. From there, you can watch the page for changes, and execute the change you want whenever that change happens.
const myCollapsible = document.getElementById('myCollapsible')
myCollapsible.addEventListener('hidden.bs.collapse', event => {
// do something...
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73417196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to push data from AWS IoT MQTT broker to a random file in S3 bucket I have created a rule to forward all messages published to any topic e.g. foo/bar of my AWS IoT core managed MQTT broker to a nested folder in S3 bucket. For that, I am using key section. I can send data to nested folder like a/b/c. The problem is - it takes c as destination file and this file gets updated with new data as it arrives. Is there any configuration that I can do to put data in bucket in a new file (with any random name) as it arrives (similar to how it happens when we forward data from firehose to S3)
A: You can change your key to use the newuuid() function. e.g.
a/b/${newuuid()}
This will write the data to a file in the a/b folder with a filename that is a generated UUID.
The key in AWS IoT S3 Actions allow you to use the IoT SQL Reference Functions to form the folder and filename.
The documentation for the key states:
The path to the file where the data is written. For example, if the value of this argument is "${topic()}/${timestamp()}", the topic the message was sent to is "this/is/my/topic,", and the current timestamp is 1460685389, the data is written to a file called "1460685389" in the "this/is/my/topic" folder on Amazon S3.
If you don't want to use a timestamp then you could form the name of the file using other functions such as a random float (rand()), calculate a hash (md5()), a UUID (newuuid()) or the trace id of the message (traceid()).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54441780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wordpress + Divi: Custom Section Toggle I have a child theme editing the main-structure-elements.php file from the Divi parent theme. I have tried to override this file by moving it into the child theme and making the changes there, as well as modifying the functions.php file to require that file, still no luck.
I just need to add a toggle to the Divi sections that adds a css filter. This is the code I have written in the main-structure-elements.php file which works great in the main divi file but is unrecognized if added just in the child theme file.
public function get_fields() {
$fields = array(
'fullpage_height' => array(
'label' => esc_html__( 'Enable Fullpage', 'et_builder' ),
'type' => 'yes_no_button',
'option_category' => 'configuration',
'options' => array(
'off' => et_builder_i18n( 'No' ),
'on' => et_builder_i18n( 'Yes' ),
),
'default' => 'off',
'description' => esc_html__( 'Here you can select whether or not your page should have Full Height enabled. This must be enabled on all sections to function', 'et_builder' ),
'tab_slug' => 'advanced',
'toggle_slug' => 'layout',
'default_on_front' => 'off',
),
this code then is triggering this code later in that same file.
if ( 'on' === $fullpage_height ) {
$this->add_classname( 'fullpage-vertical' );
}
I have been working on this for days, any insight would be a life saver
A: Did you try run this code as snippet using plugin "Code Snippets"? Maybe at this way the code will work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68371107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java: show compiler phases like `scalac -Xprint:parser` javac -Xprint only shows the class's API.
i can write a scala program, compile it with scalac -Xprint:<phase>, and print out the tree with whatever processing has done at any phase.
i want something that can emit the representation at each of the fundamental stages of java compilation:
$ javac -Xshow-phases
phase name description
---------- -----------
parser parse source into ASTs, perform simple desugaring
namer resolve names, attach symbols to named trees
packageobjects load package objects
typer the meat and potatoes: type the trees
superaccessors add super accessors in traits and nested classes
refchecks reference/override checking, translate nested objects
erasure erase types
flatten eliminate inner classes
jvm generate JVM bytecode
does such an option or tool exist? how could we do this in java?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23318933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I group objects by similiar items that they contain? I have 10,000 baskets.
In each basket, I have 10 food objects, no repetitions.
I need to group baskets in groups where all baskets in the group have >=6 of the same objects within them, with no repetitions in any group. Basically, if a group has basket1, basket2, basket33, basket 123, then no other groups will have them.
When I try to do it with combinations, I end up with many redundant groups.
from typing import Generic, TypeVar, List
import random
from uuid import uuid4
import attr
T = TypeVar("T")
food = ['apple', 'banana','grapes','orange','potato','kiwi','pomegranate','blueberry','strawberry','cantalope','honeydew','papaya','mango','raspberry',
'celery','carrot','potato','raddish','lettuce','tomato','garlic','onion','cabbage','corn','shallot','peas','squash','broccoli','spinach']
#'pasta','sugar','flour','honey','salt','pepper','corn starch','baking soda','cinnamon','paprika','butter','cream','chocolate']
@attr.dataclass
class Basket(Generic[T]):
items: List[T]
volume: int
id: str = attr.ib(factory=lambda: str(uuid4()))
#Generate baskets
basket_names = [f"basket{i}" for i in range(1, 10001)]
baskets: List[Basket[str]] = [
Basket(items=random.sample(food, 10), volume=random.randint(0, 1000), id=name)
for name in basket_names
]
A: Here is a solution using scikit-learn.
*
*sklearn.preprocessing.MultiLabelBinarizer to transform each basket into a 0-1 vector with one coordinate per food type;
*sklearn.cluster.AgglomerativeClustering to make clusters, with baskets in the same cluster if they differ by at most 8 food types (8 = 2 * 4 = 2 * (10 - 6), so if two baskets have exactly 6 food types in common, then their vectors will differ by 8 coordinates)
*AgglomerativeClustering().fit_predict() returns a list of numbers: number x at index i in the list means that the ith basket is in the xth cluster.
*itertools.groupby with zip can be used to get the clusters as a list of lists of baskets.
import random
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import MultiLabelBinarizer
from itertools import groupby
from operator import itemgetter
n_baskets = 10000
n_foodperbasket = 10
n_samefoodpercluster = 6
max_volume = 1000
food = sorted(['apple', 'banana','grapes','orange','potato','kiwi','pomegranate','blueberry',
'strawberry','cantalope','honeydew','papaya','mango','raspberry', 'celery','carrot',
'raddish','lettuce','tomato','garlic','onion','cabbage','corn','shallot',
'peas','squash','broccoli','spinach']) # removed your duplicate 'potato'
baskets = [(random.sample(food, n_foodperbasket), random.randint(0,max_volume), i) for i in range(n_baskets)]
vectorbaskets = MultiLabelBinarizer(classes=food).fit_transform([b[0] for b in baskets])
clustering = AgglomerativeClustering(n_clusters=None, distance_threshold=2*(n_foodperbasket - n_samefoodpercluster))
clusters = clustering.fit_predict(vectorbaskets)
groups = [list(g) for k,g in groupby(sorted(zip(clusters, baskets)), key=itemgetter(0))]
print(groups)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69659707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Grooy/Grails or Java : viewing YouTube videos marked private Greatings!
I've been tasked on a groovy/grails project to display YouTube videos relating to the project that are marked private. I'm guessing they want to keep the videos accessible but only through their site. So I've been given the YouTube dev api guide and asked to make it work.
Got my dev key and I'm still waiting for client login info but, wonder if I'm even barking up the right tree.
I very briefly looked over the guide, but would like to know if there are any samples/guides using this in web app environment.
Thanks
A: There doesn't appear to be any Groovy specific information. Since Groovy uses the JVM and can call java librarys with out any problem take a look at the YOutube Java developers guide Everything in it should apply to Groovy/Grails.
A: ... so I had a chance to look over the api in greater detail and I still don't see a way to make private videos publicly viewable without 'unprivating' them. Am I missing something? At this point I'm just trying to document that what I'm getting asked to do can't or at least should not be done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5681241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to sum dynamically added column values? I have dynamically added rows that I need to sum.
Added columns and total will be displayed in separate fields.
I want to sum user enter data one particular column that is "DEBIT*" columns. for example user enter 1st row on debit coloumn 100rs and user click add new row and enter 100rs that amount will be calculate and show the total field..
Here is my code.
Faild Fiddle here
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cashacc = 'cashacc' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' placeholder="NNNN" /></td><td><select class="form-control" id="cashacc" ><option value="">TDS A/C Name1</option><option value="1">Joe</option><option value="2">Joe</option><option value="3">Joe</option></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
/* second row */
var ctr = 1;
var FieldCount = 1;
$('#sndRow').on('click', '.button-add', function() {
ctr++;
var rowNum = 'rowNum' + ctr;
var cashacc_nme = 'cashacc_nme' + ctr;
var acc_narrat = 'acc_narrat' + ctr;
var accdeb = 'accdeb' + ctr;
var accCredit = 'accCredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + rowNum + ' placeholder="NNNN" /></td><td><select class="form-control" id="cashacc_nme" ><option value="">Account Name 1</option><option value="1">Plumz</option><option value="2">Plumz</option><option value="3">Plumz</option></select></td><td><input type="text" class=' + "joe" + ' id=' + acc_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe debClass" + ' id=' + accdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + accCredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<thead>
<tr>
<th>A/c Code</th>
<th>Account Name*</th>
<th>Narration*</th>
<th>Debit*</th>
<th>Credit</th>
</tr>
</thead>
<tbody>
<tr id="fst_row">
<td>
<input type="number" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashacc_code" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" class="form-control" name="cashdeb" readonly />
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly />
</td>
<td class="tblBtn" style="width: 4%">
<a href="#"><img src="./img/plus.svg" class="insrt-icon button-add"></a>
<a href="#"><img src="./img/delete.svg" class="dlt-icon dlt-icon"></a>
</td>
</tr>
<tr id="sndRow">
<td>
<input type="number" class="form-control" id="rowNum" name="cashaccCode" placeholder="NNNN" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc_nme" id="cashacc_nme">
<option value="#">Choose and items</option>
<option value="1">Joe</option>
<option value="2">Joe2</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" class="form-control debClass" id="accdeb" placeholder="NNNNNN" name="accdeb" />
</td>
<td>
<input type="number" id="accCredit" class="form-control" name="accCredit" readonly />
</td>
<td style="width: 4%">
<a href="#"><img src="./img/plus.svg" id="debsum" class="insrt-icon button-add"></a>
<a href="#"><img src="./img/delete.svg" class="dlt-icon"></a>
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="totaldbt" readonly>
</div>
</div>
I am just beginner, any help would be grateful.
Thank you.
A: EDIT: I'm sorry Joe, it looks like I attached your fiddle to the link other than my updated copy. Please check the link out again.
I've created a JSfiddle using yours for a working example.
I modified your code to make it easier by adding an attribute on your debit input of data-action="sumDebit" and added in this snippet.
$('body').on('change', '[data-action="sumDebit"]', function() { //Attach an event to body that binds to all tags that has the [data-action="sumDebit"] attribute. This will make sure all over dynamically added rows will have the trigger without us having to readd after ever new row.
var total = 0;
$('[data-action="sumDebit"]').each(function(i,e) { //Get all tags with [data-action="sumDebit"]
var val = parseFloat(e.value); //Get int value from string
if(!isNaN(val)) //Make sure input was parsable. If not, result come back as NaN
total += val;
});
$('#totaldbt').val(total); //Update value to total
});
A: I have fixed your code. please check it.
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cashacc = 'cashacc' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' name="cashaccCode" onchange="calSum()" keyup="calSum()" placeholder="NNNN" /></td><td><select class="form-control" id="cashacc" ><option value="">TDS A/C Name1</option><option value="1">Joe</option><option value="2">Joe</option><option value="3">Joe</option></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
/* second row */
var ctr = 1;
var FieldCount = 1;
$('#sndRow').on('click', '.button-add', function() {
ctr++;
var rowNum = 'rowNum' + ctr;
var cashacc_nme = 'cashacc_nme' + ctr;
var acc_narrat = 'acc_narrat' + ctr;
var accdeb = 'accdeb' + ctr;
var accCredit = 'accCredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + rowNum + ' name="cashaccCode" onchange="calSum()" keyup="calSum()" placeholder="NNNN" /></td><td><select class="form-control" id="cashacc_nme" ><option value="">Account Name 1</option><option value="1">Plumz</option><option value="2">Plumz</option><option value="3">Plumz</option></select></td><td><input type="text" class=' + "joe" + ' id=' + acc_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe debClass" + ' id=' + accdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + accCredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<tbody>
<tr id="fst_row">
///First row
<td>
<input type="number" onchange="calSum()" keyup="calSum()" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashaccCode" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" class="form-control" name="cashdeb" readonly />
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly />
</td>
<td class="tblBtn" style="width: 4%">
<a href="#"><img src="./img/plus.svg" class="insrt-icon button-add"></a>
<a href="#"><img src="./img/delete.svg" class="dlt-icon dlt-icon"></a>
</td>
</tr>
//// second row
<tr id="sndRow">
<td>
<input type="number" onchange="calSum()" keyup="calSum()" class="form-control" id="rowNum" name="cashaccCode" placeholder="NNNN" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc_nme" id="cashacc_nme">
<option value="#">Choose and items</option>
<option value="1">Joe</option>
<option value="2">Joe2</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" class="form-control debClass" id="accdeb" placeholder="NNNNNN" name="accdeb" />
</td>
<td>
<input type="number" id="accCredit" class="form-control" name="accCredit" readonly />
</td>
<td style="width: 4%">
<a href="#"><img src="./img/plus.svg" id="debsum" class="insrt-icon button-add"></a>
<a href="#"><img src="./img/delete.svg" class="dlt-icon"></a>
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="totaldbt" readonly>
</div>
</div>
<script>
function calSum(){
var calvalue = 0;
$("input[name*='cashaccCode']").each( function( key, item ) {
//alert( key + ": " + item.value );
calvalue = calvalue + parseFloat(item.value);
});
$("#totaldbt").val(calvalue);
$
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58143623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Generate list month 1 year above from current month Currently I want to create function to generate list 1 year above (for example the current month is august 2021, I want to create list from july 2021 - august 2020) any recommend class or built-in function in dart/ flutter?
this is the current code
void getListOfMonthAYear() {
List<String> months = [];
Map<int, String> listOfMonth = {
1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'
};
DateTime currentDate = DateTime.now();
int listMonthFor1Year = DateTime.monthsPerYear;
int currentMonth = DateTime.now().month;
for (int i = 0; i < listMonthFor1Year; i++) {
print(listOfMonth[currentMonth - i]);
}
}
After january, the list become null (ya because the month below 1 is not found).
A: Something like this?
void main() {
getMonthAYearFromCurrent().forEach(print);
// August 2021
// July 2021
// June 2021
// May 2021
// April 2021
// March 2021
// February 2021
// January 2021
// December 2020
// November 2020
// October 2020
// September 2020
}
List<String> getMonthAYearFromCurrent({int length = 12}) {
const listOfMonth = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
final currentDate = DateTime.now();
final months = <String>[];
for (var i = 0; i < length; i++) {
final yearInt = currentDate.year - (0 - (currentDate.month - i) + 12) ~/ 12;
final monthInt = (currentDate.month - i - 1) % 12;
months.add('${listOfMonth[monthInt]} $yearInt');
}
return months;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68723086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to generate a horizontal sinusoidal text in C without graphics.h? I am trying to write a program on generating a sinusoidal text in C. I tried the code below and got a vertical sine wave. Is it possible to make it horizontal? I am new to C programming, so if you could, please explain the code in simplest manner. Thank you!
#include <stdio.h>
#include <math.h>
int main()
{
// declarations
int x;
char y[80];
char str[] = "This is a test string";
// setting entire array to spaces
for(x = 0; x < 79; x++)
y[x] = ' ';
y[79] = '\0';
// print 20 lines, for one period (2 pi radians)
for(x = 0; str[x]!='\0'; x++)
{
y[40 + (int) (40 * sin(M_PI * (float) x /10))] = str[x];
printf("%s\n", y);
y[40 + (int) (40 * sin(M_PI * (float) x / 10))] = ' ';
}
// exit
return 0;
}
Output:
T
h
i
s
s
a
t
e
s
t
s
t
r
i
n
g
Is it possible to make the wave horizontal without changing the existing code? Thank you!
A: I wrote an answer to your question, which works, maybe not completly as you expect but it should give you enough to work with
note the following:
*
*after you wrote to the console\file it is very difficult to return and change printed values
*you must define your desiered output matrix and prepare the entire output before you print anything
the logic behine my example is this:
*
*create a matrix (80*22)
*fill the matrix with spaces
*fill the matrix by columns
*print the entire matrix by char;
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
// declarations
int col, row;
char str[] = "This is a test string";
/* define the screen for print (80 width * 22 length)*/
char printout[80][22];
// setting entire matrix to spaces
for (row=0; row < 22 ; row++)
{
for(col = 0; col < 80; col++)
printout[col][row] = ' ';
}
/* fill in the columns modulo the string to allow continuous output */
for(col = 0; col < 80 ; col++)
{
printout[col][10 + (int) (10 * sin(M_PI * (float) col /10))] = str[( col % strlen(str) )];
}
/* printout the entire matrix formatted */
for (row = 0 ; row < 22 ; row++) {
for (col = 0 ; col < 80 ; col++) {
printf("%c", printout[col][row]);
}
printf("\n");
}
// exit
return 0;
}
there are many thing to correct in this code - the rows should consider the size of the string, you should parse it as string not char etc.
but again it does give you what you want and it might help you to continue...
s t s
t t s s e t
t r s t e s t
s i e r t t s
e n t i r a t
T t g n a i
h T a g n s
i a h T s g i
s i s h i T
s s i i h s
i s i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49213910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: PHP Using DOMXPath to strip tags and remove nodes I am trying to work with DOMDocument but I am encountering some problems. I have a string like this:
Some Content to keep
<span class="ice-cts-1 ice-del" data-changedata="" data-cid="5" data-time="1414514760583" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
This content should remain, but span around it should be stripped
</span>
Keep this content too
<span>
<span class="ice-cts-1 ice-ins" data-changedata="" data-cid="2" data-time="1414512278297" data-userid="1" data-username="Site Administrator" undefined="Site Administrator">
This whole node should be deleted
</span>
</span>
What I want to do is, if the span has a class like ice-del keep the inner content but remove the span tags. If it has ice-ins, remove the whole node.
If it is just an empty span <span></span> remove it as well. This is the code I have:
//this get the above mentioned string
$getVal = $array['body'][0][$a];
$dom = new DOMDocument;
$dom->loadHTML($getVal );
$xPath = new DOMXPath($dom);
$delNodes = $xPath->query('//span[@class="ice-cts-1 ice-del"]');
$insNodes = $xPath->query('//span[@class="ice-cts-1 ice-ins"]');
foreach($insNodes as $span){
//reject these changes, so remove whole node
$span->parentNode->removeChild($span);
}
foreach($delNodes as $span){
//accept these changes, so just strip out the tags but keep the content
}
$newString = $dom->saveHTML();
So, my code works to delete the entire span node, but how do I take a node and strip out it tags but keep its content?
Also, how would I just delete and empty span? I'm sure I could do this using regex or replace but I kind of want to do this using the dom.
thanks
A: No, I wouldn't recommend regex, I strongly recommend build on what you have right now with the use of this beautiful HTML Parser. You could use ->replaceChild in this case:
$dom = new DOMDocument;
$dom->loadHTML($getVal);
$xPath = new DOMXPath($dom);
$spans = $xPath->query('//span');
foreach ($spans as $span) {
$class = $xPath->evaluate('string(./@class)', $span);
if(strpos($class, 'ice-ins') !== false || $class == '') {
$span->parentNode->removeChild($span);
} elseif(strpos($class, 'ice-del') !== false) {
$span->parentNode->replaceChild(new DOMText($span->nodeValue), $span);
}
}
$newString = $dom->saveHTML();
A: More generic solution to delete any HTML tag from a DOM tree use this;
$dom = new DOMDocument;
$dom->loadHTML($getVal);
$xPath = new DOMXPath($dom);
$tagName = $xPath->query('//table'); //use what you want like div, span etc.
foreach ($tagName as $t) {
$t->parentNode->removeChild($span);
}
$newString = $dom->saveHTML();
Example html:
<html>
<head></head>
<body>
<table>
<tr><td>Hello world</td></tr>
</table>
</body>
</html>
Output after process;
<html>
<head></head>
<body></body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26677257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get a reference to target element inside a callback I'm building a component which displays a series of generic input fields. The backing store uses a simple array of key-value pairs to manage the data:
[
{fieldkey: 'Signs and Symptoms', value:'fever, rash'},
{fieldkey: 'NotFeelingWell', value:'false'},
{fieldkey: 'ReAdmission', value:'true'},
{fieldkey: 'DateOfEvent', value:'12/31/1999'}
]
In order to eliminate a lot of boilerplate code related to data binding, the component uses these same keys when generating the HTML markup (see 'data-fieldname' attribute).
var Fields = React.createClass({
handleOnChange:function(e){
Actions.updateField( {key:e.target.attributes['data-fieldname'].value, value:e.target.value})
},
setValue:function(){
var ref = //get a reference to the DOM element that triggered this call
ref.value = this.props.form.fields[ref.attributes['data-fieldname']]
},
render:function(){
return (<div className="row">
<Input data-fieldname="Signs and Symptoms" type="text" label='Notes' defaultValue="Enter text" onChange={this.handleOnChange} value={this.setValue()} />
<Input data-fieldname="NotFeelingWell" type="checkbox" label="Not Feeling Well" onChange={this.handleOnChange} value={this.setValue()} />
<Input data-fieldname="ReAdmission" type="checkbox" label="Not Feeling Great" onChange={this.handleOnChange} value={this.setValue()} />
<Input data-fieldname="DateOfEvent" type="text" label="Date Of Event" onChange={this.handleOnChange} value={this.setValue()} />
</div>)
}
})
My goal is to use the same two functions for writing/reading from the store for all inputs and without code duplication (i.e. I don't want to add a refs declaration to each input that duplicates the key already stored in 'data-fieldname') Things work swimmingly on the callback attached to the 'onChange' event. However, I'm unsure how to get a reference to the DOM node in question in the setValue function.
Thanks in advance
A: I'm not sure if I understand your question right, but to reduce boilerplate I would map your array to generate input fields:
render:function(){
var inputs = [];
this.props.form.fields.map(function(elem){
inputs.push(<Input data-fieldname={elem.fieldkey} type="text" label="Date Of Event" onChange={this.handleOnChange} value={elem.value} />);
});
return (<div className="row">
{inputs}
</div>)
}
This will always display your data in props. So when handleOnChange gets triggered the component will rerender with the new value. In my opinion this way is better than accessing a DOM node directly.
A: If you want to use dynamic information on the input, you need to pass it through the array, and make a loop.
Here is a little example based on Dustin code:
var fieldArray = [ //replace by this.props.form.fields
{
fieldkey: 'Signs and Symptoms',
value: 'fever, rash',
type: 'text',
label: 'Notes'
},
{
fieldkey: 'NotFeelingWell',
value: 'false',
type: 'checkbox',
label: 'Not Feeling Well'
},
];
var Fields = React.createClass({
handleOnChange:function(e){
var fieldKey = e.target.attributes['data-fieldname'].value;
Actions.updateField({
key: fieldKey,
value: e.target.value
})
},
render() {
var inputs = [];
fieldArray.map(function(field) { //replace by this.props.form.fields
inputs.push(
<Input
data-fieldname={field.fieldkey}
value={field.value}
type={field.type}
label={field.label}
onChange={this.handleOnChange} />
);
}.bind(this));
return (
<div className="row">
{inputs}
</div>
);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29682321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Resque with Rails 3 + Heroku + RedisToGo giving Postgresql error I'm writing an app which needs to send many emails and creates many user notifications because of these emails. This task produces a timeout in Heroku. To solve this, I decided to use Resque and RedistToGo.
What I did was to send the email (it's actually just one email because we use Sendgrid to handle this) and create the notifications using a Resque worker. The email is already created, so I send its id to the worker, along with all the recipients.
This works fine locally. In production, unless we restart our app in Heroku, it only works once. I will post some of my code and the error message:
#lib/tasks/resque.rake
require 'resque/tasks'
task "resque:setup" => :environment do
ENV['QUEUE'] = '*'
end
desc "Alias for resque:work (To run workers on Heroku)"
task "jobs:work" => "resque:work"
#config/initalizers/resque.rb
ENV["REDISTOGO_URL"] ||= "redis://redistogo:some_hash@some_url:some_number/"
uri = URI.parse(ENV["REDISTOGO_URL"])
Resque.redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
Dir["#{Rails.root}/app/workers/*.rb"].each { |file| require file }
#app/workers/massive_email_sender.rb
class MassiveEmailSender
@queue = :massive_email_queue
def self.perform(email_id, recipients)
email = Email.find(email_id.to_i)
email.recipients = recipients
email.send_email
end
end
I've got an Email model which has an after_create that enqueues the worker:
class Email < ActiveRecord::Base
...
after_create :enqueue_email
def enqueue_email
Resque.enqueue(MassiveEmailSender, self.id, self.recipients)
end
...
end
This Email model also has the send_email method which does what I said before
I'm getting the following error message. I'm gonna post all the information Resque gives to me:
Worker
9dddd06a-2158-464a-b3d9-b2d16380afcf:1 on massive_email_queue at just now
Retry or Remove
Class
MassiveEmailSender
Arguments
21
["[email protected]", "[email protected]"]
Exception
ActiveRecord::StatementInvalid
Error
PG::Error: SSL error: decryption failed or bad record mac : SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull FROM pg_attribute a LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attrelid = '"emails"'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:1139:in `async_exec'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:1139:in `exec_no_cache'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:663:in `block in exec_query'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `block in log'
/app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.2/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'
/app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.3.2/lib/new_relic/agent/instrumentation/active_record.rb:31:in `block in log_with_newrelic_instrumentation'
/app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.3.2/lib/new_relic/agent/method_tracer.rb:242:in `trace_execution_scoped'
/app/vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-3.3.2/lib/new_relic/agent/instrumentation/active_record.rb:28:in `log_with_newrelic_instrumentation'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:662:in `exec_query'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:1264:in `column_definitions'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/postgresql_adapter.rb:858:in `columns'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/connection_adapters/schema_cache.rb:12:in `block in initialize'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/model_schema.rb:228:in `yield'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/model_schema.rb:228:in `default'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/model_schema.rb:228:in `columns'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/model_schema.rb:237:in `columns_hash'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/relation/delegation.rb:7:in `columns_hash'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/relation/finder_methods.rb:330:in `find_one'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/relation/finder_methods.rb:311:in `find_with_ids'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/relation/finder_methods.rb:107:in `find'
/app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.2/lib/active_record/querying.rb:5:in `find'
/app/app/workers/massive_email_sender.rb:5:in `perform'
According to this, the first argument is the email id, and the second one is the list of all recipients... exactly as it should be.
Can anyone help me? Thanks!
A: I've run into the same problem. Assuming you're using Active Record you have to call ActiveRecord::Base.establish_connection for each forked Resque worker to make sure it doesn't have a stale database connection. Try putting this in your lib/tasks/resque.rake
task "resque:setup" => :environment do
ENV['QUEUE'] = '*'
Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection }
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9915146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Are there any tools to monitor performance of Puma process queuing in Rails? I'm trying to isolate puma process queuing as requests come into my application. I've adde middleware to determine the time between requests being received and responses sent back. Though, I'd like to see if, for whatever reason, Puma is taking a long time or workers aren't efficiently handling requests in the queue. I can't find any good tools to benchmark requests in development.
A: You can use rack-mini-profiler gem to monitor time response. It will display result top left corner. And by default rails does what you want. You can check the response time on the bottom of every request.
Completed 200 OK in 2203ms (Views: 95.3ms | ActiveRecord: 71.5ms)
I strongly recommend you to use NewRelic for monitoring your application. Because it will handle very smoothly on both your system level and application level. It will monitor your database too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45556461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to hide a form's frame at runtime I have a form. At runtime, how can I hide the form's frame? (The borders with the form name.)
A: Set the form's FormBorderStyle property to None.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10990274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cantor function translated from java to Python I wrote a cantor function in java and I'm trying to translate it to Python. Can anyone give me some pointers ? Should I compare the fractions as one variable each or treat the top and the bottom as separate variables?
java:
import java.util.Scanner;
public class asdf {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("ENter the nth ratio you want: ");
int end = keyboard.nextInt();
int count = 0;
int top = 0;
int bottom = 0;
boolean flip = true;
for(int i=0; i<end; i++){
if(flip){
top = i+1;
bottom = 1;
for(int j = 0; j<i+1; j++){
if(count == end){
break;
}
System.out.println(top + "/" + bottom);
top--;
bottom++;
count++;
}
flip = false;
}
else{
top = 1;
bottom = i+1;
for(int j = 0; j<i+1; j++){
if(count == end){
break;
}
System.out.println(top + "/" + bottom);
top++;
bottom--;
count++;
flip = true;
}
}
}
}
}
Python:
def cantor(dat):
n=len(dat)
count, top, bottom = 0,0,0
boolean flip = true
for i in range (0,x):
if (flip):
top = i+1
bottom = 1
for j in range(0,top):
if count == 21: break
boolean found = false
double temp = top*1.0/bottom
for k in range(0,n)):
if temp == n[k]:
found = true
break
if !
top = top-1
bottom = bottom+1
count = count+1
A: The java2py3 option of AgileUML should be able to translate this. Correctly-formatted Python3 is produced.
https://github.com/eclipse/agileuml/blob/master/translators.zip
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22480134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can we simply get the edges of the graphs when using networkx GraphMatcher? We use Python networkx GraphMatcher to find matchings of two graphs G1 and G2:
from networkx.algorithms import isomorphism
GM = isomorphism.GraphMatcher(G1, G2)
matchings_list = list(GM.subgraph_isomorphisms_iter())
For example, matchings_list is [{'4':'0', '11': '1', '8': '2', '7': '3'}, {'4': '0', '11': '1', '15': '2', '6': '3'}].
Each matching in the matchings_list is a dictionary whose keys are vertices of G1, and values are vertices of G2.
If we want to get vertices of G1, we can easily access like matching.keys().
But, how can we simply access the edges of G1?
The long way to access them is to traverse the edges of G2 with G2.edges, and get the corresponding G1 vertices from the matching (create a reverse dictionary of the matching since keys are G1' vertices), and create a tuple for making an edge.
A: But, using G1.subgraph(matching.keys()).edges is slower than the long way:
in_time = time.perf_counter()
g1_edge_list = []
for m in matchings:
m2 = {y: x for x, y in m.items()}
for e1, e2 in G2.edges:
g1_edge_list.append((m2[e1], m2[e2]))
out_time = time.perf_counter() - in_time
print(out_time)
in_time2 = time.perf_counter()
g1_edge_list = []
for m in matchings:
g1_edge_list += graph.subgraph(m.keys()).edges
out_time_2 = time.perf_counter() - in_time2
print(out_time_2)
It is approximately 12 times slower. @Timus
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64843968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Joomla! Unable to edit modules PHP codes I'm quite new to Joomla! as well as PHP.
Currently i'm developing a Joomla! site using Joomla! Version 1.5.14.
I have downloaded and installed VirtueMart 1.1.3 on my site and now i want to edit the registration fields for the VirtueMart Module.
I went to C:\xampp\htdocs\mysite\modules\mod_virtuemart and opened up the mod_virtuemart PHP script.
I only see these codes for the registration part:
<?php endif; ?>
<?php if( $mosConfig_allowUserRegistration == '1' ) : ?>
<tr>
<td colspan="2">
<?php echo $VM_LANG->_('NO_ACCOUNT'); ?>
<a href="<?php $sess->purl( SECUREURL.'index.php?option=com_virtuemart&page=mysite.registration' ); ?>">
<?php echo $VM_LANG->_('CREATE_ACCOUNT'); ?>
</a>
</td>
</tr>
<?php endif; ?>
But i'm unable to find the few lines of codes for the registration fields (For the user to key in).
Examples: Email, company name, title, first name, last name, etc... (with the text boxes beside them)
Hope you get what i mean.
Now i want to add in some more fields for registration, such as 'Position in company', etc..
Can anyone tell me specifically where to find those codes so that i can edit them?
A: As per my knowledge you should do it from admin panel. Joomla provide custom settings of fields for virtuemart user registration.
You also can refer below link for that.
http://virtuemart.net/documentation/User_Manual/User_Registration_Fields.html
I think this would be helpful to you.
Let me know if anything new you get.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8570870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check an input type=“file” has a file selected? I am developing an app with HTML, JavaScript and CSS3 with VS2012 (MetroApp)
I need to trigger a verification for enabling or disabling a button after adding a file on my
<input type="file"/>
so far I have this:
HTML: default.html:
<!DOCTYPE html>
<html>
<head>
<title>myApp</title>
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<div id="content">
<h1>myApp</h1>
<br /><br />
<button id="imageCaptureButton">Take Picture</button>
<input type="file" id="uploadCaptureInputFile"/><br />
<button id="uploadCaptureButton">Subir Foto</button>
<br /><br />
<div id="result"></div>
</div>
</body>
</html>
JavaScript: default.js
function getDomElements() {
_uploadCaptureButton = document.querySelector("#uploadCaptureButton");
_uploadCaptureInputFile = document.querySelector("#uploadCaptureInputFile");
}
function wireEventHandlers() {
_uploadCaptureInputFile.addEventListener("onchange", verifyControls, false);
}
app.onloaded = function () {
getDomElements();
wireEventHandlers();
_uploadCaptureButton.disabled = true;
}
function verifyControls() {
if ( _uploadCaptureInputFile != "") {
_uploadCaptureButton.disabled = false;
}
else {
_uploadCaptureButton.disabled = true;
}
}
But I can't make it work, it seems that
_uploadCaptureInputFile.addEventListener("onchange", verifyControls, false);
it doesn't obey, is there a way to assign this event to my inputType for trigger such verification??
thanks in advance
A: When listening with addEventListener, you listen for the change event which is just "change", not "onchange". Listening for "onchange" will never fire because there is never a matching event fired (unless you create a custom one yourself).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20292557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: start-all.sh: command not found. How do I fix this? I tried installing hadoop using this tutorial, link (timestamped the video from where problem occurs)
However, after formatting the namenode(hdfs namenode -format) I don't get the "name" folder in /abc.
Also the start-all.sh and other /sbin commands dont work.
P.S I did try installing hadoop as a single node which didnt work so I tried removing it, redoing everything as a double node setup, so i had to reformat the namenode..i dont know if that affected this somehow.
EDIT 1: I fixed the start-all.sh command not working because there was a mistake in .bashrc that i corrected.
However I get these error messages when running start-all.sh or start-dfs.sh etc.
hadoop@linux-virtual-machine:~$ start-dfs.sh
Starting namenodes on [localhost]
localhost: mkdir: cannot create directory ‘/usr/local/hadoop-2.10.0/logs’: Permission denied
localhost: chown: cannot access '/usr/local/hadoop-2.10.0/logs': No such file or directory
localhost: starting namenode, logging to /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-namenode-linux-virtual-machine.out
localhost: /usr/local/hadoop-2.10.0/sbin/hadoop-daemon.sh: line 159: /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-namenode-linux-virtual-machine.out: No such file or directory
localhost: head: cannot open '/usr/local/hadoop-2.10.0/logs/hadoop-hadoop-namenode-linux-virtual-machine.out' for reading: No such file or directory
localhost: /usr/local/hadoop-2.10.0/sbin/hadoop-daemon.sh: line 177: /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-namenode-linux-virtual-machine.out: No such file or directory
localhost: /usr/local/hadoop-2.10.0/sbin/hadoop-daemon.sh: line 178: /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-namenode-linux-virtual-machine.out: No such file or directory
localhost: mkdir: cannot create directory ‘/usr/local/hadoop-2.10.0/logs’: Permission denied
localhost: chown: cannot access '/usr/local/hadoop-2.10.0/logs': No such file or directory
localhost: starting datanode, logging to /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-datanode-linux-virtual-machine.out
localhost: /usr/local/hadoop-2.10.0/sbin/hadoop-daemon.sh: line 159: /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-datanode-linux-virtual-machine.out: No such file or directory
localhost: head: cannot open '/usr/local/hadoop-2.10.0/logs/hadoop-hadoop-datanode-linux-virtual-machine.out' for reading: No such file or directory
localhost: /usr/local/hadoop-2.10.0/sbin/hadoop-daemon.sh: line 177: /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-datanode-linux-virtual-machine.out: No such file or directory
localhost: /usr/local/hadoop-2.10.0/sbin/hadoop-daemon.sh: line 178: /usr/local/hadoop-2.10.0/logs/hadoop-hadoop-datanode-linux-virtual-machine.out: No such file or directory
Starting secondary namenodes [0.0.0.0]
The authenticity of host '0.0.0.0 (0.0.0.0)' can't be established.
ECDSA key fingerprint is SHA256:a37ThJJRRW+AlDso9xrOCBHzsFCY0/OgYet7WczVbb0.
Are you sure you want to continue connecting (yes/no)? no
0.0.0.0: Host key verification failed.
EDIT 2: Fixed the above error my changing the permissions to hadoop folder (in my case both hadoop-2.10.0 and hadoop)
start-all.sh works perfectly but namenode doesnt show up.
A: It's not clear how you setup your PATH variable. Or how the scripts are not "working". Did you chmod +x them to make them executable? Any logs output that comes from them at all?
The start-all script is available in the sbin directory of where you downloaded Hadoop, so just /path/to/sbin/start-all.sh is all you really need.
Yes, the namenode needs formatted on a fresh cluster. Using the official Apache Guide is the most up-to-date source and works fine for most.
Otherwise, I would suggest you learn about Apache Amabri, which can automate your installation. Or just use a Sandbox provided by Cloudera, or use many of the Docker containers that already exist for Hadoop if you don't care about fully "installing" it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59813573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unable to connect from my credential into Microsoft Sample Key Storage Provider (Cryptographic Provider Development Kit) My current environmental situation:
1. on the client side I installing the certificate issued from a window server (ADCS) with a
provider type (Microsoft Enhanced Cryptographic Provider v1.0) and a PFX private key in the certificate
store (my store).
2. Make command to check: certutil -store my .
3. Make connection with my credential provider to KSP through the article: this article by question
Issue: KSP (Key Storage Provider) is not being loaded at logon via a Credential Provider.
I wonder if the problem is below:
*
*Are the certificate(my store) associated private key not the Microsoft Sample Key Storage Provider type? (current: Microsoft Enhanced Cryptographic Provider v1.0)
I still do not know how to create a certificate, a private key with a provider named Microsoft Sample Key Storage Provider. Anyone know can just help me?
*In the ConstructAuthInfo(LPBYTE* ppbAuthInfo, ULONG *pulAuthInfoLen) function:
WCHAR szCardName [] = L ""; // no card name specified but you
can put one if you want
WCHAR szContainerName [] = L "my_key_name";
WCHAR szReaderName [] = L "";
WCHAR szCspName [] = L "Microsoft Sample Key Storage Provider";
WCHAR szPin [] = L "11111111";
-> What does this my_key_name mean? and can it set a value L ""; Is it OK?
-> I do not use a hardware smart card, WCHAR szPin [] is an optional value?
Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62443324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I make a signed apk with upload key? I follow Manage your app signing keys which states "To create an upload key for new apps, follow the instructions on sign your app."
I check here under section "Use google play App signing", which redirects me to Manage your app signing keys. This link is the same as the first link so I stuck in a loop of redirects.
I check under section "Generate a key and keystore" in sign your app which again links me to Manage your app signing keys.
If I check under section "Manually sign an APK" in sign your app I see note stating I should use my upload key if I wanted to sign with google play app signing and for more information I should check Manage your app signing keys.
I have no idea where to get the upload key. I am just in a redirect loop.
A: An "upload key" isn't really anything special- it is just another key in a keystore. You need to register this key as an upload key in the developer console for Google to recognize it as your upload key.
To generate an upload key, simply follow the steps for generating a key and a keystor under "Generate a key and keystore" on the Sign Your App documentation. The key you generate there will be your upload key.
Once you have your upload key generated, you need to export it using
keytool -export -rfc -keystore upload-keystore.jks -alias upload -file upload_certificate.pem
where upload-keystore.jks is the name of the keystore containing the key you want to use as an upload key and upload is the alias of the key.
Finally, you need to go to your app in the developer console, go to Release Management > App signing, then click the "Upload Public Key Certificate" button to upload the .pem file you generated earlier. This registers your key an "upload key" for that app.
A: Maybe you mean for Google App Signing?
All process is same like before by creating your key from AndroidStudio, choose Build -> Generate Signed APK -> Create new -> Back -> Then follow the dialog process.
So where is the Google App Signing?
per the Help page, it's a security feature for developer if you lose your key.
If you lose your keystore or think it may be compromised, Google Play App Signing makes it possible to request a reset to your upload key. If you're not enrolled in Google Play App Signing and lose your keystore, you'll need to publish a new app with a new package name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47835959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add elements to ArrayList I'm trying to add several events retrieved from a database to an ArrayList in order to populate a listview. I've created an event class and I've set up all the methods.
EventsFunctions eventsFunctions;
JSONParser jParser = new JSONParser();
JSONArray events = null;
ArrayList<Torneo> tornei;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.all_events);
tornei= new ArrayList<Torneo>();
LoadAllEvents eventsLoader = new LoadAllEvents();
[...]
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
public class LoadAllEvents extends AsyncTask<String, Integer, JSONObject>
{
LoadAllEvents()
{
eventsFunctions = new EventsFunctions();
}
@Override
protected void onPreExecute()
{
[...]
}
protected JSONObject doInBackground(String... params)
{
String a = "code1";
// getting JSON string from URL
return eventsFunctions.eventList(a);
}
protected void onPostExecute(JSONObject json)
{
// Check your log cat for JSON reponse
Log.d("All Events list data: ", json.toString());
try
{
// Checking for SUCCESS TAG
String success = json.getString(TAG_SUCCESS);
if (success != null)
{
if (Integer.parseInt(json.getString(TAG_SUCCESS)) != 0)
{
// events found
// Getting Array of Events
events = json.getJSONArray(TAG_EVENTS);
Log.e("AllEventsActivity"," "+ Integer.toString(events.length())+ " events received from the database");
This is the relevant part of the code
// looping through All Products
for (int i = 0; i < events.length(); i++)
{
JSONObject c = events.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
Torneo torneo = new Torneo();
torneo.setName(name);
Log.e("AllEventsActivity", "Tournament name: " + torneo.getName());
tornei.add(i,torneo); //Or just tornei.add(torneo);
}
for (int j=0; j<tornei.size() ;j++ )
{
Log.e("AllEvents Reporter", "Torneo numero: "+ j + " Nome: " + tornei.get(j).getName());
}
}
And the end of the AsyncTask implementation:
else if (Integer.parseInt(json.getString(TAG_SUCCESS)) != 0)
{
Log.d("Events Report: ", "NO events scheduled");
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
// updating UI from Background Thread
[...]
}
And this is the output:
E/AllEventsActivity(10785): 4 events received from the database
E/AllEventsActivity(10785): Tournament name: One way
E/AllEventsActivity(10785): Tournament name: Super 5
E/AllEventsActivity(10785): Tournament name: Main Event 2013
E/AllEventsActivity(10785): Tournament name: First step
E/AllEvents Reporter(10785): Torneo numero: 0 Nome: First step
E/AllEvents Reporter(10785): Torneo numero: 1 Nome: First step
E/AllEvents Reporter(10785): Torneo numero: 2 Nome: First step
E/AllEvents Reporter(10785): Torneo numero: 3 Nome: First step
I/MemoryCache(10785): MemoryCache will use up to 16.0MB
D/dalvikvm(10785): GC_FOR_ALLOC freed 153K, 7% free 12544K/13383K, paused 22ms, total 22ms
I/dalvikvm-heap(10785): Grow heap (frag case) to 12.958MB for 262160-byte allocation
It seems that the only event stored in the Arraylist is the last element added in the for loop.
The log should have been like this:
E/AllEvents Reporter(10785): Torneo numero: 0 Nome: One way
E/AllEvents Reporter(10785): Torneo numero: 1 Nome: Super 5
E/AllEvents Reporter(10785): Torneo numero: 2 Nome: Main Event 2013
E/AllEvents Reporter(10785): Torneo numero: 3 Nome: First step
this is the json string parsed:
{"error":0,"success":1,"events":[{"uid":"Event_51796139b113d8.73834778","id":"58","name":"One},{"uid":"Event_5179625c988f60.49787125","id":"59","name":"Super
5"},{"uid":"Event_517969f6ac59d3.04395373","id":"60","name":"Main
Event
2013",},{"uid":"Event_517ab1f1bb91c0.03505404","id":"61","name":"First
step"}], "tag":"listimage"}
Do you have any advice?
A: Did you copy and paste your code, or retype it? It seems as though what your log is outputting might be because the line you've shown above:
Log.e("AllEvents Reporter", "Torneo numero: "+ j + " Nome: " + tornei.get(j).getName());
is actually
Log.e("AllEvents Reporter", "Torneo numero: "+ j + " Nome: " + tornei.get(i).getName());
where tornei.get(i).getName() would just output the last one in the dataset, which is what you're seeing, but this is just a guess. As Bill has said, your code seems fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16283039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recursively rename files using find and sed I want to go through a bunch of directories and rename all files that end in _test.rb to end in _spec.rb instead. It's something I've never quite figured out how to do with bash so this time I thought I'd put some effort in to get it nailed. I've so far come up short though, my best effort is:
find spec -name "*_test.rb" -exec echo mv {} `echo {} | sed s/test/spec/` \;
NB: there's an extra echo after exec so that the command is printed instead of run while I'm testing it.
When I run it the output for each matched filename is:
mv original original
i.e. the substitution by sed has been lost. What's the trick?
A: You can do it without sed, if you want:
for i in `find -name '*_test.rb'` ; do mv $i ${i%%_test.rb}_spec.rb ; done
${var%%suffix} strips suffix from the value of var.
or, to do it using sed:
for i in `find -name '*_test.rb'` ; do mv $i `echo $i | sed 's/test/spec/'` ; done
A: You mention that you are using bash as your shell, in which case you don't actually need find and sed to achieve the batch renaming you're after...
Assuming you are using bash as your shell:
$ echo $SHELL
/bin/bash
$ _
... and assuming you have enabled the so-called globstar shell option:
$ shopt -p globstar
shopt -s globstar
$ _
... and finally assuming you have installed the rename utility (found in the util-linux-ng package)
$ which rename
/usr/bin/rename
$ _
... then you can achieve the batch renaming in a bash one-liner as follows:
$ rename _test _spec **/*_test.rb
(the globstar shell option will ensure that bash finds all matching *_test.rb files, no matter how deeply they are nested in the directory hierarchy... use help shopt to find out how to set the option)
A: The easiest way:
find . -name "*_test.rb" | xargs rename s/_test/_spec/
The fastest way (assuming you have 4 processors):
find . -name "*_test.rb" | xargs -P 4 rename s/_test/_spec/
If you have a large number of files to process, it is possible that the list of filenames piped to xargs would cause the resulting command line to exceed the maximum length allowed.
You can check your system's limit using getconf ARG_MAX
On most linux systems you can use free -b or cat /proc/meminfo to find how much RAM you have to work with; Otherwise, use top or your systems activity monitor app.
A safer way (assuming you have 1000000 bytes of ram to work with):
find . -name "*_test.rb" | xargs -s 1000000 rename s/_test/_spec/
A: This happens because sed receives the string {} as input, as can be verified with:
find . -exec echo `echo "{}" | sed 's/./foo/g'` \;
which prints foofoo for each file in the directory, recursively. The reason for this behavior is that the pipeline is executed once, by the shell, when it expands the entire command.
There is no way of quoting the sed pipeline in such a way that find will execute it for every file, since find doesn't execute commands via the shell and has no notion of pipelines or backquotes. The GNU findutils manual explains how to perform a similar task by putting the pipeline in a separate shell script:
#!/bin/sh
echo "$1" | sed 's/_test.rb$/_spec.rb/'
(There may be some perverse way of using sh -c and a ton of quotes to do all this in one command, but I'm not going to try.)
A: you might want to consider other way like
for file in $(find . -name "*_test.rb")
do
echo mv $file `echo $file | sed s/_test.rb$/_spec.rb/`
done
A: I find this one shorter
find . -name '*_test.rb' -exec bash -c 'echo mv $0 ${0/test.rb/spec.rb}' {} \;
A: Here is what worked for me when the file names had spaces in them. The example below recursively renames all .dar files to .zip files:
find . -name "*.dar" -exec bash -c 'mv "$0" "`echo \"$0\" | sed s/.dar/.zip/`"' {} \;
A: For this you don't need sed. You can perfectly get alone with a while loop fed with the result of find through a process substitution.
So if you have a find expression that selects the needed files, then use the syntax:
while IFS= read -r file; do
echo "mv $file ${file%_test.rb}_spec.rb" # remove "echo" when OK!
done < <(find -name "*_test.rb")
This will find files and rename all of them striping the string _test.rb from the end and appending _spec.rb.
For this step we use Shell Parameter Expansion where ${var%string} removes the shortest matching pattern "string" from $var.
$ file="HELLOa_test.rbBYE_test.rb"
$ echo "${file%_test.rb}" # remove _test.rb from the end
HELLOa_test.rbBYE
$ echo "${file%_test.rb}_spec.rb" # remove _test.rb and append _spec.rb
HELLOa_test.rbBYE_spec.rb
See an example:
$ tree
.
├── ab_testArb
├── a_test.rb
├── a_test.rb_test.rb
├── b_test.rb
├── c_test.hello
├── c_test.rb
└── mydir
└── d_test.rb
$ while IFS= read -r file; do echo "mv $file ${file/_test.rb/_spec.rb}"; done < <(find -name "*_test.rb")
mv ./b_test.rb ./b_spec.rb
mv ./mydir/d_test.rb ./mydir/d_spec.rb
mv ./a_test.rb ./a_spec.rb
mv ./c_test.rb ./c_spec.rb
A: To solve it in a way most close to the original problem would be probably using xargs "args per command line" option:
find . -name "*_test.rb" | sed -e "p;s/test/spec/" | xargs -n2 mv
It finds the files in the current working directory recursively, echoes the original file name (p) and then a modified name (s/test/spec/) and feeds it all to mv in pairs (xargs -n2). Beware that in this case the path itself shouldn't contain a string test.
A: if you have Ruby (1.9+)
ruby -e 'Dir["**/*._test.rb"].each{|x|test(?f,x) and File.rename(x,x.gsub(/_test/,"_spec") ) }'
A: In ramtam's answer which I like, the find portion works OK but the remainder does not if the path has spaces. I am not too familiar with sed, but I was able to modify that answer to:
find . -name "*_test.rb" | perl -pe 's/^((.*_)test.rb)$/"\1" "\2spec.rb"/' | xargs -n2 mv
I really needed a change like this because in my use case the final command looks more like
find . -name "olddir" | perl -pe 's/^((.*)olddir)$/"\1" "\2new directory"/' | xargs -n2 mv
A: I haven't the heart to do it all over again, but I wrote this in answer to Commandline Find Sed Exec. There the asker wanted to know how to move an entire tree, possibly excluding a directory or two, and rename all files and directories containing the string "OLD" to instead contain "NEW".
Besides describing the how with painstaking verbosity below, this method may also be unique in that it incorporates built-in debugging. It basically doesn't do anything at all as written except compile and save to a variable all commands it believes it should do in order to perform the work requested.
It also explicitly avoids loops as much as possible. Besides the sed recursive search for more than one match of the pattern there is no other recursion as far as I know.
And last, this is entirely null delimited - it doesn't trip on any character in any filename except the null. I don't think you should have that.
By the way, this is REALLY fast. Look:
% _mvnfind() { mv -n "${1}" "${2}" && cd "${2}"
> read -r SED <<SED
> :;s|${3}\(.*/[^/]*${5}\)|${4}\1|;t;:;s|\(${5}.*\)${3}|\1${4}|;t;s|^[0-9]*[\t]\(mv.*\)${5}|\1|p
> SED
> find . -name "*${3}*" -printf "%d\tmv %P ${5} %P\000" |
> sort -zg | sed -nz ${SED} | read -r ${6}
> echo <<EOF
> Prepared commands saved in variable: ${6}
> To view do: printf ${6} | tr "\000" "\n"
> To run do: sh <<EORUN
> $(printf ${6} | tr "\000" "\n")
> EORUN
> EOF
> }
% rm -rf "${UNNECESSARY:=/any/dirs/you/dont/want/moved}"
% time ( _mvnfind ${SRC=./test_tree} ${TGT=./mv_tree} \
> ${OLD=google} ${NEW=replacement_word} ${sed_sep=SsEeDd} \
> ${sh_io:=sh_io} ; printf %b\\000 "${sh_io}" | tr "\000" "\n" \
> | wc - ; echo ${sh_io} | tr "\000" "\n" | tail -n 2 )
<actual process time used:>
0.06s user 0.03s system 106% cpu 0.090 total
<output from wc:>
Lines Words Bytes
115 362 20691 -
<output from tail:>
mv .config/replacement_word-chrome-beta/Default/.../googlestars \
.config/replacement_word-chrome-beta/Default/.../replacement_wordstars
NOTE: The above function will likely require GNU versions of sed and find to properly handle the find printf and sed -z -e and :;recursive regex test;t calls. If these are not available to you the functionality can likely be duplicated with a few minor adjustments.
This should do everything you wanted from start to finish with very little fuss. I did fork with sed, but I was also practicing some sed recursive branching techniques so that's why I'm here. It's kind of like getting a discount haircut at a barber school, I guess. Here's the workflow:
*
*rm -rf ${UNNECESSARY}
*
*I intentionally left out any functional call that might delete or destroy data of any kind. You mention that ./app might be unwanted. Delete it or move it elsewhere beforehand, or, alternatively, you could build in a \( -path PATTERN -exec rm -rf \{\} \) routine to find to do it programmatically, but that one's all yours.
*_mvnfind "${@}"
*
*Declare its arguments and call the worker function. ${sh_io} is especially important in that it saves the return from the function. ${sed_sep} comes in a close second; this is an arbitrary string used to reference sed's recursion in the function. If ${sed_sep} is set to a value that could potentially be found in any of your path- or file-names acted upon... well, just don't let it be.
*mv -n $1 $2
*
*The whole tree is moved from the beginning. It will save a lot of headache; believe me. The rest of what you want to do - the renaming - is simply a matter of filesystem metadata. If you were, for instance, moving this from one drive to another, or across filesystem boundaries of any kind, you're better off doing so at once with one command. It's also safer. Note the -noclobber option set for mv; as written, this function will not put ${SRC_DIR} where a ${TGT_DIR} already exists.
*read -R SED <<HEREDOC
*
*I located all of sed's commands here to save on escaping hassles and read them into a variable to feed to sed below. Explanation below.
*find . -name ${OLD} -printf
*
*We begin the find process. With find we search only for anything that needs renaming because we already did all of the place-to-place mv operations with the function's first command. Rather than take any direct action with find, like an exec call, for instance, we instead use it to build out the command-line dynamically with -printf.
*%dir-depth :tab: 'mv '%path-to-${SRC}' '${sed_sep}'%path-again :null delimiter:'
*
*After find locates the files we need it directly builds and prints out (most) of the command we'll need to process your renaming. The %dir-depth tacked onto the beginning of each line will help to ensure we're not trying to rename a file or directory in the tree with a parent object that has yet to be renamed. find uses all sorts of optimization techniques to walk your filesystem tree and it is not a sure thing that it will return the data we need in a safe-for-operations order. This is why we next...
*sort -general-numerical -zero-delimited
*
*We sort all of find's output based on %directory-depth so that the paths nearest in relationship to ${SRC} are worked first. This avoids possible errors involving mving files into non-existent locations, and it minimizes need to for recursive looping. (in fact, you might be hard-pressed to find a loop at all)
*sed -ex :rcrs;srch|(save${sep}*til)${OLD}|\saved${SUBSTNEW}|;til ${OLD=0}
*
*I think this is the only loop in the whole script, and it only loops over the second %Path printed for each string in case it contains more than one ${OLD} value that might need replacing. All other solutions I imagined involved a second sed process, and while a short loop may not be desirable, certainly it beats spawning and forking an entire process.
*So basically what sed does here is search for ${sed_sep}, then, having found it, saves it and all characters it encounters until it finds ${OLD}, which it then replaces with ${NEW}. It then heads back to ${sed_sep} and looks again for ${OLD}, in case it occurs more than once in the string. If it is not found, it prints the modified string to stdout (which it then catches again next) and ends the loop.
*This avoids having to parse the entire string, and ensures that the first half of the mv command string, which needs to include ${OLD} of course, does include it, and the second half is altered as many times as is necessary to wipe the ${OLD} name from mv's destination path.
*sed -ex...-ex search|%dir_depth(save*)${sed_sep}|(only_saved)|out
*
*The two -exec calls here happen without a second fork. In the first, as we've seen, we modify the mv command as supplied by find's -printf function command as necessary to properly alter all references of ${OLD} to ${NEW}, but in order to do so we had to use some arbitrary reference points which should not be included in the final output. So once sed finishes all it needs to do, we instruct it to wipe out its reference points from the hold-buffer before passing it along.
AND NOW WE'RE BACK AROUND
read will receive a command that looks like this:
% mv /path2/$SRC/$OLD_DIR/$OLD_FILE /same/path_w/$NEW_DIR/$NEW_FILE \000
It will read it into ${msg} as ${sh_io} which can be examined at will outside of the function.
Cool.
-Mike
A: I was able handle filenames with spaces by following the examples suggested by onitake.
This doesn't break if the path contains spaces or the string test:
find . -name "*_test.rb" -print0 | while read -d $'\0' file
do
echo mv "$file" "$(echo $file | sed s/test/spec/)"
done
A: This is an example that should work in all cases.
Works recursiveley, Need just shell, and support files names with spaces.
find spec -name "*_test.rb" -print0 | while read -d $'\0' file; do mv "$file" "`echo $file | sed s/test/spec/`"; done
A: $ find spec -name "*_test.rb"
spec/dir2/a_test.rb
spec/dir1/a_test.rb
$ find spec -name "*_test.rb" | xargs -n 1 /usr/bin/perl -e '($new=$ARGV[0]) =~ s/test/spec/; system(qq(mv),qq(-v), $ARGV[0], $new);'
`spec/dir2/a_test.rb' -> `spec/dir2/a_spec.rb'
`spec/dir1/a_test.rb' -> `spec/dir1/a_spec.rb'
$ find spec -name "*_spec.rb"
spec/dir2/b_spec.rb
spec/dir2/a_spec.rb
spec/dir1/a_spec.rb
spec/dir1/c_spec.rb
A: Your question seems to be about sed, but to accomplish your goal of recursive rename, I'd suggest the following, shamelessly ripped from another answer I gave here:recursive rename in bash
#!/bin/bash
IFS=$'\n'
function RecurseDirs
{
for f in "$@"
do
newf=echo "${f}" | sed -e 's/^(.*_)test.rb$/\1spec.rb/g'
echo "${f}" "${newf}"
mv "${f}" "${newf}"
f="${newf}"
if [[ -d "${f}" ]]; then
cd "${f}"
RecurseDirs $(ls -1 ".")
fi
done
cd ..
}
RecurseDirs .
A: More secure way of doing rename with find utils and sed regular expression type:
mkdir ~/practice
cd ~/practice
touch classic.txt.txt
touch folk.txt.txt
Remove the ".txt.txt" extension as follows -
cd ~/practice
find . -name "*txt" -execdir sh -c 'mv "$0" `echo "$0" | sed -r 's/\.[[:alnum:]]+\.[[:alnum:]]+$//'`' {} \;
If you use the + in place of ; in order to work on batch mode, the above command will rename only the first matching file, but not the entire list of file matches by 'find'.
find . -name "*txt" -execdir sh -c 'mv "$0" `echo "$0" | sed -r 's/\.[[:alnum:]]+\.[[:alnum:]]+$//'`' {} +
A: Here's a nice oneliner that does the trick.
Sed can't handle this right, especially if multiple variables are passed by xargs with -n 2.
A bash substition would handle this easily like:
find ./spec -type f -name "*_test.rb" -print0 | xargs -0 -I {} sh -c 'export file={}; mv $file ${file/_test.rb/_spec.rb}'
Adding -type -f will limit the move operations to files only, -print 0 will handle empty spaces in paths.
A: I share this post as it is a bit related to question. Sorry for not providing more details. Hope it helps someone else.
http://www.peteryu.ca/tutorials/shellscripting/batch_rename
A: This is my working solution:
for FILE in {{FILE_PATTERN}}; do echo ${FILE} | mv ${FILE} $(sed 's/{{SOURCE_PATTERN}}/{{TARGET_PATTERN}}/g'); done
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4793892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "93"
} |
Q: Cortex-M0+ dual application/image linking For most products, we implement a bootloader+application approach which uses an external SPI flash for storing different application versions. Upon startup, the bootloader checks if a new image is stored in the SPI flash. If so, it flashes the application area of the µC and starts it.
The internal flash-layout typically looks like this:
+-----------------+
| 6k Bootloader |
+-----------------+
| 2k EEPROM |
+-----------------+
| 56K Application |
+-----------------+
However, for our next product, we want to eliminate the external flash and want to use a µC with an bigger internal flash to store two applications in it to dynamically switch between them.
+-----------------+
| 6k Bootloader |
+-----------------+
| 2k EEPROM |
+-----------------+
| 60K App A |
+-----------------+
| 60K App B |
+-----------------+
In our plans, App A is able to receive OTA updates and flash it to the memory region of App B. It then marks App B as the newer application and upon reboot, the bootloader jumps to App B instead of App A. Naturaly, App B can flash App A and mark it as the newer image.
So far so good, now the actual problem: While rolling out the OTA, we do not know if the OTA is flashed as App A or App B. Thus, when linking the application, we do not know which memory region in the internal flash is used. In other words, we do not know the offset which the application is started from and can not define jump addresses and position of isr-tables.
How do I link such an application that can be flashed in both regions? Is there a possibility to tell the compiler/linker to use "relative" jumps instead of "absolute" jumps? If not, are there any other solutions for such an approach? I.E. telling the M0+ to treat all addresses with an offset which is set up by the bootloader?
A: Basically I don't think this is possible with any widely available compiler.
You would have to use program-counter relative addressing for all data in flash, but absolute addressing for addresses in RAM. While the ELF for ARM specification has these kinds of relocations, I don't think any compiler knows how to do generate code to use them. Also, it wouldn't know which to use in each case given that what is in flash and what is in RAM isn't decided until the linker stage.
One solution (which I have used in production) is to compile all your sources once but link them twice with two different linker scripts with absolute addresses. You will then have to distribute a double-sized update image, only half of which is used on any occasion.
Alternatively if you only want to have one image, then you need to do a double-shuffle. Have your working image write the new image to one area of internal flash, then reboot and have the bootloader copy it from there to the working location. You couldn't run it from the temporary location because the embedded addresses would be wrong (this is identical to your current solution but only uses the internal flash).
A: You build the application as position independent, the startup code looks at the address it is executing from and adjusts the GOT before it launches into main() or whatever your C entry point is. Can certainly do this with gnu tools, I assume llvm supports position independent as well.
Now you can only boot from one place and that is common to both paths so you do know which path you are taking because you have to create a non-volatile scheme to mark which path to try first or which path is the most recent. There are various ways to do that, too broad to answer here. That code can do the GOT thing just like a normal program loader would for an operating system, or each application can patch itself up before calling compiled code, or can do a hybrid.
You can have the application run in sram instead of from flash and the single entry point code can copy whichever one is the current one to ram, and you do not need position independence you link for ram and either can be a copy and jump.
You can link two versions of each application and part of the update process is to in some way (many ways to do it, too broad for here) determine which partition and write the one linked for that partition, then the common entry point can simply branch to the right address.
Some mcus have banked flashes and a way to put one out front, you can buy one of those products.
The common code can live in each image just in case and the A code assumed to be at the entry point for the chip will be the real bootloader that determines which partition to use and make adjustments as needed.
Your chip might have an mmu and you can remap whichever into the same address space and link for that address space.
Not only is this doable this is not complicated, there are too many ways to do it to describe and you have to simply pick the one you want to implement and maintain. The chip may or may not help in this decision. If you are already a bare-metal programmer then dealing with startup code and PIC and the GOT, and stuff are simple not scary.
What does GOT mean. global offset table, a side effect of how at least gcc/binutils work. With position independent code.
Just use the tools, no target hardware necessary....
flash.s
.cpu cortex-m0
.thumb
.thumb_func
.word 0x20001000
.word reset
.thumb_func
reset:
bl notmain
.thumb_func
hang: b .
.thumb_func
.globl lbounce
lbounce:
bx lr
bounce.c
void fbounce ( unsigned int x )
{
}
notmain.c
void lbounce ( unsigned int );
void fbounce ( unsigned int );
unsigned int x = 9;
int notmain ( void )
{
x++;
lbounce(5);
fbounce(7);
return(0);
}
flash.ld
MEMORY
{
rom : ORIGIN = 0x00000000, LENGTH = 0x1000
mor : ORIGIN = 0x80000000, LENGTH = 0x1000
ram : ORIGIN = 0x20000000, LENGTH = 0x1000
}
SECTIONS
{
.ftext : { bounce.o } > mor
.text : { *(.text*) } > rom
.data : { *(.data*) } > ram
}
build it position dependent
arm-linux-gnueabi-as --warn --fatal-warnings -mcpu=cortex-m0 flash.s -o flash.o
arm-linux-gnueabi-gcc -Wall -O2 -ffreestanding -mcpu=cortex-m0 -mthumb -c notmain.c -o notmain.o
arm-linux-gnueabi-gcc -Wall -O2 -ffreestanding -mcpu=cortex-m0 -mthumb -c bounce.c -o bounce.o
arm-linux-gnueabi-ld -nostdlib -nostartfiles -T flash.ld flash.o notmain.o bounce.o -o notmain.elf
arm-linux-gnueabi-objdump -D notmain.elf > notmain.list
arm-linux-gnueabi-objcopy -O binary notmain.elf notmain.bin
arm-linux-gnueabi vs arm-none-eabi does not matter for this code, since the differences are not relevant here. This just happened to be what I had in this makefile.
arm-none-eabi-objdump -d notmain.o
notmain.o: file format elf32-littlearm
Disassembly of section .text:
00000000 <notmain>:
0: 4a06 ldr r2, [pc, #24] ; (1c <notmain+0x1c>)
2: b510 push {r4, lr}
4: 6813 ldr r3, [r2, #0]
6: 2005 movs r0, #5
8: 3301 adds r3, #1
a: 6013 str r3, [r2, #0]
c: f7ff fffe bl 0 <lbounce>
10: 2007 movs r0, #7
12: f7ff fffe bl 0 <fbounce>
16: 2000 movs r0, #0
18: bd10 pop {r4, pc}
1a: 46c0 nop ; (mov r8, r8)
1c: 00000000 .word 0x00000000
So the variable x is in .data the code is in .text, they are separate segments so you cannot make assumptions when compiling a module the pieces come together when linking. So this code is built so that the linker will fill in the value that is shown in this output as the 1c address. The address of x is read using that pc-relative load, then x itself is accessed using that address to do the x++;
lbounce and fbounce are not known to this code they are external functions so the best the compiler can really do is create a branch link to them.
Once linked:
00000010 <notmain>:
10: 4a06 ldr r2, [pc, #24] ; (2c <notmain+0x1c>)
12: b510 push {r4, lr}
14: 6813 ldr r3, [r2, #0]
16: 2005 movs r0, #5
18: 3301 adds r3, #1
1a: 6013 str r3, [r2, #0]
1c: f7ff fff7 bl e <lbounce>
20: 2007 movs r0, #7
22: f000 f805 bl 30 <__fbounce_veneer>
26: 2000 movs r0, #0
28: bd10 pop {r4, pc}
2a: 46c0 nop ; (mov r8, r8)
2c: 20000000 andcs r0, r0, r0
Per the linker script .data starts at 0x20000000 and we only have one item there so that is where x is. Now fbounce is too far away to encode in a single bl instruction so there is a trampoline or veneer created by the linker to connect them
00000030 <__fbounce_veneer>:
30: b401 push {r0}
32: 4802 ldr r0, [pc, #8] ; (3c <__fbounce_veneer+0xc>)
34: 4684 mov ip, r0
36: bc01 pop {r0}
38: 4760 bx ip
3a: bf00 nop
3c: 80000001 andhi r0, r0, r1
Note that is 0x80000000 with the lsbit set, the address is 0x80000000 not 0x80000001 look at the arm documentation (the lsbit means this is a thumb address and tells the bx instruction logic to go to or remain in thumb mode, then strip that bit off and make it a zero. Being a cortex-m it is always thumb mode if you have a zero there then the processor will fault because it does not have an arm mode, the tool generated that properly).
Now position independent.
arm-linux-gnueabi-as --warn --fatal-warnings -mcpu=cortex-m0 flash.s -o flash.o
arm-linux-gnueabi-gcc -fPIC -Wall -O2 -ffreestanding -mcpu=cortex-m0 -mthumb -c notmain.c -o notmain.o
arm-linux-gnueabi-gcc -fPIC -Wall -O2 -ffreestanding -mcpu=cortex-m0 -mthumb -c bounce.c -o bounce.o
arm-linux-gnueabi-ld -nostdlib -nostartfiles -T flash.ld flash.o notmain.o bounce.o -o notmain.elf
arm-linux-gnueabi-objdump -D notmain.elf > notmain.list
arm-linux-gnueabi-objcopy -O binary notmain.elf notmain.bin
on my machine gives
0000000e <lbounce>:
e: 4770 bx lr
00000010 <notmain>:
10: b510 push {r4, lr}
12: 4b07 ldr r3, [pc, #28] ; (30 <notmain+0x20>)
14: 4a07 ldr r2, [pc, #28] ; (34 <notmain+0x24>)
16: 447b add r3, pc
18: 589a ldr r2, [r3, r2]
1a: 2005 movs r0, #5
1c: 6813 ldr r3, [r2, #0]
1e: 3301 adds r3, #1
20: 6013 str r3, [r2, #0]
22: f7ff fff4 bl e <lbounce>
26: 2007 movs r0, #7
28: f000 f806 bl 38 <__fbounce_veneer>
2c: 2000 movs r0, #0
2e: bd10 pop {r4, pc}
30: 1fffffea svcne 0x00ffffea
34: 00000000 andeq r0, r0, r0
00000038 <__fbounce_veneer>:
38: b401 push {r0}
3a: 4802 ldr r0, [pc, #8] ; (44 <__fbounce_veneer+0xc>)
3c: 4684 mov ip, r0
3e: bc01 pop {r0}
40: 4760 bx ip
42: bf00 nop
44: 80000001 andhi r0, r0, r1
There may be some other interesting PIC flags, but so far this already shows a difference.
12: 4b07 ldr r3, [pc, #28] ; (30 <notmain+0x20>)
14: 4a07 ldr r2, [pc, #28] ; (34 <notmain+0x24>)
16: 447b add r3, pc
18: 589a ldr r2, [r3, r2]
1c: 6813 ldr r3, [r2, #0]
1e: 3301 adds r3, #1
20: 6013 str r3, [r2, #0]
Now it takes all of this to increment x. It is using a pc-relative offset in the literal pool at the end of the function to get from where we are to the GOT in .data. (important thing to note that means of you move .text around in memory you also need to move .data to be at the same relative offset for this to work). Then it has to do those math steps to get the address of x then it can do the read modify write.
Also note that the trampoline doesn't change still has the hard-coded address for the section that contains fbounce, so this tells us that we cannot move fbounce as built.
Disassembly of section .data:
20000000 <x>:
20000000: 00000009 andeq r0, r0, r9
Disassembly of section .got:
20000004 <.got>:
20000004: 20000000 andcs r0, r0, r0
So what is a GOT? It's a global offset table, in this trivial example there is this data item x in .data. There is a global offset table (okay correcting a statement above the .got section needs to be in the same place relative to .text for this to work as built, but .data can move and that is the whole point. .got for this to work needs to be in sram (and naturally that means a proper bootstrap needs to put it there just like .data needs to be placed from flash to sram before the C entry point).
So if you wanted to move the .data to some other address in memory because you are copying it from flash to a different address than it was linked for. You would need to go through the global offset table and modify those addresses. If you think about the position dependent, every function every instances of the global variable x, there will be that word in the literal pool after all the functions that access it, in places you cannot unravel. you would have to know the dozens to hundreds of places to modify if you wanted to move .data. With this solution you need to know where the GOT is and update it. So if instead of 0x20000000 you put it at 0x20008000 then you would go through the got and add 0x8000 to each entry before you launched this code or at least before the code touches any .data item.
And if you wanted to only move .text then at least as I have built this here, and not .data, then you need to move/copy the .text to the other address space and copy .got to the same relative address but not modify the got.
In your case you want to execute from two different address spaces but not move .data. So ideally need to get the tools to
have a fixed location for the .got which I did not dig into, exercise for the reader. If you can get the .got to be fixed and
independent of the location of .text then a single build of your program can be executed from two different flash locations without any modification. Without the need for two separately linked, binaries, etc.
.got : { *(.got*) } > rom
Done.
Disassembly of section .data:
20000000 <x>:
20000000: 00000009 andeq r0, r0, r9
Disassembly of section .got:
00000048 <.got>:
48: 20000000 andcs r0, r0, r0
that means the GOT is in the flash, which would end up being in the big binary blob that would get programmed in either flash location in the correct relative position.
So my fbounce was for demonstration.
If you build position independent and there is not enough flash to worry about the veneer, so a single binary can be created that will execute from two different flash locations without modification.
Thus the term position independent code. But this is the trivial part of your problem, the part that takes little effort (took me a few minutes to see and solve the one issue I had). You still have other issues to solve that can be solved dozens of ways and you have to decide, design, and implement your solution. Way too broad for Stack Overflow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70677559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get string length after it has changed but before its assigned Lets say I want to do something like this:
$string = 'arbitrary string' # << is random
$string = ($string + 'randomstring').Substring(0, [math]::Min(20, $string.lenght) # < doesn't work properly
How do I get current length of $string, when it is not yet assigned?
A: Just assign the string using +=.
$string = 'arbitrary string' # << is random
$string = ($string += 'randomstring').Substring(0, [math]::MIN(20, $string.Length)) #
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42435275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Parsing of multiple Arrays in android Please tell me how i can parse this model, i am a fresher in android. i tried like this way:-
{ "error": false, "response": { "comdata": [{ "id": "35", "address": "Address" }], "empdata": [{ "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" }, { "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" }] }
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jObj = new JSONObject(json);
if (jObj.getString("error").equalsIgnoreCase("false")) {
JSONObject object = jObj.getJSONObject("response");
for (int i = 0; i < object.length(); i++) {
JSONArray jsonArray = object.getJSONArray("parentdata");
JSONObject jsonObject = jsonArray.getJSONObject(0);
//Something write here
JSONArray jsonArray1 = object.getJSONArray("childata");
for (int a = 0; a < jsonArray1.length(); a++) {
JSONObject object1 = jsonArray1.getJSONObject(a);
} return "true";
}return "true";
}else{
}
A: Your JSON is invalid correct JSON will look like this.
{
"error": false,
"response": {
"comdata": [
{
"id": "35",
"address": "Address"
}
],
"empdata": [
{
"cid": "33",
"comid": "35",
"empname": "test",
"empdob": "0000-00-00"
},
{
"cid": "33",
"comid": "35",
"empname": "test",
"empdob": "0000-00-00"
}
]
}
}
You can parse the JSON using below code.
private void parseResponse(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.getBoolean("error")) {
JSONObject response = jsonObject.getJSONObject("response");
JSONArray jsonArray1 = response.getJSONArray("comdata");
List<ComData> comdataList = new ArrayList<>();
for (int i = 0; i < jsonArray1.length(); i++) {
ComData comData = new ComData();
comData.setId(jsonArray1.getJSONObject(i).getString("id"));
comData.setAddress(jsonArray1.getJSONObject(i).getString("address"));
comdataList.add(comData);
}
JSONArray jsonArray2 = response.getJSONArray("empdata");
List<EmpData> empdataList = new ArrayList<>();
for (int i = 0; i < jsonArray2.length(); i++) {
EmpData empData = new EmpData();
empData.setCid(jsonArray2.getJSONObject(i).getString("cid"));
empData.setComid(jsonArray2.getJSONObject(i).getString("comid"));
empData.setEmpname(jsonArray2.getJSONObject(i).getString("empname"));
empData.setEmpdob(jsonArray2.getJSONObject(i).getString("empdob"));
empdataList.add(empData);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Or you can easily parse JSON to POJO using GSON, refer César Ferreira's answer.
A: Your JSON is invalid you should have it something like this:
{
"error": false,
"response": {
"comdata": [{
"id": "10",
"username": null,
"email": "[email protected]"
}],
"empdata": [{
"eid": "33",
"empname": "test",
"empdob": "0000-00-00",
"empgender": "test",
"empphoto": ""
}],
"someData": [{
"eid": "34",
"empname": "test",
"empdob": "0000-00-00",
"empgender": "test",
"empphoto": ""
}]
}
}
The property someData I had to add it so it would be a valid JSON, I don't know if it fits your requirements.
You can use jsonschematopojo to generate a class like this:
Comdatum class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Comdatum {
@SerializedName("id")
@Expose
private String id;
@SerializedName("username")
@Expose
private Object username;
@SerializedName("email")
@Expose
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object getUsername() {
return username;
}
public void setUsername(Object username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Data class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
@SerializedName("error")
@Expose
private Boolean error;
@SerializedName("response")
@Expose
private Response response;
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
}
Empdatum Class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import package com.example;
public class Empdatum {
@SerializedName("eid")
@Expose
private String eid;
@SerializedName("empname")
@Expose
private String empname;
@SerializedName("empdob")
@Expose
private String empdob;
@SerializedName("empgender")
@Expose
private String empgender;
@SerializedName("empphoto")
@Expose
private String empphoto;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpdob() {
return empdob;
}
public void setEmpdob(String empdob) {
this.empdob = empdob;
}
public String getEmpgender() {
return empgender;
}
public void setEmpgender(String empgender) {
this.empgender = empgender;
}
public String getEmpphoto() {
return empphoto;
}
public void setEmpphoto(String empphoto) {
this.empphoto = empphoto;
}
}
Response Class
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
@SerializedName("comdata")
@Expose
private List<Comdatum> comdata = null;
@SerializedName("empdata")
@Expose
private List<Empdatum> empdata = null;
@SerializedName("someData")
@Expose
private List<SomeDatum> someData = null;
public List<Comdatum> getComdata() {
return comdata;
}
public void setComdata(List<Comdatum> comdata) {
this.comdata = comdata;
}
public List<Empdatum> getEmpdata() {
return empdata;
}
public void setEmpdata(List<Empdatum> empdata) {
this.empdata = empdata;
}
public List<SomeDatum> getSomeData() {
return someData;
}
public void setSomeData(List<SomeDatum> someData) {
this.someData = someData;
}
}
SomeDatum Class
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SomeDatum {
@SerializedName("eid")
@Expose
private String eid;
@SerializedName("empname")
@Expose
private String empname;
@SerializedName("empdob")
@Expose
private String empdob;
@SerializedName("empgender")
@Expose
private String empgender;
@SerializedName("empphoto")
@Expose
private String empphoto;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpdob() {
return empdob;
}
public void setEmpdob(String empdob) {
this.empdob = empdob;
}
public String getEmpgender() {
return empgender;
}
public void setEmpgender(String empgender) {
this.empgender = empgender;
}
public String getEmpphoto() {
return empphoto;
}
public void setEmpphoto(String empphoto) {
this.empphoto = empphoto;
}
}
And Then you can just do something like this:
String jsonString = "Your JSON String";
Gson converter = new Gson();
Data settingsdata = converter.fromJson(jsonString , Data.class);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52717669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Filttering json data in html-table I have to display json data in HTML-table and have succeeded in it. My problem is that I also need to filter this data by genders and studyfields using radiobuttons and dropdown list in the webpage. I have managed to do so but the filters clash with each other and mess the results in the table.
HTML:
<div>
<h4>Filter by Gender</h4>
<label>All</label>
<input class="filter-by-gender" checked="checked" type="radio" id="filterByGenderAll" value="all" name="filter_by_gender">
<label>Males</label>
<input class="filter-by-gender" type="radio" id="filterByGenderM" value="male" name="filter_by_gender">
<label>Females</label>
<input class="filter-by-gender" type="radio" id="filterByGenderF" value="female" name="filter_by_gender">
<br><br>
<h4>Filter by Studies</h4>
<select id="filterByStudiesAll" input class="filter-by-studies" name="filter-by-studies">
<option value="All" name="filter-by-studies">All</option>
<option value="Computer Science"name="filter-by-studies">Computer science</option>
<option value="Business"name="filter-by-studies">Business</option>
<option value="Art"name="filter-by-studies">Art</option>
</select>
</div>
<table id="students">
<thead>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Studyfield</th>
<th>Email</th>
<th>Phone</th>
<th>Address</th>
</thead>
<tbody class="tbody" id="personsTable">
</tbody>
</table>
Json is like this:
var students = [
{
"student_id": "123456",
"age": 20,
"firstname": "Horne",
"lastname": "Hess",
"gender": "male",
"study_field": "Computer Science",
"email": "[email protected]",
"phone": "+1 (877) 436-3132",
"address": "745 Livingston Street, Cassel, South Dakota, 103"}]
and lastly javascript:
function filterStudentsByGender(gender)
{
var filteredStudents = students
switch(gender)
{
case "male":
filteredStudents = students.filter(function(student){
return student.gender === "male"
})
break;
case "female":
filteredStudents = students.filter(function(student){
return student.gender === "female"
})
break;
}
var studentsHtml = filteredStudents.map(function(student){
return '<tr><td>'+student.firstname+" "+student.lastname+'</td><td>'+student.gender+'</td><td>'+student.age+'</td><td>'+student.study_field+"</td><td>"+student.email+"</td><td>"+student.phone+"</td><td>"+student.address+"</td></tr>";
})
$("#students").find('.tbody').html(studentsHtml)
}
function filterStudentsByStudy(study_field)
{
var filteredStudents=students
switch(study_field){
case "Computer Science":
filteredStudents=students.filter(function(student){
return student.study_field=="Computer Science"
})
break;
case "Art":
filteredStudents=students.filter(function(student){
return student.study_field=="Art"
})
break;
case "Business":
filteredStudents=students.filter(function(student){
return student.study_field=="Business"
})
break;
}
var studentsHtml = filteredStudents.map(function(student){
return '<tr><td>'+student.firstname+" "+student.lastname+'</td><td>'+student.gender+'</td><td>'+student.age+'</td><td>'+student.study_field+"</td><td>"+student.email+"</td><td>"+student.phone+"</td><td>"+student.address+"</td></tr>";
})
$("#students").find('.tbody').html(studentsHtml)
}
/* ########################## event listeners */
$(".filter-by-studies").on("change", function(e){
var checked = $(this).val();
filterStudentsByStudy(checked)
})
$(".filter-by-gender").on("change", function(e){
var checkedValue = $(this).val();
filterStudentsByGender(checkedValue)
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53337612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Programmatically Position Views in RelativeLayout I want my TextView to appear below my ImageView in a RelativeLayout that is going into a GridView. I've tried:
public override View GetView(int position, View convertView, ViewGroup parent)
{
RelativeLayout rl = new RelativeLayout(context);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent);
ImageView imageView;
TextView tv;
imageView = new ImageView(context);
imageView.LayoutParameters = new GridView.LayoutParams(250, 250);
imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
imageView.SetPadding(8, 8, 8, 8);
imageView.SetImageResource(thumbIds[position]);
imageView.Id = position;
lp.AddRule(LayoutRules.Below, position);
lp.AddRule(LayoutRules.CenterHorizontal);
tv = new TextView(context);
tv.Text = stringIds[position].ToString();
tv.SetTextSize(Android.Util.ComplexUnitType.Dip, 20);
tv.SetTextColor(Android.Graphics.Color.WhiteSmoke);
tv.LayoutParameters = lp;
rl.AddView(imageView);
rl.AddView(tv);
return rl;
}
But the TextView always shows up on top of the ImageView.
A: Check out this question.
When you call rl.AddView(tv), you should include the LayoutParams rl.AddView(tv, lp).
A: You have to use
imageView.setLayoutParams(lp) in order to assign the params to your view.
How do you setLayoutParams() for an ImageView?
A: Since my content is not dynamic, I worked around the issue by simply editing my image in Paint and placing text below the image. Then I made that the background for the ImageView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9200813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQLite returned: error code = 1 I have a pre-filled database in assets folder, which I move to internal storage on first run. It works fine on some devices, but on some I get the following error: sqlite returned: error code = 1, msg = no such table: FTSgesla, db=/data/data/com.example.enigmar/databases/gesla
The mentioned table definately exist, so I don't know where the problem is.
SQLiteOpenHelper code:
public static class DictionaryOpenHelper extends SQLiteOpenHelper
{
private final Context mHelperContext;
private SQLiteDatabase mDatabase;
//private static String DB_PATH="/data/data/com.example.enigmar/databases/";
private static String DB_PATH="";
private static final String DB_NAME = "gesla";
DictionaryOpenHelper(Context context)
{
super(context, DB_NAME, null, 1);
//
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
//
this.mHelperContext = context;
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
public void createDataBase() throws IOException
{
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
this.getReadableDatabase();
this.close();
new Thread(new Runnable()
{
public void run()
{
try
{
copyDataBase();
Log.e(TAG, "createDatabase database created");
BAZA_NAREJENA=true;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}).start();
}
}
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException
{
InputStream mInput = mHelperContext.getAssets().open(DB_NAME);
//final Resources resources = mHelperContext.getResources();
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
//InputStream mInput = resources.openRawResource(R.raw.gesla);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
public boolean openDataBase() throws SQLException
{
String mPath = DB_PATH + DB_NAME;
mDatabase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
return mDatabase != null;
}
@Override
public synchronized void close() {
if(mDatabase != null)
mDatabase.close();
super.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
What is wrong?
A: In your public void createDataBase() , you are using a Thread to copy your database in. Are you sure you have finished the copy before you try to access it? This is my working copy of the code which is very similar to yours you may want to see. Another thing is
byte[] mBuffer = new byte[1024];
try 4096 , I had problems with 1024 before.
A: Check that the table really exists in the database. Most likely, the actual database is empty, since you don't do anything in the onCreate function (where one should initialize the database). Instead, you probably one of the following:
Instead of passing SQLiteDatabase.CREATE_IF_NECESSARY to openDatabase, call your (currently unused) function createDataBase.
Alternatively, create the database in onCreate by copying over the data of the default database. For that, you'll need another function to convert your existing in-asset database to SQL commands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14800907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ArgumentException vs. ArgumentNullException? I’m refactoring some code and adding a method which will replace a (soon-to-be) deprecated method. The new method has the following signature:
FooResult Foo(FooArgs args) { ... }
The deprecated method contained a growing list of parameters. These parameters are now properties on the FooArgs class. The deprecated method has several guard conditions which checked for null values with the following structure:
if (parameter1 == null)
throw new ArgumentNullException(“parameter1”);
if (parameter... == null)
throw new ArgumentNullException(“parameter...”);
if (parameterN == null)
throw new ArgumentNullException(“parameterN”);
Now that the parameters have been collapsed into the FooArgs class should I throw an ArgumentNullException for the individual properties of the FooArgs parameter:
if (args.Property1 == null)
throw new ArgumentNullException(“args.Property1”);
if (args.Property... == null)
throw new ArgumentNullException(“args.Property...”);
if (args.PropertyN == null)
throw new ArgumentNullException(“args.PropertyN”);
Or to throw a more general ArgumentException for the entire FooArgs parameter:
if (args.Property1 == null)
throw new ArgumentException(“Property1 cannot be null.”, “args”);
if (args.Property... == null)
throw new ArgumentException(“Property... cannot be null.”, “args”);
if (args.PropertyN == null)
throw new ArgumentException(“Property2 cannot be null.”, “args”);
Thanks!
A: You need to add a check for the args itself to be non-null. The ANE is not appropriate for individual components, so you need to use more general AE, like this:
if (args == null)
throw new ArgumentNullException(“args”);
if (args.Property1 == null)
throw new ArgumentException(“Property1 cannot be null.”, “args”);
if (args.Property... == null)
throw new ArgumentException(“Property... cannot be null.”, “args”);
if (args.PropertyN == null)
throw new ArgumentException(“Property2 cannot be null.”, “args”);
A: In this case, it may be best to check for a null reference of the FooArgs parameter inside that method, and throw an ArgumentNullException if a null reference has been passed in. Then if other methods or sections of code use the parameters contained within the args class, they should be the ones to check this and throw exceptions as necessary. However, if your method that takes in the args class is the one to use all the arguments, then it would be better to check for valid parameters in that method, as you suggested.
Also, use ArgumentNullException only for arguments that are null references. If it's simply an invalid value (for example an empty string), then you should use the more generic ArgumentException.
A: This kind of depends on your tooling and how you feel about your tooling (resharper, fxcops and the like). Some static code analysis tools accept this:
throw new ArgumentNullException(“args.Property...”,"args");
and reject this
throw new ArgumentNullException(“args.Property...”,"args.Property");
So if you want to use the tooling, then assertions of null-hood against a parameter property must throw an ArgumentException
It's also valid to just make it up as you go along. What ever communicates the right message to the maintenance developer to help him pass the parameters correctly is the correct message.
A: While I agree completely with dasblinkenlight's answer, you may also want to consider moving the validation for FooArgs into the FooArgs class itself. If this class is designed specifically to move arguments around, it is likely not valid for it to have null proeprties, in which case, I would allow its constructor to do its validation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8459755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Make intersection of two methods in typescript I have intersection type GetSet and instances of Get and Set. How can I compose the GetSet instance? get & set gives two errors:
*
*TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type
*TS2345: Argument of type 'number' is not assignable to parameter of type 'GetSet'. Type 'number' is not assignable to type 'Get'
type Get = (<T>(a: RecoilValue<T>) => T)
type Set = (<T>(s: RecoilState<T>, u: (((currVal: T) => T) | T)) => void)
export type GetSet = Get & Set;
// some external functions
let get: Get;
let set: Set;
function callback(getSet: GetSet) {
}
function perform() {
callback(get & set); // <--- error here
}
A: calback(get & set) is plain wrong it will change to 0 in JavaScript (try (function () {}) & (function() {}) in chrome console), there is no & operator that will combine functions in JavaScript. type GetSet = Get & Set is a type definition in TypeScript which only means that the definition is a combination of both. However, there is no such thing in JavaScript.
If you want to pass two functions in JavaScript, you have to either use Tuple/Array or Object Literal.
callback([get, set]);
// or
callback({ get, set });
However, In this case, the callback definition should change as follow,
type Get = (<T>(a: RecoilValue<T>) => T)
type Set = (<T>(s: RecoilState<T>, u: (((currVal: T) => T) | T)) => void)
export type GetSet = { get: Get, set: Set };
// some external functions
let get: Get;
let set: Set;
function callback({ get, set }: GetSet) {
}
function perform() {
callback({ get , set }); // <--- this is correct way
}
You can combine get set as a single function as shown below...
function getOrSet(... a: any[]) {
if (a.length === 1) {
return get(a[0]);
}
return set(a[0], a[1]);
}
If you look at how jQuery was organized, you can call same method without parameter to get value and if you pass a parameter, it will set the value.
This might require rewriting many definitions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75432261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP MySQL SELECT from 2 tables not working I am trying to select records from two tables.
Please see the screenshots for the table structures:
Table listing
Table c_profile
I want to display the records of listing table and few from c_profile table..
SELECT c_profile.c_name,c_profile.logo, c_profile.email, listing.id, listing.title, listing.type,listing.job_desc,listing.c_id, listing.time, listing.vote_up from c_profile,listing where c_uid=c_id
The above statement works fine but only problem is it doesn't select "vote_up" results.
However, if I use a normal SELECT statement without WHERE, it seems to work.
How can I solve this problem?
A: I think what you want is a left join, because you want all the records of listing table and a few from c_profile table.
SELECT c_profile.c_name,
c_profile.logo,
c_profile.email,
listing.id,
listing.title,
listing.type,
listing.job_desc,
listing.c_id,
listing.time,
listing.vote_up
FROM listing
LEFT JOIN c_profile ON c_uid=c_id
this way you keep all records for listing and only join where you can find a matching c_profile
A: SELECT c_profile.c_name,c_profile.logo, c_profile.email, listing.id, listing.title, listing.type,listing.job_desc,listing.c_id, listing.time, listing.vote_up from listing left join c_profile ON c_profile.c_uid=listing .c_id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36574105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Copy HTML to UIPasteboard with React Native I have a simple react-native app that has some functionality to copy HTML to the global clipboard such that it preserves the styling. The expected result is I copy HTML and can paste it into another app with the styling intact. Note, I’m not looking to paste HTML source code, that is easy and can be done simply by copying as a string.
For iOS 13 I made a minor modification to the react-native clipboard native module to change it from copying plain text to copying HTML. This code worked as expected with iOS 13, but since updating to 14 it doesn't seem to work - no value seems to be present in the clipboard.
CustomClipboard.m
#import "CustomClipboard.h"
#import <UIKit/UIKit.h>
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>
#import <MobileCoreServices/MobileCoreServices.h>
@implementation CustomClipboard
RCT_EXPORT_MODULE();
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXPORT_METHOD(setString:(NSString *)content)
{
UIPasteboard *clipboard = [UIPasteboard generalPasteboard];
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
[clipboard setData:data forPasteboardType:(NSString *)kUTTypeHTML];
}
RCT_EXPORT_METHOD(getString:(RCTPromiseResolveBlock)resolve
reject:(__unused RCTPromiseRejectBlock)reject)
{
UIPasteboard *clipboard = [UIPasteboard generalPasteboard];
resolve((clipboard.string ? : @""));
}
@end
CustomClipboard.h
#import <React/RCTBridgeModule.h>
@interface CustomClipboard : NSObject <RCTBridgeModule>
@end
The native module is imported in JS through:
import { NativeModules } from 'react-native';
export default NativeModules.CustomClipboard;
And the exposed to the rest of the app via a Clipboard module:
import NativeClipboard from './NativeClipboard';
/**
* `Clipboard` gives you an interface for setting and getting content from Clipboard on both iOS and Android
*/
export const Clipboard = {
/**
* Get content of string type, this method returns a `Promise`, so you can use following code to get clipboard content
* ```javascript
* async _getContent() {
* var content = await Clipboard.getString();
* }
* ```
*/
getString(): Promise<string> {
return NativeClipboard.getString();
},
/**
* Set content of string type. You can use following code to set clipboard content
* ```javascript
* _setContent() {
* Clipboard.setString('hello world');
* }
* ```
* @param the content to be stored in the clipboard.
*/
setString(content: string) {
NativeClipboard.setString(content);
},
};
The code all seems to run correctly, but no value is copied to the clipboard. I haven't been able to find any known bugs on this. Any ideas?
A: EDIT
This is the second attempt. Earlier I understood you wanted to copy and paste the HTML as text but after your comments and edits to the question I now understand that you have some text that you format using HTML and you want to paste that text while retaining the formatting.
More or less as shown below.
This also illustrates how to wire it up in storyboard. Here is the code.
#import "ViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <WebKit/WebKit.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel * statusLabel;
@property (weak, nonatomic) IBOutlet WKWebView * webView;
@property (weak, nonatomic) IBOutlet UITextView * textView;
@end
@implementation ViewController
#pragma mark -
#pragma mark Actions
- (IBAction)reloadButtonAction:(id)sender {
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.webfx.com/blog/images/assets/cdn.sixrevisions.com/0435-01_html5_download_attribute_demo/samp/htmldoc.html"]]];
}
- (IBAction)copyButtonAction:(id)sender {
if ( self.webView.loading ) {
self.statusLabel.text = @"Loading";
} else {
self.statusLabel.text = @"Copying ...";
[self.webView evaluateJavaScript:@"document.documentElement.outerHTML.toString()"
completionHandler: ^ ( id content, NSError * error ) {
if ( error ) {
self.statusLabel.text = @"Error";
} else if ( [content isKindOfClass:NSString.class] ) {
[UIPasteboard.generalPasteboard setData:[( NSString * ) content dataUsingEncoding:NSUTF8StringEncoding]
forPasteboardType:( NSString * ) kUTTypeHTML];
self.statusLabel.text = @"Copied HTML";
} else {
self.statusLabel.text = @"Unknown type";
}
}];
}
}
- (IBAction)pasteButtonAction:(id)sender {
if ( [UIPasteboard.generalPasteboard containsPasteboardTypes:@[( NSString * ) kUTTypeHTML]] ) {
// Convert to attributed string
NSError * cvtErr;
NSData * data = [UIPasteboard.generalPasteboard dataForPasteboardType:( NSString * ) kUTTypeHTML];
NSAttributedString * attr = [[NSAttributedString alloc] initWithData:data
options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType }
documentAttributes:NULL
error: & cvtErr];
if ( cvtErr ) {
self.statusLabel.text = @"Convert error";
} else if ( attr ) {
self.statusLabel.text = @"Attributed";
self.textView.attributedText = attr;
} else {
self.statusLabel.text = @"Unable to decode";
}
} else {
NSString * content = UIPasteboard.generalPasteboard.string;
if ( content ) {
// Paste plain text
self.textView.text = content;
self.statusLabel.text = @"Pasted";
} else {
self.statusLabel.text = @"No string content";
}
}
}
@end
The code is very similar to before. The problem is that HTML = plain text so to copy HTML and retain the style or formatting also depends on the destination app into which you paste it. That destination app needs to handle the HTML correctly for what you want to achieve.
Anyhow, here are the changes from earlier.
On the copy side: the text is now copied as HTML and not as a string. There is very little difference there except that now, unlike before, the string is converted to data and the type is marked as kUTTypeHTML.
On the paste side: the real difference is here. If the pasteboard contains HTML then it is retrieved and formatted using an attributed string. It also works fine if you e.g. paste into Notes BTW.
This illustrates the problem you are dealing with here. I could just as well have used the code I used earlier and everything would work but in stead of formatted HTML I would get the unformatted / source HTML.
Here I assume that you are interested in fairly simple but formatted text. You did not mention text specifically and if you e.g. wanted to copy an HTML formatted table then my example is not adequate as I use a UITextView as destination.
For more complex HTML I'd use a WKWebView as destination as well and set its HTML string to the pasted in HTML, but again, this shows how the destination app also needs to cooperate in handling the HTML correctly.
Finally, looking at the updated answer and your code it is difficult to spot a difference, so I suspect your problem could be earlier with content itself in
RCT_EXPORT_METHOD(setString:(NSString *)content)
UPDATE
I also looked at the git repository you mention. There I found the following
RCT_EXPORT_METHOD(hasString:(RCTPromiseResolveBlock)resolve
reject:(__unused RCTPromiseRejectBlock)reject)
{
BOOL stringPresent = YES;
UIPasteboard *clipboard = [UIPasteboard generalPasteboard];
if (@available(iOS 10, *)) {
stringPresent = clipboard.hasStrings;
} else {
NSString* stringInPasteboard = clipboard.string;
stringPresent = [stringInPasteboard length] == 0;
}
resolve([NSNumber numberWithBool: stringPresent]);
}
It looks wrong, I think that one line should be
stringPresent = [stringInPasteboard length] != 0;
HTH
A: I found the answer here: http://www.andrewhoyer.com/converting-html-to-nsattributedstring-copy-to-clipboard/
The string needed to be converted to RTF before it was put in the clipboard.
RCT_EXPORT_METHOD(setString:(NSString *)content)
{
// Source: http://www.andrewhoyer.com/converting-html-to-nsattributedstring-copy-to-clipboard/
UIPasteboard *clipboard = [UIPasteboard generalPasteboard];
// Sets up the attributes for creating Rich Text.
NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
NSRTFTextDocumentType, NSDocumentTypeDocumentAttribute,
NSCharacterEncodingDocumentAttribute, [NSNumber numberWithInt:NSUTF8StringEncoding],
nil];
// Create the attributed string using options to indicate HTML text and UTF8 string as the source.
NSAttributedString *atr = [[NSAttributedString alloc]
initWithData: [content dataUsingEncoding:NSUTF8StringEncoding]
options: @{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
}
documentAttributes:nil error:nil];
// Generate the Rich Text data using the attributed string and the previously created attributes.
NSData *rtf = [atr dataFromRange:NSMakeRange(0, [atr length]) documentAttributes:documentAttributes error:nil];
// Set the Rich Text to the clipboard using an RTF Type
// Note that this requires <MobileCoreServices/MobileCoreServices.h> to be imported
[clipboard setData:rtf forPasteboardType:(NSString*)kUTTypeRTF];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65308176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need to commit open transaction? Is it need to commit opened hibernate transaction.What will happen if someone didn't?
Is it caused to some issues?
thanks
A: Commit will make the database commit. The changes to persistent object will be written to database. If you don't commit you will loose the changes you made in the database.
A: A transaction MUST ends, either by a commit or by a rollback.
Why ?
A transaction is consuming resources:
*
*some bytes in memory
*usually a JBDC connection. (or any kind of connection to a transnational external resource)
So, if a tx never ends : it will use a JDBC connection forever and there a good chances that you run out of database connections.
Conclusion : you don't need to commit every tx, but you need to terminate them : either by a commit or a rollback (there is no other end state for a tx)
A: Well it is not only with hibernate transaction but with all database transactions. Commit/ Rollback are Atomicity of ACID (Atomicity, Consistency, Isolation, Durability) properties which actually represent/specifies TRANSACTION. Atomicity is more like do or die.
Answer to your question:
//creates something like cache/temporary space for you to perform all your operations. Note this changes will not be reflected in your database at this point.
Session.beginTransaction();
//perform some db operations
//this line flushes/post your changes from temporary stuff to database. If your changes contains error then this will not be affected/made changes to the database else the changes will be affected.
Session.commit();
Hope this is helpful!
A: A transaction must be closed. So by committing the transaction would automatically be closed as long as current context property mentioned in hibernate.cfg.xml is is thread and not managed.
This is to maintain the ACID properties of transaction. Also a when a transaction is begin it is allocated a lot of memory and resources.
What the best practices suggest is you should roll back the entire transaction and close the session if there's exception in catch block and you should commit the transaction in the last part of try block rather than finally block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20759676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Correcting country names to make them match a different naming convention I want to make a world map with ggplot as follows:
library(ggplot2)
library(countrycodes)
library(dplyr)
library(tidyverse)
worldmap_AMIS_Market <- map_data("world")
# Set colors
vec_AMIS_Market <- c("Canada", "China","United States of America", "Republic of Korea", "Russian Federation")
worldmap_AMIS_Market <- mutate(worldmap, fill = ifelse(region %in% vec_AMIS_Market, "green", "lightgrey"))
# Use scale_fiil_identity to set correct colors
ggplot(worldmap_AMIS_Market, aes(long, lat, fill = fill, group=group)) +
geom_polygon(colour="gray") + ggtitle("Map of World") +
ggtitle("Availability of AMIS Supply and Demand Data - Monthly") +
scale_fill_identity()
As you can see the US does not light up in green, because in the worldmap_AMIS_Market data, the US is written as USA, while the vector uses United States of America. The same goes for Russia and South Korea. As I am going to go through this process for around 50 different datasets, I would prefer to not manually correct all countries that do no match.
Is there any way to solve issues like this? I have a couple of ideas, but not an actual solution:
*
*I could do fuzzy matching, but that won't work for USA -> United States.
*I know the package countrycodes can convert countries to iso codes etc, but I don't think it has the option to correct country names (https://github.com/vincentarelbundock/countrycode).
*I could somehow collect all alternative naming conventions for all countries, and then do a fuzzy match on that. But I don't know where to get the alternative names from, and I am not sure I would be able to write the fuzzy code for this scenario anymore.
Could someone perhaps help me fix this?
A: One option would be countrycode::countryname to convert the country names.
Note: countrycode::countryname throws a warning so it will probably not work in all cases. But at least to me the cases where it fails are rather exotic and small countries or islands.
library(ggplot2)
library(countrycode)
library(dplyr)
library(tidyverse)
worldmap <- map_data("world")
# Set colors
vec_AMIS_Market <- c("Canada", "China","United States of America", "Republic of Korea", "Russian Federation")
worldmap_AMIS_Market <- mutate(worldmap, region = countryname(region), fill = ifelse(region %in% countryname(vec_AMIS_Market), "green", "lightgrey"))
#> Warning in countrycode_convert(sourcevar = sourcevar, origin = origin, destination = dest, : Some values were not matched unambiguously: Ascension Island, Azores, Barbuda, Canary Islands, Chagos Archipelago, Grenadines, Heard Island, Madeira Islands, Micronesia, Saba, Saint Martin, Siachen Glacier, Sint Eustatius, Virgin Islands
# Use scale_fiil_identity to set correct colors
ggplot(worldmap_AMIS_Market, aes(long, lat, fill = fill, group=group)) +
geom_polygon(colour="gray") + ggtitle("Map of World") +
ggtitle("Availability of AMIS Supply and Demand Data - Monthly") +
scale_fill_identity()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70127083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sticker App : UnsatisfiedLinkError after releasing app AsyncTask I am getting error as I got following crash from Play Console.
Its sticker application and I just updated, before that I have updated many times but didn't get any error.
In this updates I just changed assets folder by adding one folder with 25 images.
java.lang.RuntimeException:
at android.os.AsyncTask$3.done (AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:383)
at java.util.concurrent.FutureTask.setException (FutureTask.java:252)
at java.util.concurrent.FutureTask.run (FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:636)
at java.lang.Thread.run (Thread.java:764)
Caused by: java.lang.UnsatisfiedLinkError:
at com.facebook.soloader.SoLoader.b (Unknown Source:254)
at com.facebook.soloader.SoLoader.a (Unknown Source:106)
at com.facebook.soloader.SoLoader.a (Unknown Source:94)
at com.facebook.soloader.SoLoader.a (Unknown Source:1)
at com.facebook.imagepipeline.nativecode.d.a (Unknown Source:20)
at com.facebook.animated.webp.WebPImage.a (Unknown Source)
at com.wastickers.stickers.j.a (Unknown Source:17)
at com.wastickers.stickers.j.a (Unknown Source:19)
at com.wastickers.stickers.j.a (Unknown Source:467)
at com.wastickers.stickers.i.a (Unknown Source:109)
at com.wastickers.stickers.EntryActivity$a.a (Unknown Source:11)
at com.wastickers.stickers.EntryActivity$a.doInBackground (Unknown Source:2)
at android.os.AsyncTask$2.call (AsyncTask.java:333)
at java.util.concurrent.FutureTask.run (FutureTask.java:266)
I am following this repository to make this app.
build.gradle: you can also check here
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.facebook.fresco:fresco:1.12.0'
implementation 'com.facebook.fresco:webpsupport:1.12.0'
implementation 'com.facebook.fresco:animated-webp:1.12.0'
}
Can anyone help me out, please?
A: Here I got the solution:
As per this comment the problem with fresco, where app bundle is not well supported.
The problem was that app bundle builds multiple dexes, but Fresco was
only looking at one to find the so file. There were no problems with
using apk to send to play store.
From that link I found to update following libraries.
implementation 'com.facebook.fresco:fresco:1.12.0'
implementation 'com.facebook.fresco:webpsupport:1.12.0'
implementation 'com.facebook.fresco:animated-webp:1.12.0'
Update:
implementation 'com.facebook.fresco:fresco:1.12.1'
implementation 'com.facebook.fresco:webpsupport:1.12.1'
implementation 'com.facebook.fresco:animated-webp:1.12.1'
For Me, Following version worked.
Reference Link:
https://github.com/WhatsApp/stickers/issues/410
https://github.com/WhatsApp/stickers/issues/413
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54905094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I use pure SQL in ASP.net MVC? hello guys i need to use pure SQL queries for my database project
at the same time i wanna use ASP.net MVC so i can learn a new technology !!!
can i use SQL with ASP.net MVC WITHOUT using " LINQ to SQL " ?!
i'm still learning so i'm sorry if it so stupid using things the OLD SCHOOL
but my instructor insists that he want to see a PURE SQL Queries
A: Yes. You can use whatever you want for your model layer. Note, you can use raw SQL queries with LINQ To SQL as well.
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
IEnumerable<Customer> results = db.ExecuteQuery<Customer>
(@"SELECT c1.custid as CustomerID, c2.custName as ContactName
FROM customer1 as c1, customer2 as c2
WHERE c1.custid = c2.custid"
);
Or perhaps your instructor wants straight up ADO.NET, which works fine too.
There is an example here.
A: You can use raw SQL queries in ASP.Net MVC the same way you use them anywhere else.
It can be helpful to use idioms like
using (var reader = command.ExecuteReader())
return View(reader.Select(dr => new { Name = dr["Name"], ... }));
EDIT: It appears that you're asking how to use ADO.Net in general.
Try this tutorial.
A: Of course you can use SQL in ASP.NET MVC. I'd consider keeping the SQL code on stored procedures rather than hard-coding the SQL directly in the application code. It's better to maintain and it's a good practice that will probably be looked upon by your instructor.
A: SQL has nothing to do with ASP.NET MVC. ASP.NET MVC is a web framework for building web sites and applications. My suggestion is that you try to abstract as much as possible, the MVC application shouldn't know if you're using SQL (stored procedures), Entity Framework, Linq-to-sql or if you get your data from a web-service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4594233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to extract information from the command line? I would like to analyze the options passed via the command line using C++ and QT, without using external libraries. In particular, assuming that the possible lines of command are the following ones, what is the easiest way to analyze and extract the required information (path, string, int_1, int_2, int_3)?
--intrinsic <path> <int_1> <int_2> <int_3>
--extrincic <path> -solve -3D <string> -2D <string>
--extrincic <path> -verify -3D <string>
A: Maybe the new class QCommandLineParser can help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23361944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The web server hangs while calling 3rd party Web API from my Web API I need to call a 3 party Web Api from my ASP.net Web API, when it runs the line
HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);
the web server hangs. I have tried to put below code in to a console program, it runs well. What is wrong with below code when run in ASP.net Web API project?
client.BaseAddress = new Uri(webAPIAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string token = Crypto.EncryptStringAES("abcd1234");
client.DefaultRequestHeaders.Add("X-Token", token);
HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);
if (response.IsSuccessStatusCode)
{
...
}
A: You probably have a Task<T>.Result or Task.Wait call further up your call stack. This will cause a deadlock on ASP.NET that I describe in more detail on my blog.
In summary, await will capture a "context" - in this case, an ASP.NET request context, which only allows one running thread at a time. When its awaitable completes (that is, when the POST finishes), the async method will continue in that context. If your code is blocking further up the call stack (e.g., Result or Wait), then it will block a thread in that ASP.NET request context, and the async method cannot enter that context to continue executing.
You don't see the deadlock in the Console app because there's no context being captured, so the async method resumes on a thread pool thread instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31237989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Create maven dependency instead of .jar Is there a way where I can take an existing java project (it's an automation framework) and actually export it out in a way that another project can consume it using the maven GAV instead of having to add it as an external jar?
I was able to create a jar of the framework project and then tested adding the jar to a 2nd project and all that works fine. I really would just prefer to be able to reference the framework project as a maven dependency in the pom instead of having to add the jar. I also think this will be easier when it comes to making updates to the framework and having the consuming projects just update the version of the maven dependency in the pom.
Of course I could be way off with my thinking here. I'm primarily in the c# world where I can just export my project out as a nuget package that gets consumed easily so that's what I'm used to.
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54961881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CURL to C# HttpWebRequest I need help with converting PHP's CURL to C# HttpWebRequest. My c# code doesn't work well, the request loads all the time ending with timeout exception. Here is my PHP code:
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, 'https://api.example.com/');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Origin: http://media.example.com/',
'Accept-Encoding: gzip,deflate,sdch',
'Host: api.example.com',
'Accept-Language: en-US,en;q=0.8',
'Authorization: FD 08306ECE-C36C-4939-B65F-4225F37BD296:905664F40E29B95CF5810B2ACA85497C7430BB1498E74B52',
'Content-Type: application/json',
'Accept: */*',
'Referer: http://example.com',
'User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36',
'Connection: keep-alive'
)
);
curl_setopt($curl, CURLOPT_POSTFIELDS, '{"language":"en","original_text":"' . $text . '","product":"pen"}' . chr(10));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
And here is my c# code:
var request = WebRequest.Create("https://api.example.com/social/autocomplete/v2/search/messages") as HttpWebRequest; ;
request.ContentType = "application/json";
request.Method = "POST";
request.Headers["Origin"] = "http://media.example.com";
request.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
//request.Headers["Host"] = "api.example.com"
request.Host = "api.example.com";
request.Headers["Accept-Language"] = "en-US,en;q=0.8";
request.Headers["Authorization"] = "FD 08306ECE-C36C-4939-B65F-4225F37BD296:905664F40E29B95CF5810B2ACA85497C7430BB1498E74B52";
request.ContentType = "application/json";
request.Accept = "*/*";
request.Referer = "http://example.com/";
request.UserAgent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
request.KeepAlive = true;
byte[] buffer = Encoding.UTF8.GetBytes("{\"language\":\"en\",\"original_text\":\"hello\",\"product\":\"pen\"}");
string result = System.Convert.ToBase64String(buffer);
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(response.ToString());
Console.ReadKey();
I hope someone can help me. Thanks in advance.
A: You need to read the response stream from the web server.
Use the response.GetResponseStream() function.
If the response contains Unicode text, you can read that text using a StreamReader.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20315684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: My website is accessible to some users but throws "this site can't be reached" for others I recently set up a website http://shehara.co and it works fine on my pc and phone and some of my friends, when working properly it should display "nothing to see here" on the top left corner, But for most users, it does not load.
I tried pinging it through my command prompt and that fails too(all packets lost), then I tried the site downforeveryoneorjustme.com which again tells the site is down, I'm confused to as what is happening, I'm using a free host service called byet.host, can someone explain how to fix this
A: Now site is working but showing nothing is here I think at that time server has got to many requests that's why it cannot be reached .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61097385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Images and Icons for Apps (Android - iOS) I am creating my first App for the iOS and Android platforms and want to start with some good icons and images. I do not want to spent a lot of money on them. I also do not have experience with softwares like photoshop to create my own images and icons.
I am trying to find some websites that can provide me with sports related UI resources.
What are some popular/good sites that I can utilize for my project.
A: I recommend two sites: IconArchive and Icon8.
They both have free icon sets that can help you to get you started with your designs!
Cheers
A: Depends on what kind of resources your looking for, if it's mainly icons I suggest: http://iconfinder.com
If your looking for photo resources I would try http://gettyimage.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23810110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: raspberry pi camera motion detection I'm programming a motion detection system using Raspberry Pi, the official Raspberry Pi Camera and OpenCV with Python. While I'm using the absdiff and bitwise_and operation it comes up with this:
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor,
file /home/pi/opencv-2.4.10/modules/imgproc/src/color.cpp, line 3739
Traceback (most recent call last): File "icanseeu-diff.py", line 18,
in
t_minus = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) cv2.error:
/home/pi/opencv-2.4.10/modules/imgproc/src/color.cpp:3739: error:
(-215) scn == 3 || scn == 4 in function cvtColor
Here is the code:
import cv2
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
camera = PiCamera()
camera.resolution = (320, 240)
camera.framerate = 30
camera.rotation = 180
rawCapture = PiRGBArray(camera, size = (320, 240))
def diffImg(t0, t1, t2):
d1 = cv2.absdiff(t2, t1)
d2 = cv2.absdiff(t1, t0)
return cv2.bitwise_and(d1, d2)
# Read three images first
frame1 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)
frame2 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)
frame3 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)
while True:
cv2.imshow( motions, diffImg(t_minus, t, t_plus) )
# Read next image
frame1 = frame2
frame2 = frame3
frame3 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)
key = cv2.waitKey(10)
if key == 27:
cv2.destroyWindow(motions)
break
Seems like an assignation problem, but I don't know how to deal with it. What should I do? Thanks!
A: The error message that you are getting is informing you that image that you are passing does not have 3 or 4 channels. This is the assestion that has failed.
This is because camera.capture function does not return any values (API Documentation). Instead the rawCapture gets updated, it is this that you should be passing to cvtColor.
Instead of
frame1 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)
Use
rawCapture.truncate()
camera.capture(rawCapture, format = "bgr", use_video_port = True)
frame1 = cv2.cvtColor(rawCapture.array, cv2.COLOR_BGR2GRAY)
And the same for each time you capture an image.
I haven't been able to test this as I don't currently have my Raspberry Pi and Camera on me but it should fix the problem.
A: I think you didn't close your camera, so python thinks that the camera is used by another program. Try to restart your Pi. The program should work after the restart. The second start of the program after the restart won't work. If this happens, close the camera in the last if-statement.
A: To save your time, I have built a completed application to detect motion and notify to the iOS/Android. The notification will have text, image, and video.
Check this out
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30416045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Selenium Webdriver error: An item with the same key has already been added Can someone advice me how to prevent this error: "An item with the same key has already been added."?
I have two tests that runs fine when run individually, but when I "run all" in visual studio, I get that error.
[Binding]
public sealed class Steps
{
private Squish squish = new Squish();
private Tools tools = new Tools();
[Given(@"I navigated to the Squish homepage")]
public void GivenINavigatedToTheSquishHomepage()
{
squish.NavigateToURL("Squish.com");
ScenarioContext.Current["siteTitle"] = squish.GetPageTitle();
}
Is there any alternatives to FeatureContext.Current.Add(key, value)? So I don't have to be directly be storing anything?
A: I guess you should read specflow documentation about parallel test runs http://specflow.org/documentation/Parallel-Execution/
It's said:
You may not be using the static context properties
ScenarioContext.Current, FeatureContext.Current or
ScenarioStepContext.Current.
Actually your error is self-descriptive - you've created item in dictionary with key "siteTitle"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47341135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to read this data into a .json file format? private ArrayList<Double> celciusList = new ArrayList<Double>();
private ArrayList<Double> farenList = new ArrayList<Double>();
private ArrayList<Double> LDRlist = new ArrayList<Double>();
private ArrayList<Double> inchList = new ArrayList<Double>();
private ArrayList<Double> cmList = new ArrayList<Double>();
How do i possibly use this data information as my headings to print out in a .json file format?
A: I would use some kind of Java JSON Serializer, there a few of them out there.
*
*GSON
*FlexJson
Here is a simple example with FlexJson on how you could convert an object to JSON String.
final JSONSerializer serializer = new JSONSerializer();
final String output = serializer.transform(new ProtocolCalculatorTransformer(),ProtocolCalculation.class).exclude("*.class").deepSerialize(this);
return output;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23224412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: how do i make my website background a gradient colour? I am currently trying to create a website.
I have created the logo for the website but I'm not sure how to make my header and footer background a gradient color on Dreamweaver CS6.
I can only put it as a solid color and I am not sure if I need to use CSS or HTML to change it.
Does anyone know if it is possible, and if it is how to do it?
thanks :)
A: There is a online tool from which you can generate css gradient -
http://www.colorzilla.com/gradient-editor/
On left side of screen you have options to choose colors and on right you have code which you need to copy in your css.
A: Try www.css3generator.com and then select gradient and select color and equivalent code will be generated ..copy the code and use in your CSS.
This site is very helpful.
A: Use CSS3:
body {
background-image: -webkit-linear-gradient(top left, white 0%, #9FBFD2 100%);
background-image: -moz-linear-gradient(top left, white 0%, #9FBFD2 100%);
background-image: -o-linear-gradient(top left, white 0%, #9FBFD2 100%);
background-image: linear-gradient(top left, white 0%, #9FBFD2 100%);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32798595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamically serving users from one of the multiple servers behind a single domain? When someone registers to my SaaS app they are assigned to a region (US/EU/Pacific), and it is saved into the DB. In this example I have 3 servers, 1 for each region.
When a user logs in (it could be a single central server/subdomain for the whole world), I want to get their region from DB, and serve them from that server directly (so I do not just want to make a load balancer, I actually want the traffic to go directly to the assigned server).
Handling it using Round Robin on the DNS level is not a viable solution, because the servers in different regions will have different database content, and possibly different software versions, so random distribution is unwanted.
Obviously I could make different subdomains like us.app.com and eu.app.com, but what I would like to do is to solve this problem with a minimum number of subdomains.
Is there an elegant way to do this?
A: You need either a geo IP capable or latency based DNS service (e.g. AWS Route 53) to make shure visitors from a distinct region connect to the right server. See http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html if it's an option for you to use Route53.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42101671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How to keep ui-router parameters on browser refresh I'm using a ui-sref which takes two strings and an object as parameters. All works fine under normal circumstances, however when I refresh the browser on the page which I have navigated to the object becomes null.
The two strings in the URL are fine after a refresh. Is there a way to get the object to persist in the $stateparams after a page refresh. I have tried several options such as $rootscope.$stateparams = $stateparams, I've tried using a service too but it gets wiped on a refresh. Using local storage is not an option.
.state('edit', {
url: '/editItem/:id?userId',
templateUrl: 'app/items/edit.html',
controller: 'editController',
controllerAs: 'vm',
params: {
id: "",
userId: "",
userObject: null,
}
})
I really just need the object to persist on reload. I'm using UI-router 1.0.0-beta.2
A: If you want to use your url params in your state everytime, you can use the resolve function:
.state('edit', {
url: '/editItem/:id/:userId',
templateUrl: 'app/items/edit.html',
controller: 'editController',
controllerAs: 'vm',
resolve: {
testObject: function($stateParams) {
return {
id: $stateParams.id,
userId: $stateParams.userId
}
}
}
})
Now, you can pass testObject as a dependency to your editController and every time this route is resolved, the values will be available within your controller as testObject.id and testObject.userId
If you want to pass an object from one state to the next, use $state.go programatically:
$state.go('myState', {myParam: {some: 'thing'}})
$stateProvider.state('myState', {
url: '/myState',
params: {myParam: null}, ...
The only other option is to cache, trough Localstorage or cookies
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39456146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Min Fibonacci Heap - How to implement increase-key operation? I have been trying to implementing heap data structures for use in my research work. As part of that, I am trying to implement increase-key operations for min-heaps. I know that min-heaps generally support decrease-key. I was able to write the increase-key operation for a binary min-heap, wherein, I exchange increased key with the least child recursively.
In the case of the Fibonacci heap, In this reference, they say that the Fibonacci heap also supports an increase-key operation. But, I couldn't find anything about it in the original paper on Fibonacci Heaps, nor could I find anything in CLRS (Introduction to Algorithms by Cormen).
Can someone tell me how I can go about implementing the increase-key operation efficiently and also without disturbing the data structure's amortized bounds for all the other operations?
A: First, note that increase-key must be (log) if we wish for insert and find-min to stay (1) as they are in a Fibonacci heap.
If it weren't you'd be able to sort in () time by doing inserts, followed by repeatedly using find-min to get the minimum and then increase-key on the head by with ∀:> to push the head to the end.
Now, knowing that increase-key must be (log), we can provide a straightforward asymptotically optimal implementation for it. To increase a node to value , first you decrease-key(,−∞), then delete-min() followed by insert(,).
Refer here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57432502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Invalid hook call inside arrow functional component although the code runs I'm learning react and am trying to get a simple pop-up to show whenever the Show Toast button is clicked using Toast. However, I'm receiving this error:
Error in /turbo_modules/[email protected]/cjs/react-dom.development.js (12408:27)
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
I'm assuming it's something simple although I'm not used to hooks. The error states that hooks can only be called inside the body of a functional component, so:
*
*Where is technically the body of a functional component? I assume where I've put this comment: //body of functional component here
*Why is this error also appearing in the JS console: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method
*How can I get the pop-up to show? The console.log('click') shows in the console so I assume it's the succeeding toast code that's incorrect
Here is a stackblitz demo
And here is the code:
import React from "react";
import { useForm } from "react-hook-form";
import { useToast } from "@chakra-ui/core";
const App = () => {
const { register, handleSubmit, watch, errors } = useForm();
//const toast = useToast();
const onSubmit = data => {
console.log('data', data);
};
// body of functional component here?
const toastTest = () =>
{
const toast = useToast();
return (
<button
onClick={() =>
{
console.log('click');
toast({
title: "Account created.",
description: "We've created your account for you.",
status: "success",
duration: 9000,
isClosable: true,
})
}
}
>
Show Toast
</button>
)
};
console.log(watch("example"));
return (
<>
{toastTest()}
<form onSubmit={handleSubmit(onSubmit)}>
<input name="example" defaultValue="test" ref={register} />
<input name="exampleRequired" ref={register({ required: true })} />
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
</>
);
}
export default App
I've seen similar other posts from other users but cannot get this to work. Any beginner advice to hooks would be appreciated, thank you.
A: Technically you are violating the Rules of Hooks. You should move out useToast from the function's body called toastTest into the root of your function component.
See my suggested solution below:
const App = () => {
const toast = useToast(); // useToast moved here from the function
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = data => {
console.log('data', data);
}
const toastTest = () =>
// please notice useToast is removed from here
// ... rest of the function's body
}
return <> { /* your return */ }</>
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64411953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Calculating 3D pixel variance from 4D array Let there be some 4D array [x,y,z,k] comprised of k 3D images [x,y,z].
Is there any way to calculate the variance of each individual pixel in 3D from the 4D array?
E.g. I have a 10x10x10x5 array and would like to return a 10x10x10 variance array; the variance is calculated for each pixel (or voxel, really) along k
If this doesn't make sense, let me know and I'll try explaining better.
Currently, my code is:
tensors = []
while error > threshold:
for _ in range(5): #arbitrary
new_tensor = foo(bar) #always returns array of same size
tensors.append(new_tensor)
tensors = np.stack(tensors, axis = 3)
#tensors.shape
And I would like the calculate a variance array for tensors
A: There is a simple way to do that if you're using numpy:
variance = tensors.var(axis=3)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51638870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dictionary comprehension inside insert() method not working I am making a MappingList class which is a list implemented as an OrderedDict.
This is the MappingList class (some methods omitted):
class MappingList(MutableSequence):
"""
A MappingList is a regular list implemented as a dictionary
"""
def __repr__(self):
return str(list(self.seq.values()))
def __getitem__(self, item):
try:
return self.seq[item]
except KeyError:
_traceback_from_none(IndexError, "list index out of range")
def __setitem__(self, key, value, *, usage=None):
if key > max(self.seq.keys()) and usage != "append":
raise IndexError("list index out of range")
self.seq[key] = value
def __delitem__(self, key):
try:
del self.seq[key]
except KeyError:
_traceback_from_none(IndexError, "list index out of range")
def __len__(self):
return len(self.seq)
def __eq__(self, other):
if not isinstance(other, MappingList):
return NotImplemented
return self.seq == other.seq
@classmethod
def _dict_from_seq(cls, seq):
return OrderedDict(enumerate(seq))
def _next_available_slot(self):
return max(self.seq) + 1
def insert(self, index, value): # todo: insert() should not overwrite
"""Insert a value into the MappingList"""
if index > max(self.seq.keys()):
raise IndexError("list index out of range")
for k, v in {k: v for k, v in self.seq.items() if k > index}:
del self.seq[k]
self.seq[k + 1] = v
self[index] = value
When I try to insert an item into a MappingList, I get the following error:
File "C:\...\My Python Programs\free_time\mappinglist.py", line 103, in test_insert
self.li.insert(1, MappingList(["blah", 1, 5.8]))
File "C:\...\My Python Programs\free_time\mappinglist.py", line 85, in insert
for k, v in {k: v for k, v in self.seq.items() if k > index}:
TypeError: cannot unpack non-iterable int object
Why is this error happening? Does OrderedDict.items() return an integer?
A: The error doesn't happen due to that.
When you don't provide keys(), values(), items(), python iterates over the keys by default. You need to provide items() to tell python to get the keys and values.
for k, v in {k: v for k, v in self.seq.items() if k > index}.items():
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68834085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Downloading files from an sftp site - how? I have the username and password.
Using Firefox, the URL ftp://[email protected] pops a dialogue asking fo the password. The the response is '503 User not logged in'
Using IE, the URL ftp.xxx.com pops a dialogue asking for username and password; the response is the same as with Firefox.
How do I connect to the site?
If not using a browser, can I connect from the command line?
Thank you for your help.
A: SFTP has nothing to do with FTP, except inasmuch as both are for transferring files. Firefox out of the box doesn't speak SFTP, last i heard.
In order to download something via SFTP, you'll need an SFTP client, like WinSCP. or PSFTP (part of PuTTY). Both are free. Or, apparently, there's a FF addon called FireFTP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8405781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What naming convention for a method/function that both sets and gets a value? This may come across as a strange question, since the convention is usually to have separate set and get methods. But in my case, it is a bit different: an argument to a function decides whether that function is a getter or a setter, so I am looking for a function name that will indicate such function.
Some names I have found were getset, setget, rw, and etc but i find these names rather strange. What kind of naming convention would fit for such functions?
A: Until Java beans came along with the get/set naming convention, one quite often saw functions (particularly methods in C++ and other OO languages) that did exactly as you describe.
They were often named after the variable that they set or got, e.g.:
int counter_;
int counter () {
return counter_;
}
int counter (int c) {
counter_ = c;
return counter_;
}
In languages with different namespaces for variables and functions, you could even have the variable and the get/set functions have exactly the same name (without the need for a trailing _ as I've shown here).
In languages with default parameters, you could potentially write the getter and setter as one function, e.g. something like this:
int counter (int c = MAX_INT) {
if (c != MAX_INT) {
counter_ = c;
}
return counter_;
}
... though I wasn't particularly keen on that approach because it led to subtle bugs if someone called counter (MAX_INT), for instance.
I always thought that this naming approach made some sense and I've written some libraries that worked that way.
This naming convention did, however, potentially confuse the reader of the code, particularly in languages where one could call a parameterless function without the trailing parentheses, so it was hard to see if a function was being called or if a public variable was being accessed directly. Of course some would call the latter a feature rather than a problem ...
A: How about just name the function after the name of the variable it populates? Like a property, when the parameter passed is null or other special value, then it is get, otherwise it is set.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15737692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is shallow copy sufficient for structures with char[]? I have a structure containing character arrays with no any other member functions. I am doing assignment operation between two instances of these structures. If I'm not mistaken, it is doing shallow copy. Is shallow copy safe in this case?
I've tried this in C++ and it worked but I would just like to confirm if this behavior is safe.
A: Assigning structs does a member-wise assignment, and for arrays this means assigning each item. (And this is done recursively for "multiple dimension" arrays, which are really just arrays of arrays.)
You are correct that it does a shallow copy, even on arrays. (I'm assuming that you have not overloaded op= with respect to C++; if you overload it you can do anything you want.)
Remember that a shallow copy means copying the value of something, while a deep copy means copying the value to which something points or refers. The value of an array is each item in it.
The difference between shallow and deep is most meaningful when you have a type that does indirection, such as a pointer. I find my answer the most helpful way to look at this issue, but you could also say "shallow" vs "deep" doesn't even apply to other types, and they are just "copied".
struct S {
int n;
int* p;
int a[2];
int* ap[2];
int xy[2][2];
};
void f() {
S c, d;
c = d;
// equivalent to:
c.n = d.n;
c.p = d.p;
c.a[0] = d.a[0]; // S::a is similar to your situation, only using
c.a[1] = d.a[1]; // int instead of char.
c.ap[0] = d.ap[0];
c.ap[1] = d.ap[1];
c.xy[0][0] = d.xy[0][0];
c.xy[0][1] = d.xy[0][1];
c.xy[1][0] = d.xy[1][0];
c.xy[1][1] = d.xy[1][1];
}
That I used int above doesn't change anything of the semantics, it works identically for char arrays, copying each char. This is the S::a situation in my code.
Note that p and ap are copied shallowly (as is every other member). If those pointers "own" the memory to which they point, then it might not be safe. ("Safe" in your question is vague, and really depends on what you expect and how you handle things.)
For an interesting twist, consider boost::shared_ptr and other smart pointers in C++. They can be copied shallowly, even though a deep copy is possible, and this can still be safe.
A: If by "shallow copy", you mean that after assignment of a struct containing an array, the array would point to the original struct's data, then: it can't. Each element of the array has to be copied over to the new struct. "Shallow copy" comes into the picture if your struct has pointers. If it doesn't, you can't do a shallow copy.
When you assign a struct containing an array to some value, it cannot do a shallow copy, since that would mean assigning to an array, which is illegal. So the only copy you get is a deep copy.
Consider:
#include <stdio.h>
struct data {
char message[6];
};
int main(void)
{
struct data d1 = { "Hello" };
struct data d2 = d1; /* struct assignment, (almost) equivalent to
memcpy(&d2, &d1, sizeof d2) */
/* Note that it's illegal to say d2.message = d1.message */
d2.message[0] = 'h';
printf("%s\n", d1.message);
printf("%s\n", d2.message);
return 0;
}
The above will print:
Hello
hello
If, on the other hand, your struct had a pointer, struct assignment will only copy pointers, which is "shallow copy":
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data {
char *message;
};
int main(void)
{
struct data d1, d2;
char *str = malloc(6);
if (str == NULL) {
return 1;
}
strcpy(str, "Hello");
d1.message = str;
d2 = d1;
d2.message[0] = 'h';
printf("%s\n", d1.message);
printf("%s\n", d2.message);
free(str);
return 0;
}
The above will print:
hello
hello
In general, given struct T d1, d2;, d2 = d1; is equivalent to memcpy(&d2, &d1, sizeof d2);, but if the struct has padding, that may or may not be copied.
Edit: In C, you can't assign to arrays. Given:
int data[10] = { 0 };
int data_copy[10];
data_copy = data;
is illegal. So, as I said above, if you have an array in a struct, assigning to the struct has to copy the data element-wise in the array. You don't get shallow copy in this case: it doesn't make any sense to apply the term "shallow copy" to a case like this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2241699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: python. how to export to csv file after gather data on web I did some web scraping with selenium and was able to generate to print a table with the data I need to export (see image below). How can now export it to csv (place a .csv in a specific folder with todays date).
Thanks a lot for your inputs.
from selenium import webdriver
from selenium.webdriver.support.ui import Select
path_to_chromedriver = 'C:\python34\chromedriver\chromedriver.exe' # change path as needed
browser = webdriver.Chrome(executable_path = path_to_chromedriver)
url = 'http://test.com'
browser.get(url)
browser.find_element_by_xpath("//select[@name='query_choice']/option[text()='60 days']").click() # working to select DLP
browser.find_element_by_css_selector('input[type=\"submit\"]').click() # working to press submit
for tag in browser.find_elements_by_xpath('//*[@id="page1"]/table'):
print (tag.text)
A: Assuming your table is a list
with open('saveTo\Directory\file.csv','w') as f:
f.write(','.join(tableData))
Where you can technically, call the f.write method on each line of the table as soon as you have it, but change the 'w' parameter to 'a' to append to the file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35429746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Nested ListView in wicket throwing IndexOutOfBoundsException I have a nested ListView in wicket which for some reason is throwing an IndexOutOfBoundsException. Here is the relevant markup:
<table>
<tr wicket:id="dataRow">
<td wicket:id="dataCell"><span wicket:id="dataContent"></span></td>
</tr>
<table>
and the relevant code:
ListView<User> dataRow = new ListView<User>("dataRow", new AbstractReadOnlyModel<List<User>>() {
private static final long serialVersionUID = 1L;
@Override
public List<User> getObject() {
...
return getUsers(itemOffset, c, filter, sc, isDescending );
// returns a List<User> of row objects
}
}) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(ListItem<User> item) {
// list of <TD>s
ListView<String> dataCell = new ListView<String>("dataCell",new AbstractReadOnlyModel<List<String>>() {
private static final long serialVersionUID = 1L;
@Override
public List<String> getObject() {
return getColumnValues(item.getModelObject());
// gets a list of strings to display from the User object
}
}) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(ListItem<String> stringItem) {
Label dataContent = new Label("dataContent", stringItem.getModel());
dataContent.setRenderBodyOnly(true);
stringItem.add(dataContent);
}
};
dataCell.setReuseItems(true);
item.add(dataCell);
}
};
dataRow.setReuseItems(true);
add(dataRow);
No Ajax refresh or anything has been done (yet), but I get an exception at the first rendering already:
Unexpected RuntimeException
Last cause: Index: 10, Size: 10
WicketMessage: Exception in rendering component: [Component id = dataContent]
Stacktrace
Root cause:
java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at org.apache.wicket.markup.html.list.ListItemModel.getObject(ListItemModel.java:59)
at org.apache.wicket.Component.getDefaultModelObject(Component.java:1605)
at org.apache.wicket.markup.html.list.ListItem.getModelObject(ListItem.java:92)
at myadmin.web.panels.TableViewPanel$3$1.getObject(TableViewPanel.java:156)
at myadmin.web.panels.TableViewPanel$3$1.getObject(TableViewPanel.java:1)
at org.apache.wicket.Component.getDefaultModelObject(Component.java:1605)
at org.apache.wicket.markup.html.list.ListView.getModelObject(ListView.java:643)
at org.apache.wicket.markup.html.list.ListItemModel.getObject(ListItemModel.java:59)
at org.apache.wicket.Component.getDefaultModelObject(Component.java:1605)
at org.apache.wicket.Component.getDefaultModelObjectAsString(Component.java:1633)
at org.apache.wicket.markup.html.basic.Label.onComponentTagBody(Label.java:131)
at org.apache.wicket.markup.html.panel.DefaultMarkupSourcingStrategy.onComponentTagBody(DefaultMarkupSourcingStrategy.java:71)
at org.apache.wicket.Component.internalRenderComponent(Component.java:2529)
at org.apache.wicket.markup.html.WebComponent.onRender(WebComponent.java:56)
at org.apache.wicket.Component.internalRender(Component.java:2359)
at org.apache.wicket.Component.render(Component.java:2287)
at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1392)
at org.apache.wicket.MarkupContainer.renderAll(MarkupContainer.java:1557)
at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1532)
at org.apache.wicket.MarkupContainer.onComponentTagBody(MarkupContainer.java:1487)
at org.apache.wicket.markup.html.panel.DefaultMarkupSourcingStrategy.onComponentTagBody(DefaultMarkupSourcingStrategy.java:71)
at org.apache.wicket.Component.internalRenderComponent(Component.java:2529)
at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1496)
at org.apache.wicket.Component.internalRender(Component.java:2359)
at org.apache.wicket.Component.render(Component.java:2287)
at org.apache.wicket.markup.html.list.ListView.renderItem(ListView.java:584)
at org.apache.wicket.markup.html.list.ListView.renderChild(ListView.java:573)
at org.apache.wicket.markup.repeater.AbstractRepeater.onRender(AbstractRepeater.java:101)
at org.apache.wicket.Component.internalRender(Component.java:2359)
at org.apache.wicket.Component.render(Component.java:2287)
at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1392)
at org.apache.wicket.MarkupContainer.renderAll(MarkupContainer.java:1557)
at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1532)
at org.apache.wicket.MarkupContainer.onComponentTagBody(MarkupContainer.java:1487)
at org.apache.wicket.markup.html.panel.DefaultMarkupSourcingStrategy.onComponentTagBody(DefaultMarkupSourcingStrategy.java:71)
at org.apache.wicket.Component.internalRenderComponent(Component.java:2529)
at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1496)
at org.apache.wicket.Component.internalRender(Component.java:2359)
...
I don't see what I'm doing wrong. Any help would be greatly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39205636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: -Replace Operator not accepting capture group variable and user variable at once In the below example if I use single quotes for the -Replace operator ('Tag000: (.*)', 'Tag000: $1 hello $scategory') the capture group variable ($1) gets resolved at run time, while $scategory does not.
If I use double quotes (-replace "Tag000: (.*)", "Tag000: $1 hello $scategory") the $scategory variable works but then the capture group varibale is not recognised
$scategory = "my car is red "
$Read_Opus_Category= Get-Content -Path "C:\Temp\Chapter 6.ps1" -Stream multitags.txt -Raw
$Modified_Opus_Category= $Read_Opus_Category -replace 'Tag000: (.*)', "Tag000: $1 hello $scategory"
Am at a loss here, any help would be wonderfull
A: Use ` to escape the $ in an expandable string literal:
$Read_Opus_Category -replace 'Tag000: (.*)', "Tag000: `$1 hello $scategory"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73387890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hadoop, MapReduce Custom Java Counters Exception in thread "main" java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING Error is:
Exception in thread "main" java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING
at org.apache.hadoop.mapreduce.Job.ensureState(Job.java:294)
at org.apache.hadoop.mapreduce.Job.getCounters(Job.java:762)
at com.aamend.hadoop.MapReduce.CountryIncomeConf.main(CountryIncomeConf.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
The error shows that the problem lies in the line:
Counter counter =
job.getCounters().findCounter(COUNTERS.MISSING_FIELDS_RECORD_COUNT);
Also I do have a enum with the name COUNTERS.
Mapper :
import java.io.IOException;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.log4j.Logger;
public class CountryIncomeMapper extends Mapper<Object, Text, Text, DoubleWritable> {
private Logger logger = Logger.getLogger("FilterMapper");
private final int incomeIndex = 54;
private final int countryIndex = 0;
private final int lenIndex = 58;
String seperator = ",";
public void map(Object key, Text line, Context context) throws IOException,
InterruptedException {
if (line == null) {
logger.info("null found.");
context.getCounter(COUNTERS.ERROR_COUNT).increment(1);
return;
}
if (line.toString().contains(
"Adjusted net national income per capita (current US$)")) {
String[] recordSplits = line.toString().split(seperator);
logger.info("The data has been splitted.");
if (recordSplits.length == lenIndex) {
String countryName = recordSplits[countryIndex];
try {
double income = Double.parseDouble(recordSplits[incomeIndex]);
context.write(new Text(countryName), new DoubleWritable(income));
} catch (NumberFormatException nfe) {
logger.info("The value of income is in wrong format." + countryName);
context.getCounter(COUNTERS.MISSING_FIELDS_RECORD_COUNT).increment(1);
return;
}
}
}
}
}
Driver Class :
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class CountryIncomeConf {
public static void main(String[] args) throws IOException,
InterruptedException, ClassNotFoundException {
Path inputPath = new Path(args[0]);
Path outputDir = new Path(args[1]);
// Create configuration
Configuration conf = new Configuration(true);
// Create job
Job job = new Job(conf, "CountryIncomeConf");
job.setJarByClass(CountryIncomeConf.class);
Counter counter =
job.getCounters().findCounter(COUNTERS.MISSING_FIELDS_RECORD_COUNT);
System.out.println("Error Counter = " + counter.getValue());
// Setup MapReduce
job.setMapperClass(CountryIncomeMapper.class);
job.setNumReduceTasks(1);
// Specify key / value
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(DoubleWritable.class);
// Input
FileInputFormat.addInputPath(job, inputPath);
job.setInputFormatClass(TextInputFormat.class);
// Output
FileOutputFormat.setOutputPath(job, outputDir);
job.setOutputFormatClass(TextOutputFormat.class);
// Delete output if exists
FileSystem hdfs = FileSystem.get(conf);
if (hdfs.exists(outputDir))
hdfs.delete(outputDir, true);
// Execute job
int code = job.waitForCompletion(true) ? 0 : 1;
System.exit(code);
}
}
A: Looks like you're trying to get the counter before you submitted the job.
A: I had the same error at the time of an sqoop export.
The error was generated because the hdfs directory was empty.
Once I populated the directory (corresponding to a hive table), the sqoop ran without problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31480400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MS Access SQL Query to Concatenate or Consolidate Related Fields If I had the following MS Access table and sample data,
Status tbl
UpdateID PK
CustomerNo text
StatusType text
UpdateDate date
UpdateID, CustomerNo, StatusType, UpdateDate
001, 0099, Open, 2011-01-01
002, 0099, Pend, 2011-01-02
003, 0100, Open, 2011-01-03
004, 0099, Appr, 2011-01-04
005, 0100, Pend, 2011-01-05
006, 0099, Clsd, 2011-01-07
then how could I write a query that would result in the following consolidated/concatenated output?
CustomerNo, UpdateDate
0099, 2011-01-01;2011-01-02;2011-01-04;2011-01-07
0100, 2011-01-03;2011-01-05
A: There is no convenient way to do this in Access without using code to iterate over the returned rows and build the string yourself.
Here is some code that will help you do this:
Public Function ListOf(sSQL As String, Optional sSeparator As String = ", ") As String
Dim sResults As String
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset(sSQL)
While Not rs.EOF
If sResults = "" Then
sResults = Nz(rs.Fields(0).Value, "???")
Else
sResults = sResults + sSeparator & Nz(rs.Fields(0).Value, "???")
End If
rs.MoveNext
Wend
ListOf = sResults
End Function
And here is how you can use it in an Access query:
SELECT [CustomerNo],
(ListOf('SELECT [UpdateDate] FROM StatusTbl WHERE CustomerNo = ' + CStr([CustomerNo]))) AS UpdateDates
FROM StatusTbl
Note that this only works if you're executing the query in Access, queries executed from (for instance) an ADO connection will not have access to the ListOf function.
A: This comes up fairly often, here is a previous take: Combine rows / concatenate rows
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4785713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ruby on rails new project gemfile error I recently installed and created a new project, I followed rails tutorial (http://guides.rubyonrails.org/getting_started.html) and everything was ok.
Now, when I tried to create a new project and start the server I get this:
=> Booting WEBrick
=> Rails 4.0.0 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2013-09-09 15:28:55] INFO WEBrick 1.3.1
[2013-09-09 15:28:55] INFO ruby 2.0.0 (2013-06-27) [x64-mingw32]
[2013-09-09 15:28:55] INFO WEBrick::HTTPServer#start: pid=12064 port=3000
Started GET "/" for 127.0.0.1 at 2013-09-09 15:28:56 +0100
Gem::LoadError (Specified 'sqlite3' for database adapter, but the gem is not loa
ded. Add `gem 'sqlite3'` to your Gemfile.):
activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:58:in `rescue in resolve_hash_connection'
activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:55:in `resolve_hash_connection'
activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:46:in `resolve_string_connection'
activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:30:in `spec'
activerecord (4.0.0) lib/active_record/connection_handling.rb:39:in `establish
_connection'
activerecord (4.0.0) lib/active_record/railtie.rb:175:in `block (2 levels) in
<class:Railtie>'
activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:38:in `instance_ev
al'
activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:38:in `execute_hoo
k'
activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:45:in `block in ru
n_load_hooks'
activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:44:in `each'
activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:44:in `run_load_ho
oks'
activerecord (4.0.0) lib/active_record/base.rb:322:in `<module:ActiveRecord>'
activerecord (4.0.0) lib/active_record/base.rb:22:in `<top (required)>'
activerecord (4.0.0) lib/active_record/query_cache.rb:50:in `restore_query_cac
he_settings'
activerecord (4.0.0) lib/active_record/query_cache.rb:43:in `rescue in call'
activerecord (4.0.0) lib/active_record/query_cache.rb:32:in `call'
activerecord (4.0.0) lib/active_record/connection_adapters/abstract/connection
_pool.rb:626:in `call'
activerecord (4.0.0) lib/active_record/migration.rb:369:in `call'
actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in
call'
activesupport (4.0.0) lib/active_support/callbacks.rb:373:in `_run__342058401_
_call__callbacks'
activesupport (4.0.0) lib/active_support/callbacks.rb:80:in `run_callbacks'
actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.0.0) lib/action_dispatch/middleware/reloader.rb:64:in `call'
actionpack (4.0.0) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
actionpack (4.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `c
all'
actionpack (4.0.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `ca
ll'
railties (4.0.0) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.0.0) lib/rails/rack/logger.rb:21:in `block in call'
activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `block in tag
ged'
activesupport (4.0.0) lib/active_support/tagged_logging.rb:25:in `tagged'
activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `tagged'
railties (4.0.0) lib/rails/rack/logger.rb:21:in `call'
actionpack (4.0.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
rack (1.5.2) lib/rack/runtime.rb:17:in `call'
activesupport (4.0.0) lib/active_support/cache/strategy/local_cache.rb:83:in `
call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
actionpack (4.0.0) lib/action_dispatch/middleware/static.rb:64:in `call'
railties (4.0.0) lib/rails/engine.rb:511:in `call'
railties (4.0.0) lib/rails/application.rb:97:in `call'
rack (1.5.2) lib/rack/lock.rb:17:in `call'
rack (1.5.2) lib/rack/content_length.rb:14:in `call'
rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
C:/Ruby200-x64/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
C:/Ruby200-x64/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
C:/Ruby200-x64/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'
Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/_source.erb (2.0ms)
Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/_trace.erb (2.0ms)
Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/_request_and_response.erb (2.0ms)
Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (122.
1ms)
When I open a browser window I get
Gem::LoadError
Specified 'sqlite3' for database adapter, but the gem is not loaded. Add gem 'sqlite3' to your Gemfile.
What can I do to fix this?
A: According to the error, you need to add sqlite3 gem to your Gemfile (it's just a plain text file that should be on your Redmine root folder). Edit it and add something like.-
gem 'sqlite3'
You may also find this thread useful.-
Ruby on Rails - "Add 'gem sqlite3'' to your Gemfile"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18700953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the GET function on AWS S3 Are Get functions read-only? like if a GetObject, GetBucketPolicy or GetBucketLogging event is executed on an s3 then does that mean the user only read the information
Thanks!
A: Yes that is a standard practice. While building any REST API; ( just like when we create beans and implement getter and setter methods ) get api are for "select" while set api are for update/delete.. Similarly you have PutObject also to update an object onto S3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64702991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Minimum code coverage threshold in Jacoco Gradle on the whole project level(not on the module level) Our project is using Gradle 3.5, jacoco 0.8.1
It has 3 modules -- module-A, module-B and module-C, and its code coverage is 50%, 6% and 42% separately, and the code coverage for the whole project is 38%.
Now we want to use the current code coverage for the whole project as the threshold, that means if the code coverage of the whole project is less than 38%, the build will fail.
I tried the solution in
Minimum code coverage threshold in Jacoco Gradle
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.38
}
}
}
but failed, it hints that module-B violates the rules, instruction covered ratio is 0.06, but expect is 0.38, seems it only suits for the module level, not the whole project level.
Also I tried to use element = 'GROUP', but seems no effect.
(https://www.eclemma.org/jacoco/trunk/doc/api/org/jacoco/core/analysis/ICoverageNode.ElementType.html)
Anyone knows how to set the minimum code coverage threshold for the whole project and not for the module level?
thanks,
A: I suggest having a separate project (module) within your multi-module build for reporting on the whole project. You might need the JacocoMerge task too. Let's assume a, b and c are java projects. Eg
Eg:
def javaProjects = [':a', ':b', ':c']
javaProjects.each {
project(it) {
apply plugin: 'java'
apply plugin: 'jacoco'
}
}
project(':report') {
FileCollection execData = files(javaProjects.collect { project(it).tasks.withType(Test).jacoco.destinationFile })
FileCollection sourceDirs = files(javaProjects.collect { project(it).sourceSets.main.java.srcDirs })
FileCollection classDirs = files(javaProjects.collect { project(it).sourceSets.main.java.output.classesDirs })
def testTasks = javaProjects.collect { project(it).tasks.withType(Test)}
task jacocoMerge(type: JacocoMerge) {
dependsOn testTasks
executionData execData
jacocoClasspath = classDirs
}
task coverageVerification(type: JacocoCoverageVerification) {
dependsOn jacocoMerge
executionData jacocoMerge.destinationFile
sourceDirectories srcDirs
classDirectories classDirs
violationRules.rule.limit.minimum = 0.38
}
task jacocoReport(type: JacocoReport) {
dependsOn jacocoMerge
executionData jacocoMerge.destinationFile
sourceDirectories srcDirs
classDirectories classDirs
}
}
A: Yes, I find another solution for it, that is to write limit rule in each module, such as for module-A, its code coverage is 50%, so in the build.gradle file in module-A, the rule is as following:
// for moudle-A module
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.5
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51372406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Date and Json in type definition for graphql Is it possible to have a define a field as Date or JSON in my graphql schema ?
type Individual {
id: Int
name: String
birthDate: Date
token: JSON
}
actually the server is returning me an error saying :
Type "Date" not found in document.
at ASTDefinitionBuilder._resolveType (****node_modules\graphql\utilities\buildASTSchema.js:134:11)
And same error for JSON...
Any idea ?
A: Have a look at custom scalars: https://www.apollographql.com/docs/graphql-tools/scalars.html
create a new scalar in your schema:
scalar Date
type MyType {
created: Date
}
and create a new resolver:
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';
const resolverMap = {
Date: new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value); // value from the client
},
serialize(value) {
return value.getTime(); // value sent to the client
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return parseInt(ast.value, 10); // ast value is always in string format
}
return null;
},
})
};
A: Primitive scalar types in GraphQL are Int, Float, String, Boolean and ID. For JSON and Date you need to define your own custom scalar types, the documentation is pretty clear on how to do this.
In your schema you have to add:
scalar Date
type MyType {
created: Date
}
Then, in your code you have to add the type implementation:
import { GraphQLScalarType } from 'graphql';
const dateScalar = new GraphQLScalarType({
name: 'Date',
parseValue(value) {
return new Date(value);
},
serialize(value) {
return value.toISOString();
},
})
Finally, you have to include this custom scalar type in your resolvers:
const server = new ApolloServer({
typeDefs,
resolvers: {
Date: dateScalar,
// Remaining resolvers..
},
});
This Date implementation will parse any string accepted by the Date constructor, and will return the date as a string in ISO format.
For JSON you might use graphql-type-json and import it as shown here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49693928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "59"
} |
Q: Spring Boot 2.1.0 Web app and Java 11 fail to maven clean install The following web app fail to maven clean install: https://github.com/cassiusvm/sfg-pet-clinic
The error is below:
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/cassius/git/sfg-pet-clinic/pet-clinic-web/src/main/java/guru/springframework/sfgpetclinic/controllers/PetController.java:[3,47] package guru.springframework.sfgpetclinic.model does not exist
The following web app don't fail to maven clean install: https://github.com/cassiusvm/spring5-recipe-app
On Eclipse IDE 2018-09, both are successfully constructed and they run fine.
Both use Spring Boot 2.1.0 and Java 11.
How to maven install the sfg-pet-clinic web app with success, please ?
A: Solved it.
I did include id repackage to plugin spring-boot-maven-plugin on module pet-clinic-data.
I did include the dependency mockito-core to plugin wro4j-maven-plugin on module pet-clinic-web.
A: I'm on the same project pet-clinic-web, and for me was enough to add the dependency mockito-core to wro4j-maven-plugin.
Though when the project was on jdk 8 I didn't have this problem. The problem started when I update to jdk 11.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53269168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: unable to find matching constructor for: java.time.ZonedDateTime() i have a very simple code base and i feel really silly here. Why am i getting the error groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.time.ZonedDateTime()
import org.testng.annotations.Test
import java.time.ZonedDateTime
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
class timeTests {
Logger log = LogManager.getLogger(this.class.getName())
def startTime(){
return new ZonedDateTime().now()
}
def endTime(){
def start = startTime()
def end = start.plusSeconds(5)
return end
}
@Test
void test(){
log.info(endTime())
}
}
example taken from: https://www.geeksforgeeks.org/zoneddatetime-now-method-in-java-with-examples/
A: The constructor does not exist. Use ZonedDateTime.now() or one of the equivalents. See the relevant JavaDoc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63563576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Querystring for Paypal I am making the following get request to Paypal Sandbox. But it says some problem with merchant account.
Is there any way that i can see what i am sending wrong? Here is the request URL
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_cart&[email protected]&invoice=1949¤cy_code=USD&item_name=localhost&item_number=1&quantity=1&amount=100.00&return=http://localhost/drupal/user/register&cancel_return=http://localhost/drupal/paypal/cancel
A: You are missing one of the variables:
The string should be :
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_cart&[email protected]&invoice=1949¤cy_code=USD&item_name=localhost&item_number=1&quantity=1&amount=100.00&return=http://localhost/drupal/user/register&cancel_return=http://localhost/drupal/paypal/cancel&add=1
add=1 is missing
Check the variables associated with cart command here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26558639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using blocks that returns and takes a parameter So in AFNetworking there is a function as follows:
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
cacheName:(NSString *)cacheNameOrNil
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
I am trying to use it as follows:
[AFImageRequestOperation imageRequestOperationWithRequest:nil imageProcessingBlock:^UIImage * (UIImage *) {
}cacheName:@"nsurl" success:^(NSURLRequest *request, NSHTTPURLResponse * response, UIImage * image){
}failure:^(NSURLRequest *request, NSHTTPURLResponse * response, NSError * error){
}];
However it doesn't seem to be correct in the UIImage part.. any ideas?
A: You are almost there - your code was missing a parameter name for the image in the first block:
[AFImageRequestOperation imageRequestOperationWithRequest:nil imageProcessingBlock:^UIImage * (UIImage *image) { // <<== HERE
} cacheName:@"nsurl" success:^(NSURLRequest *request, NSHTTPURLResponse * response, UIImage * image){
}failure:^(NSURLRequest *request, NSHTTPURLResponse * response, NSError * error){
}];
I think this is a bug in Xcode, because it expanded the signature into precisely what you posted, without the parameter name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10628447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to handle both `with open(...)` and `sys.stdout` nicely? Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet:
if target:
with open(target, 'w') as h:
h.write(content)
else:
sys.stdout.write(content)
I would like to rewrite it and handle both targets uniformly.
In ideal case it would be:
with open(target, 'w') as h:
h.write(content)
but this will not work well because sys.stdout is be closed when leaving with block and I don't want that. I neither want to
stdout = open(target, 'w')
...
because I would need to remember to restore original stdout.
Related:
*
*Redirect stdout to a file in Python?
*Handling Exceptions - interesting article about handling exceptions in Python, as compared to C++
Edit
I know that I can wrap target, define separate function or use context manager. I look for a simple, elegant, idiomatic solution fitting that wouldn't require more than 5 lines
A: Another possible solution: do not try to avoid the context manager exit method, just duplicate stdout.
with (os.fdopen(os.dup(sys.stdout.fileno()), 'w')
if target == '-'
else open(target, 'w')) as f:
f.write("Foo")
A: Stick with your current code. It's simple and you can tell exactly what it's doing just by glancing at it.
Another way would be with an inline if:
handle = open(target, 'w') if target else sys.stdout
handle.write(content)
if handle is not sys.stdout:
handle.close()
But that isn't much shorter than what you have and it looks arguably worse.
You could also make sys.stdout unclosable, but that doesn't seem too Pythonic:
sys.stdout.close = lambda: None
with (open(target, 'w') if target else sys.stdout) as handle:
handle.write(content)
A: import contextlib
import sys
with contextlib.ExitStack() as stack:
h = stack.enter_context(open(target, 'w')) if target else sys.stdout
h.write(content)
Just two extra lines if you're using Python 3.3 or higher: one line for the extra import and one line for the stack.enter_context.
A: If it's fine that sys.stdout is closed after with body, you can also use patterns like this:
# Use stdout when target is "-"
with open(target, "w") if target != "-" else sys.stdout as f:
f.write("hello world")
# Use stdout when target is falsy (None, empty string, ...)
with open(target, "w") if target else sys.stdout as f:
f.write("hello world")
or even more generally:
with target if isinstance(target, io.IOBase) else open(target, "w") as f:
f.write("hello world")
A: As pointed in Conditional with statement in Python, Python 3.7 allows using contextlib.nullcontext for that:
from contextlib import nullcontext
with open(target, "w") if target else nullcontext(sys.stdout) as f:
f.write(content)
A: An improvement of Wolph's answer
import sys
import contextlib
@contextlib.contextmanager
def smart_open(filename: str, mode: str = 'r', *args, **kwargs):
'''Open files and i/o streams transparently.'''
if filename == '-':
if 'r' in mode:
stream = sys.stdin
else:
stream = sys.stdout
if 'b' in mode:
fh = stream.buffer # type: IO
else:
fh = stream
close = False
else:
fh = open(filename, mode, *args, **kwargs)
close = True
try:
yield fh
finally:
if close:
try:
fh.close()
except AttributeError:
pass
This allows binary IO and pass eventual extraneous arguments to open if filename is indeed a file name.
A: Just thinking outside of the box here, how about a custom open() method?
import sys
import contextlib
@contextlib.contextmanager
def smart_open(filename=None):
if filename and filename != '-':
fh = open(filename, 'w')
else:
fh = sys.stdout
try:
yield fh
finally:
if fh is not sys.stdout:
fh.close()
Use it like this:
# For Python 2 you need this line
from __future__ import print_function
# writes to some_file
with smart_open('some_file') as fh:
print('some output', file=fh)
# writes to stdout
with smart_open() as fh:
print('some output', file=fh)
# writes to stdout
with smart_open('-') as fh:
print('some output', file=fh)
A: Why LBYL when you can EAFP?
try:
with open(target, 'w') as h:
h.write(content)
except TypeError:
sys.stdout.write(content)
Why rewrite it to use the with/as block uniformly when you have to make it work in a convoluted way? You'll add more lines and reduce performance.
A: I'd also go for a simple wrapper function, which can be pretty simple if you can ignore the mode (and consequently stdin vs. stdout), for example:
from contextlib import contextmanager
import sys
@contextmanager
def open_or_stdout(filename):
if filename != '-':
with open(filename, 'w') as f:
yield f
else:
yield sys.stdout
A: Okay, if we are getting into one-liner wars, here's:
(target and open(target, 'w') or sys.stdout).write(content)
I like Jacob's original example as long as context is only written in one place. It would be a problem if you end up re-opening the file for many writes. I think I would just make the decision once at the top of the script and let the system close the file on exit:
output = target and open(target, 'w') or sys.stdout
...
output.write('thing one\n')
...
output.write('thing two\n')
You could include your own exit handler if you think its more tidy
import atexit
def cleanup_output():
global output
if output is not sys.stdout:
output.close()
atexit(cleanup_output)
A: This is a simpler and shorter version of the accepted answer
import contextlib, sys
def writer(fn):
@contextlib.contextmanager
def stdout():
yield sys.stdout
return open(fn, 'w') if fn else stdout()
usage:
with writer('') as w:
w.write('hello\n')
with writer('file.txt') as w:
w.write('hello\n')
A: If you really must insist on something more "elegant", i.e. a one-liner:
>>> import sys
>>> target = "foo.txt"
>>> content = "foo"
>>> (lambda target, content: (lambda target, content: filter(lambda h: not h.write(content), (target,))[0].close())(open(target, 'w'), content) if target else sys.stdout.write(content))(target, content)
foo.txt appears and contains the text foo.
A: How about opening a new fd for sys.stdout? This way you won't have any problems closing it:
if not target:
target = "/dev/stdout"
with open(target, 'w') as f:
f.write(content)
A: if (out != sys.stdout):
with open(out, 'wb') as f:
f.write(data)
else:
out.write(data)
Slight improvement in some cases.
A: The following solution is not a beauty, but from a time long, long ago; just before with ...
handler = open(path, mode = 'a') if path else sys.stdout
try:
print('stuff', file = handler)
... # other stuff or more writes/prints, etc.
except Exception as e:
if not (path is None): handler.close()
raise e
handler.close()
A: One way to solve it is with polymorphism. Pathlib.path has an open method that functions as you would expect:
from pathlib import Path
output = Path("/path/to/file.csv")
with output.open(mode="w", encoding="utf-8") as f:
print("hello world", file=f)
we can copy this interface for printing
import sys
class Stdout:
def __init__(self, *args):
pass
def open(self, mode=None, encoding=None):
return self
def __enter__(self):
return sys.stdout
def __exit__(self, exc_type, exc_value, traceback):
pass
Now we simply replace Path with Stdout
output = Stdout("/path/to/file.csv")
with output.open(mode="w", encoding="utf-8") as f:
print("hello world", file=f)
This isn't necessarily better than overloading open, but it's a convenient solution if you're using Path objects.
A: With python 3 you can used wrap stdout file descriptor with IO object and avoid closing on context leave it with closefd=False:
h = open(target, 'w') if target else open(sys.stdout.fileno(), 'w', closefd=False)
with h as h:
h.write(content)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17602878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "123"
} |
Q: Negative margin on table row How do I give a <tr> a negative margin to move it up? I'm trying to move .small-item-block
<tr>
<td class="item-name">Caprese</td>
<td class="item-description">Fresh mozzarella, tomato, fresh basil and balsamic vinegar on a bed of spinach.</td>
<td>$4.00</td>
<td>$20.00</td>
</tr>
<tr class="small-item-block" >
<td class="item-name"></td>
<td class="item-addition-name">Add Bacon</td>
<td class="item-addition-price">$1.00</td>
<td class="item-addition-price">$3.00</td>
</tr>
CSS
tr.small-item-block {
margin-top: -10px;
border-spacing: -10px;
}
Here is the JS Fiddle.
A: You can't really move a row any higher than the row above it, so I think your best bet would be to remove margin/padding from the <td>s inside that <tr>. Example:
tr.small-item-block td {
margin-top: 0;
padding-top: 0;
}
A: You can't move a tr, but you can set the td's to position: relative, and then set a negative top property, like:
tr.small-item-block td {
position: relative;
top: -10px;
}
Here's your fiddle updated: http://jsfiddle.net/L4gLM/2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24148495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: VueJS Front-end never receives response from NodeJS backend I'm trying to set up a login feature in my web application, where the backend uses a MongoDB database and is done with NodeJS (express), and the front-end with VueJS. However, whenever I try to send back the response from the backend to the front-end, the front-end never seems to get it. Postman also never gets the response. Here is the code:
Backend:
app.post('/login', async (req,res) => {
let qusername;
let qpassword;
console.log(req.body);
await User.find({username: req.body.username}, (err,user) => {
if (user == null){
return res.status(400).send('User not found');
}
qusername = user[0].username;
qpassword = user[0].password;
});
try{
const user = { username: qusername, password: qpassword};
await bcrypt.compare(req.body.password, user.password, (err,res) => {
if(err){
res.status(500).send(err.message);
}
if(res){
const accessToken = jwt.sign(user, JWT_SECRET, { expiresIn: 300}, (err, accessToken) => {
console.log(accessToken);
if(err) {
res.status(500).send(err.message);
}
console.log("before");
res.send(accessToken);
console.log("after");
});
}
else {
res.send('Wrong password');
}
});
}
catch(e) {
console.log(e);
res.status(500).json({ message: e.message });
}
});
Front-end:
async getToken({ commit }, { user }) {
try {
const response = await axios.post(`${HOST}:${PORT}/login`, user);
const authToken = response.data;
commit("setToken", { authToken });
} catch (e) {
console.error(e);
}
}
The backend is logging the correct request body, the JWT and "before", but not "after". So the problem really occurs in res.send().
A: As pointed out by Danizavtz, the issue was that I had two variables named res. Changed the variable name in bcrypt.compare() from res to result and now everything works perfectly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65415228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Have trouble to understand why this code fails Have been working on this problem for days and cant figure it out. On line with ExecuteMso I get following error message Method "ExecuteMso" of object "_CommandBars" failed. I'm having difficulty to understand or find why.
Searched web for days.
Sub GenerateReport()
Dim Wapp As Object
'Launches word application
Set Wapp = CreateObject("Word.Application")
Wapp.Visible = True
Wapp.Activate
...
Call CreateChart(Wapp)
End Sub
'Procedure, chart in word
Sub CreateChart(Wapp As Object)
Dim FomtCh As Excel.ChartObject
Dim InlineShCount As Long
'Create reference to excel chart
Set FomtCh = ThisWorkbook.Sheets("Doc").ChartObjects(1)
'Copy from excel chart to word chart
FomtCh.Chart.ChartArea.Copy
'Counts number of shapes in word document
InlineShCount = ActiveDocument.InlineShapes.Count
'Paste without linking to excel chart and embeding copy in word file
Word.Application.CommandBars.ExecuteMso ("PasteExcelChartSourceFormatting")
Do '<~~ wait completion of paste operation
DoEvents
Loop Until ActiveDocument.InlineShapes.Count > InlineShCount
End Sub
A: Not all of the Ribbon commands exist in the legacy CommandBars collection.
To get a full listing of the available commands create a blank document in Word and run the code below (from Word).
Sub ListCommands()
Dim cbar As CommandBar
Dim cbarCtrl As CommandBarControl
For Each cbar In Application.CommandBars
For Each cbarCtrl In cbar.Controls
Selection.TypeText cbarCtrl.Caption & vbCr
Next cbarCtrl
Next cbar
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57269151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Selecting Single XML from Multiple XMLs rows in a Table I have an XML column in a table where each row of the table is a complete XML node. I am trying to simply trying to select a subset of these rows and generate an XML document out of it with a root node. I thought I could do the following, but it keeps added an extra wrapper around each node with the name of the XML column. Is there anything different I can do to not get this wrapper?
Sample Data Structure:
CREATE TABLE ActivityTable
(
XMLDATA AS XML
)
INSERT INTO [ActivityTable] VALUES ( '<Activity>This is activity one</Activity>' )
INSERT INTO [ActivityTable] VALUES ( '<Activity>This is activity two</Activity>' )
INSERT INTO [ActivityTable] VALUES ( '<Activity>This is activity three</Activity>' )
Query to get Data
SELECT
XMLdata FROM ActivityTable
FOR XML PATH(''), ROOT('RootNode')
What I'm getting:
<root>
<XMLdata>
<Activity>This is activity one</Activity>
</XMLdata>
<XMLdata>
<Activity>This is activity two</Activity>
</XMLdata>
<XMLdata>
<Activity>This is activity three</Activity>
</XMLdata>
</root>
What I want:
<root>
<Activity>This is activity one</Activity>
<Activity>This is activity two</Activity>
<Activity>This is activity three</Activity>
</root>
A: SELECT XMLdata AS '*'
FROM ActivityTable
FOR XML PATH(''), ROOT('RootNode')
Columns with a Name Specified as a Wildcard Character
If the column name specified is a wildcard character (*), the content
of that column is inserted as if there is no column name specified.
A: using .query('/Node') is a way of querying for a certain node, and you don't get the XMLData tags back. Hope it helps!
SELECT XMLDATA.query('/Activity') FROM ActivityTable
FOR XML PATH(''), ROOT('root')
SQL Fiddle example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14283480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Should we use Visual Studio 2010 for all SQL Server Database Development? Our company currently has seven dedicated SQL Server 2008 servers each running an average of 10 databases.
All databases have many stored procedures and UDFs that commonly reference other databases both on the same server and also across linked servers.
We currently use SSMS for all database related administration and development but we have recently purchased Visual Studio 2010 primarily for ongoing C# WinForms and ASP.NET development.
I have used VS2010 to perform schema comparisons when rolling out changes from a development server into production and I'm finding it great for this task.
We would like to consider using VS2010 for all database development going forward but as far as I understand, we would have to set up ALL databases as projects because of the dependencies on linked servers etc.
My question is, do you have any experience using VS2010 for database development in a similar environment? Is it easy to use in tandem with SSMS or is it a one way street once VS2010 projects have been set up for all databases?
Can you make any recommendations/impart any experience with a similar scenario?
Thanks,
Luke
A: I don't see any reason why you couldn't use SSMS in tandom with VS 2010 - actually, for some operations like CREATE DATABASE, you'll have to - you cannot do that from VS.
VS is probably a pretty good database dev environment for 60-80% of your cases - but I doubt you'll be able to completely forget about SSMS. But again: the Visual Studio database projects are really nothing other than collections of SQL scripts - so I don't see why anyone would say you have to "go all the way" with VS if you start using it that way..... it just executes SQL scripts against a SQL database - you can and might need to still use SQL Server Management Studio for some more advanced tasks.....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2987047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.