title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
SQL Xamarin Forms Delete Item Duplication
|
<p>I have an application where items are added to a collection view which is swipable to be deleted. I am using SQL to do so. However, when deleting the item, sometimes the items have 'duplicated' until a refresh happens and then they disappear once again. How do I go about fixing this issue and why does it only occur sometimes? (See below for bug).</p>
<p>Here is the Xaml:</p>
<pre><code><RefreshView x:DataType="local:ItemsViewModel" Command="{Binding LoadItemsCommand}" IsRefreshing="{Binding IsBusy, Mode=TwoWay}">
<CollectionView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
SelectionMode="None">
<CollectionView.ItemTemplate>
<DataTemplate>
<SwipeView>
<SwipeView.RightItems>
<SwipeItems Mode="Execute">
<SwipeItem Text="Delete"
BackgroundColor="Red"
Command="{Binding Source={RelativeSource AncestorType={x:Type local:ItemsViewModel}}, Path=DeleteItemCommand}"
CommandParameter="{Binding Source={RelativeSource Self}, Path=BindingContext}"/>
</SwipeItems>
</SwipeView.RightItems>
<StackLayout Padding="10" x:DataType="model:Item" BackgroundColor="#333333">
<Label Text="{Binding Text}"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemTextStyle}"
FontSize="16"
FontAttributes="Bold"
TextColor="White"/>
<Label Text="{Binding Description}"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemDetailTextStyle}"
FontSize="13"
TextColor="White"/>
<Label Text="{Binding DueDate}"
Style="{DynamicResource ListItemDetailTextStyle}"
FontSize="13"
TextColor="White"/>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer
NumberOfTapsRequired="1"
Command="{Binding Source={RelativeSource AncestorType={x:Type local:ItemsViewModel}}, Path=ItemTapped}"
CommandParameter="{Binding .}">
</TapGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
</SwipeView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</RefreshView>
</code></pre>
<p>Here is the delete function:</p>
<pre><code>private async Task OnDeleteItem(Item selectedItem)
{
await LocalDatabaseService.DeleteItem(selectedItem);
}
</code></pre>
<p>SQL Delete:</p>
<pre><code>public async Task DeleteItem(Item item)
{
var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyData3.db");
var db = new SQLiteAsyncConnection(databasePath);
await db.DeleteAsync(item);
OnDeletedItem?.Invoke();
}
</code></pre>
<p>OnDeleteItem?.Invoke();</p>
<pre><code>private void LocalDatabaseService_OnDeletedItem()
{
_ = ExecuteLoadItemsCommand();
}
</code></pre>
<p>ExecuteLoadItemsCommand();</p>
<pre><code>async Task ExecuteLoadItemsCommand()
{
IsBusy = true;
try
{
Items.Clear();
var items = await LocalDatabaseService.GetAllItems();
foreach (var item in items)
{
Items.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
</code></pre>
<p>Here is what happens occasionally:
<a href="https://i.stack.imgur.com/VnF7e.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VnF7e.gif" alt="enter image description here" /></a></p>
<p>any help is appreciated, Thanks.</p>
| 3 | 2,453 |
Azure devops timeout when downloading artifacts
|
<p>The release pipeline was working fine until recently, nothing had changed but it was saying that the agents were offline or disabled when they weren't. It turned out they needed to be updated from version <code>2.163</code> to <code>2.188</code> after this the pipeline would begin, but now it times out after downloading only a few artifacts.</p>
<p>What could be the issue?</p>
<p>EDIT:</p>
<p>The pre-releases <code>2.188.1</code> and <code>2.188.2</code> of the agents are allowing the pipeline to begin, but they timeout when downloading the artifacts. Anything before that version won't begin the pipeline. The last full release is <code>v2.187.2</code></p>
<p>EDIT 2:</p>
<p>I have noticed that during a change to the release pipeline it automatically updates this property in the defintion for every task.</p>
<p><code>"currentRelease": {"id": 3664,"url": "https://foo/bar/_apis/Release/releases/3664","_links": {}}</code></p>
<p>3664 is updated to a new number in both places</p>
<p>When I reverted this change, these properties are unchanged and keep that version and the release is still failing to start.</p>
<p>Logs when timing out:</p>
<p>2021-06-22T10:32:03.0526533Z Task : Download build artifacts
2021-06-22T10:32:03.0527316Z Description : Download files that were saved as artifacts of a completed build
2021-06-22T10:32:03.0527728Z Version : 1.189.0
2021-06-22T10:32:03.0528349Z Author : Microsoft Corporation
2021-06-22T10:32:03.0529128Z Help : <a href="https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/download-build-artifacts" rel="nofollow noreferrer">https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/download-build-artifacts</a>
2021-06-22T10:32:03.0529670Z ==============================================================================
2021-06-22T10:32:04.5890571Z Download from the specified build: #7588
2021-06-22T10:32:04.6009135Z Download artifact to: D:\B\4\r1\a/CI-Master/
2021-06-22T10:32:09.9551492Z Start downloading FCS artifact- drop
2021-06-22T10:32:09.9555929Z Minimatch patterns: [**]</p>
<p>2021-06-22T10:32:34.2488452Z Downloading: D:\B\4\r1\a/foo</p>
<p>2021-06-22T10:32:34.2544775Z Downloading: D:\B\4\r1\a/bar</p>
<p>2021-06-22T10:32:34.2552426Z Downloading: D:\B\4\r1\a/foo</p>
<p>2021-06-22T10:32:34.4205359Z Downloading: D:\B\4\r1\a/bar</p>
<p>2021-06-22T10:32:34.4232934Z Downloading: D:\B\4\r1\a/foo</p>
<p>2021-06-22T10:32:34.4298593Z Downloading: D:\B\4\r1\a/bar</p>
<p>2021-06-22T10:32:34.4710656Z Downloading: D:\B\4\r1\a/foo</p>
<p>2021-06-22T10:32:34.4722254Z Downloading: D:\B\4\r1\a/bar</p>
<p>EDIT 3:</p>
<p>There was another pre-release <code>2.188.3</code> since using this one I get these error messages in the log when trying to download the artifacts:</p>
<p>[https://a45vsblobproduks133.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/FCEBC807EB275E589526A319F580BE1B820DBCBB851D7E81C0E2BADDCC81783802?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:59:37Z&sp=r&rscl=x-e2eid-de94b040-568b459c-8cda94e5-026534ed-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://efcvsblobproduks136.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/BDC14BEB4450AF1EE289CEA5F6B6CC274C8001913AE60F90848E41A0C557965502?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:52:13Z&sp=r&rscl=x-e2eid-d318c08f-5f3148e4-a0411ef3-c2bcfb72-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://n5tvsblobproduks163.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/B078AA0E6EDECA41E40653102F86D48A272C221DEB4628C4CDBA440257C3079102?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:50:39Z&sp=r&rscl=x-e2eid-c4e45f8a-d9f54f42-b607074d-a31fd556-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://e9bvsblobproduks184.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/3B33EC397D2EDD7B9D78264333B7278932B32C208D969E3C8292350E2C6A7C8002?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:36:57Z&sp=r&rscl=x-e2eid-14dabff3-f7f04eb4-981bebb4-43531bd4-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://bipvsblobproduks176.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/8C234856A821AF42832040AD4B84FA11247E56C61FAA030F59B72AE96B5EF0DA02?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:46:26Z&sp=r&rscl=x-e2eid-b27f132d-33f545f9-b27d072b-ce6646a4-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://35rvsblobproduks146.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/D2FA706A53F22231B91D578430E9C3EAA837904E8874F774D1C65F83700401CC02?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:54:41Z&sp=r&rscl=x-e2eid-7c1cedd2-c5154bd9-b9e8f474-b46ca697-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://pubvsblobproduks130.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/08830F9C5398685A635B5B689C6D6A77E76E37CCFEE38313C611D22868E45B3702?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T10:01:00Z&sp=r&rscl=x-e2eid-829fca95-c1c743b5-b8ec857a-94a72dab-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://e56vsblobproduks19.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/63D246F0DA6625164C85C92B1724DDA1C38CC2273971AB1542201D7016C17CF702?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:41:43Z&sp=r&rscl=x-e2eid-a5abdf02-304a4aad-8d866aac-1bc0dd5d-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://a45vsblobproduks133.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/FCEBC807EB275E589526A319F580BE1B820DBCBB851D7E81C0E2BADDCC81783802?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:59:37Z&sp=r&rscl=x-e2eid-de94b040-568b459c-8cda94e5-026534ed-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://efcvsblobproduks136.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/BDC14BEB4450AF1EE289CEA5F6B6CC274C8001913AE60F90848E41A0C557965502?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:52:13Z&sp=r&rscl=x-e2eid-d318c08f-5f3148e4-a0411ef3-c2bcfb72-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://e9bvsblobproduks184.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/3B33EC397D2EDD7B9D78264333B7278932B32C208D969E3C8292350E2C6A7C8002?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:36:57Z&sp=r&rscl=x-e2eid-14dabff3-f7f04eb4-981bebb4-43531bd4-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://n5tvsblobproduks163.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/B078AA0E6EDECA41E40653102F86D48A272C221DEB4628C4CDBA440257C3079102?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:50:39Z&sp=r&rscl=x-e2eid-c4e45f8a-d9f54f42-b607074d-a31fd556-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://35rvsblobproduks146.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/D2FA706A53F22231B91D578430E9C3EAA837904E8874F774D1C65F83700401CC02?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:54:41Z&sp=r&rscl=x-e2eid-7c1cedd2-c5154bd9-b9e8f474-b46ca697-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://bipvsblobproduks176.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/8C234856A821AF42832040AD4B84FA11247E56C61FAA030F59B72AE96B5EF0DA02?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:46:26Z&sp=r&rscl=x-e2eid-b27f132d-33f545f9-b27d072b-ce6646a4-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://pubvsblobproduks130.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/08830F9C5398685A635B5B689C6D6A77E76E37CCFEE38313C611D22868E45B3702?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T10:01:00Z&sp=r&rscl=x-e2eid-829fca95-c1c743b5-b8ec857a-94a72dab-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://e56vsblobproduks19.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/63D246F0DA6625164C85C92B1724DDA1C38CC2273971AB1542201D7016C17CF702?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:41:43Z&sp=r&rscl=x-e2eid-a5abdf02-304a4aad-8d866aac-1bc0dd5d-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 4/5, Task was requested to be canceled.
[https://a45vsblobproduks133.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/FCEBC807EB275E589526A319F580BE1B820DBCBB851D7E81C0E2BADDCC81783802?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:59:37Z&sp=r&rscl=x-e2eid-de94b040-568b459c-8cda94e5-026534ed-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://n5tvsblobproduks163.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/B078AA0E6EDECA41E40653102F86D48A272C221DEB4628C4CDBA440257C3079102?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:50:39Z&sp=r&rscl=x-e2eid-c4e45f8a-d9f54f42-b607074d-a31fd556-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://efcvsblobproduks136.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/BDC14BEB4450AF1EE289CEA5F6B6CC274C8001913AE60F90848E41A0C557965502?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:52:13Z&sp=r&rscl=x-e2eid-d318c08f-5f3148e4-a0411ef3-c2bcfb72-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://e9bvsblobproduks184.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/3B33EC397D2EDD7B9D78264333B7278932B32C208D969E3C8292350E2C6A7C8002?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:36:57Z&sp=r&rscl=x-e2eid-14dabff3-f7f04eb4-981bebb4-43531bd4-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://bipvsblobproduks176.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/8C234856A821AF42832040AD4B84FA11247E56C61FAA030F59B72AE96B5EF0DA02?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:46:26Z&sp=r&rscl=x-e2eid-b27f132d-33f545f9-b27d072b-ce6646a4-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://35rvsblobproduks146.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/D2FA706A53F22231B91D578430E9C3EAA837904E8874F774D1C65F83700401CC02?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:54:41Z&sp=r&rscl=x-e2eid-7c1cedd2-c5154bd9-b9e8f474-b46ca697-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://pubvsblobproduks130.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/08830F9C5398685A635B5B689C6D6A77E76E37CCFEE38313C611D22868E45B3702?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T10:01:00Z&sp=r&rscl=x-e2eid-829fca95-c1c743b5-b8ec857a-94a72dab-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.
[https://e56vsblobproduks19.blob.core.windows.net/db3e0237a17a774f58bb16e2c2f11aea06/63D246F0DA6625164C85C92B1724DDA1C38CC2273971AB1542201D7016C17CF702?sv=2019-07-07&sr=b&spr=https&se=2021-06-25T09:41:43Z&sp=r&rscl=x-e2eid-a5abdf02-304a4aad-8d866aac-1bc0dd5d-session-21903563-37d34744-8179a8e6-c0d8f1a5] Try 3/5, Task was requested to be canceled.</p>
| 3 | 6,027 |
Relationship Between AffineTransformation and Polygon's Point
|
<p>As a project, I'm attempting to create an emulation of the game Asteroids. Currently, I'm trying to make it so then the spaceship appears on the opposite side of the GUI if the player ever sends himself out of bounds.</p>
<p>However, I've become quite confused between how AffineTransformation's rotate and createTransformedShape function interacts with the x and y points of the polygon. </p>
<p>Currently, I have the spaceship working; it flies in the angle the user specifies it and all the movement involved works fine. However, when I tried to get the lowest X coordinate of the spaceship to compare if it ever goes bigger than the constant <code>WIDTH</code>, it returns 780. This happens all the time whether or not I am on one side of the map to the other, it always returns 780. This I find really strange because shouldn't it return the smallest X coordinate of where it currently is?
<a href="https://i.stack.imgur.com/RA7rt.png" rel="nofollow noreferrer">Here is a screenshot of the console displaying that the "smallest x coordinate" of the polygon is 780, despite not being at 780</a></p>
<p>Can someone explain to me why the X coordinates of the polygon are not changing? I have 2 classes. One, which is the driver classes, and the other which is the ship class which extends Polygon.</p>
<pre><code>public class AsteroidGame implements ActionListener, KeyListener{
public static AsteroidGame game;
public Renderer renderer;
public boolean keyDown = false;
public int playerAngle = 0;
public boolean left = false;
public boolean right = false;
public boolean go = false;
public boolean back = false;
public boolean still = true;
public double angle = 0;
public int turnRight = 5;
public int turnLeft = -5;
public Shape transformed;
public Shape transformedLine;
public Point p1;
public Point p2;
public Point center;
public Point p4;
public final int WIDTH = 1600;
public final int HEIGHT = 800;
public Ship ship;
public AffineTransform transform = new AffineTransform();
public AsteroidGame(){
JFrame jframe = new JFrame();
Timer timer = new Timer(20, this);
renderer = new Renderer();
jframe.add(renderer);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(WIDTH, HEIGHT);
jframe.setVisible(true);
jframe.addKeyListener(this);
jframe.setResizable(false);
int xPoints[] = {800, 780, 800, 820};
int yPoints[] = {400, 460, 440, 460};
p1 = new Point(400,400);
p2 = new Point(380, 460);
center = new Point(400,440);//center
p4 = new Point(420, 460);
ship = new Ship(xPoints, yPoints, 4, 0);
transformed = transform.createTransformedShape(ship);
timer.start();
}
public void repaint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.WHITE);
g2d.draw(transformed);
/*
g2d.draw(r2);
Path2D.Double path = new Path2D.Double();
path.append(r, false);
AffineTransform t = new AffineTransform();
t.rotate(Math.toRadians(45));
path.transform(t);
g2d.draw(path);
Rectangle test = new Rectangle(WIDTH/2, HEIGHT/2, 200, 100);
Rectangle test2 = new Rectangle(WIDTH/2, HEIGHT/2, 200, 100);
g2d.draw(test2);
AffineTransform at = AffineTransform.getTranslateInstance(100, 100);
g2d.rotate(Math.toRadians(45));
g2d.draw(test);
*/
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if (right){
ship.right();
transform.rotate(Math.toRadians(turnRight), ship.getCenterX(), ship.getCenterY());
System.out.println(ship.getCenterY());
}
else if (left){
ship.left();
transform.rotate(Math.toRadians(turnLeft), ship.getCenterX(), ship.getCenterY());
}
if (go){
ship.go();
//ship.x += Math.sin(Math.toRadians(angle)) * 5;
//ship.y
/*
ship.x += (int) Math.sin(Math.toRadians(angle));
ship.y += (int) Math.cos(Math.toRadians(angle));
*/
//System.out.println(Math.sin(Math.toRadians(ship.angle)) * 5 + "y" + Math.cos(Math.toRadians(ship.angle)) * 5);
}
else if (back){
ship.reverse();
}
ship.move();
//ship.decrement();
transformed = transform.createTransformedShape(ship);
if (ship.smallestX() >= WIDTH){
System.out.println("out");
}
renderer.repaint();
System.out.println("Smallest x coordinate: " + ship.smallestX());
}
public static void main(String[] args){
game = new AsteroidGame();
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
System.out.println("I am down");
right = true;
keyDown = true;
}else if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
System.out.println("I am down");
keyDown = true;
}
if (e.getKeyCode() == KeyEvent.VK_UP){
go = true;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN){
back = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
right = false;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_UP){
go = false;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
back = false;
}
still = true;
keyDown = false;
System.out.println("up");
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
</code></pre>
<p>Ship Class:</p>
<pre><code>public class Ship extends Polygon{
/**
*
*/
private double currSpeed = 0;
private static final long serialVersionUID = 1L;
public double angle;
public Ship(int[] x, int[] y, int points, double angle){
super(x, y, points);
this.angle= angle;
}
public void right(){
angle += 5;
}
public void left(){
angle -= 5;
}
public void move(){
for (int i = 0; i < super.ypoints.length; i++){
super.ypoints[i] -= currSpeed;
//System.out.println(super.ypoints[i]);
//System.out.println(super.xpoints[i]);
}
}
public void reverse(){
if (currSpeed > -15) currSpeed -= 0.2;
}
public void go(){
if (currSpeed < 25) currSpeed += 0.5;
}
public int smallestX(){
int min = super.xpoints[0];
for (int i = 0; i < super.xpoints.length; i++){
if (min > super.xpoints[i]){
min = super.xpoints[i];
}
}
return min;
}
public int smallestY(){
int min = super.ypoints[0];
for (int i = 0; i < super.ypoints.length; i++){
if (min < super.ypoints[i]){
min = super.ypoints[i];
}
}
return min;
}
public int getCenterX(){
return super.xpoints[2];
}
public int getCenterY(){
return super.ypoints[2];
}
public double getAng(){
return angle;
}
</code></pre>
| 3 | 3,412 |
Toolbar haven't the full size
|
<p>Hey Guys I want to make a Custom Toolbar. I tried so many things but nothing works.... So I have this in my manifest.xml:</p>
<pre><code><application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true">
<activity android:name=".HomeActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<!--android:theme="@style/HomeActionBar">-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</code></pre>
<p>And here my activity_home.xml:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.iiiii.iiiii.HomeActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="enterAlways|scroll" />
<!-- <Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Delete SharedPreferences" /> -->
</android.support.design.widget.CoordinatorLayout></code></pre>
</div>
</div>
</p>
<p>But look! I didn't get the full size of the ActionBar:
<a href="https://i.stack.imgur.com/50QHu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/50QHu.png" alt="enter image description here"></a></p>
| 3 | 1,025 |
Avoid new lines in csv because of carriage return with php
|
<p>doing my few first steps in PHP and I'm stuck. Been searching SO all afternoon but couldn't come up with a solution. Highly appreciate any advice from experienced devs.</p>
<p><strong>Scenario:</strong>
Users are asked to fill out a short survey consisting of two textareas. Upon hitting the submit button, the content of the textareas is written to a csv file.</p>
<p><strong>Problem:</strong>
My problem is that (while it does write the content) whenever people use carriage return in the textarea, it results in a new line in the csv file, thus messing it up. I've spent the afternoon reading up on stackoverflow and trying to use str_replace(); for rewriting all \n with spaces " ", alas to no avail.</p>
<p>Here is my <strong>HTML</strong>:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Survey name here</title>
<meta charset='utf-8'>
</head>
<body>
<?php
if(!empty($errorMessage))
{
echo("<p>Error!</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<div id="content">
<h1>Survey</h1>
<form action="post.php" method="post" id="survey">
<p><strong>Question 1:</strong><br />Do you like it or not?</p>
<p><textarea rows="6" cols="100" name="question1" value="<?=$answer;?>"><?php echo $answer ?></textarea></p>
<p><strong>Question 2:</strong><br />Would you prefer this or that?</p>
<p><textarea rows="6" cols="100" name="question2" value="<?=$answer2;?>"><?php echo $answer2 ?></textarea></p>
<input type="submit" name="formSubmit" value="Submit" id="submit" onclick="return Validate()"/>
</form>
</div><!-- End Content -->
</body>
</html>
</code></pre>
<p>And here is the <strong>PHP</strong> part:</p>
<pre><code><?php
if($_POST['formSubmit'] == "Submit")
{
$answer1 = $_POST['question1'];
$answer2 = $_POST['question2'];
// report error when not answered
$errorMessage = "";
if(empty($_POST['question1']))
{
$errorMessage .= "<li class='errormsg'>Please answer the question No. 1!</li>";
}
if(empty($_POST['question2']))
{
$errorMessage .= "<li class='errormsg'>Please answer the question No. 2!</li>";
}
// sending to CSV
if(empty($errorMessage))
{
str_replace('\r\n', ' ', $answer1 . $answer2);
$fs = fopen("test.csv","a");
fwrite($fs,$answer1 . ";" . $answer2 . "\n");
fclose($fs);
// after submit, head to thank you page
header("Location: thankyou.php");
exit;
}
}
?>
</code></pre>
<p>I figure I'm not applying the str_replace() function correctly. Who can help me?</p>
| 3 | 1,103 |
Script keep showing "SettingCopyWithWarning'
|
<p>Hello my problem is that my script keep showing below message </p>
<hr>
<p>SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame</p>
<p>See the caveats in the documentation: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy</a>
downcast=downcast</p>
<hr>
<p>I Searched the google for a while regarding this, and it seems like my code is somehow
assigning sliced dataframe to new variable, which is problematic. </p>
<p>The problem is ** I can't find where my code get problematic **
I tried copy function, or seperated the nested functions, but it is not working </p>
<p>I attached my code below. </p>
<pre><code>def case_sorting(file_get, col_get, methods_get, operator_get, value_get):
ops = {">": gt, "<": lt}
col_get = str(col_get)
value_get = int(value_get)
if methods_get is "|x|":
new_file = file_get[ops[operator_get](file_get[col_get], value_get)]
else:
new_file = file_get[ops[operator_get](file_get[col_get], np.percentile(file_get[col_get], value_get))]
return new_file
</code></pre>
<p>Basically what i was about to do was to make flask api that gets excel file as an input, and returns the csv file with some filtering. So I defined some functions first. </p>
<pre><code>def get_brandlist(df_input, brand_input):
if brand_input == "default":
final_list = (pd.unique(df_input["브랜드"])).tolist()
else:
final_list = brand_input.split("/")
if '브랜드' in final_list:
final_list.remove('브랜드')
final_list = [x for x in final_list if str(x) != 'nan']
return final_list
</code></pre>
<p>Then I defined the main function </p>
<pre><code>def select_bestitem(df_data, brand_name, col_name, methods, operator, value):
# // 2-1 // to remove unnecessary rows and columns with na values
df_data = df_data.dropna(axis=0 & 1, how='all')
df_data.fillna(method='pad', inplace=True)
# // 2-2 // iterate over all rows to find which row contains brand value
default_number = 0
for row in df_data.itertuples():
if '브랜드' in row:
df_data.columns = df_data.iloc[default_number, :]
break
else:
default_number = default_number + 1
# // 2-3 // create the list contains all the target brand names
brand_list = get_brandlist(df_input=df_data, brand_input=brand_name)
# // 2-4 // subset the target brand into another dataframe
df_data_refined = df_data[df_data.iloc[:, 1].isin(brand_list)]
# // 2-5 // split the dataframe based on the "brand name", and apply the input condition
df_per_brand = {}
df_per_brand_modified = {}
for brand_each in brand_list:
df_per_brand[brand_each] = df_data_refined[df_data_refined['브랜드'] == brand_each]
file = df_per_brand[brand_each].copy()
df_per_brand_modified[brand_each] = case_sorting(file_get=file, col_get=col_name, methods_get=methods,
operator_get=operator, value_get=value)
# // 2-6 // merge all the remaining dataframe
df_merged = pd.DataFrame()
for brand_each in brand_list:
df_merged = df_merged.append(df_per_brand_modified[brand_each], ignore_index=True)
final_df = df_merged.to_csv(index=False, sep=',', encoding='utf-8')
return final_df
</code></pre>
<p>And I am gonna import this function in my app.py later </p>
<p>I am quite new to all the coding, therefore really really sorry if my code is quite hard to understand, but I just really wanted to get rid of this annoying warning message. Thanks for help in advance :) </p>
| 3 | 1,371 |
How to add more nodes in the self signed certificate of Kubernetes Dashboard
|
<p>I finally managed to resolve my question related to how to add more nodes in the CAs of the Master nodes (<a href="https://stackoverflow.com/questions/65186710/how-to-add-extra-nodes-to-the-certificate-authority-data-from-a-self-signed-k8s/65198463?noredirect=1#comment115265632_65198463">How to add extra nodes to the certificate-authority-data from a self signed k8s cluster?</a>).</p>
<p>Now the problem that I am facing is I want to use kubeconfig file e.g. <code>~/.kube/config</code> to access the Dashboard.</p>
<p>I managed to figured it out by having the following syntax:</p>
<pre class="lang-sh prettyprint-override"><code>$ kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: DATA+OMITTED
server: https://IP:6443
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: kubernetes-admin
name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
user:
client-certificate-data: REDACTED
client-key-data: REDACTED
token: REDACTED
</code></pre>
<p>The problem that I am having is that I need to use the IP of one of the Master nodes in order to be able to reach the Dashboard. I would like to be able to use the LB IP to reach the Dashboard.</p>
<p>I assume this is related to the same problem that I had before as I can see from the file that the CAs are autogenerated.</p>
<pre class="lang-sh prettyprint-override"><code>args:
- --auto-generate-certificates
- etc etc
.
.
.
</code></pre>
<p>Apart from creating the CAs on your self in order to use them is there any option to pass e.g. IP1 / IP2 etc etc in a flag within the file?</p>
<p><strong>Update:</strong> I am deploying the Dashboard through the recommended way <code>kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml</code> (<a href="https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/" rel="nofollow noreferrer">Deploying the Dashboard UI</a>). The deployment is on prem but I have configured the cluster with an external loadbalancer (HAProxy) towards the Api and also Ingress and also <code>type: LoadBalancer</code> on Ingress. Everything seems to working as expected apart from the Dashboard UI (through LB IP). I am also using authentication mode <code>authorization-mode: Node,RBAC</code> on the kubeconfig file (if relevant).</p>
<p>I am access the Dashboard through Inress HTTPS e.g. <code>https://dashboard.example.com</code>.</p>
<p>I get the error <code>Not enough data to create auth info structure</code>. Found the <code>token: xxx</code> solution from this question <a href="https://stackoverflow.com/questions/48228534/kubernetes-dashboard-access-using-config-file-not-enough-data-to-create-auth-inf">Kubernetes Dashboard access using config file Not enough data to create auth info structure.</a>.</p>
<p>If I switch the LB IP with the Master nodes then I can access the UI with the kubeconfig file.</p>
<p>I just updated now to the latest version of the dashboard v2.0.5 is not working with the kubeconfig button / file but it works with the token directly <a href="https://github.com/kubernetes/dashboard/releases/tag/v2.0.5" rel="nofollow noreferrer">kubernetes/Dashoboard-v2.0.5</a>. With the previous version everything works as described above. No error logs in the pod logs.</p>
| 3 | 1,113 |
tensorflow gpu Resource Exhausted during model definition
|
<p>I get <strong>ResourceExhaustedError</strong> from tensorflow not during training but during my model definition, so che classic suggestion "decrease batch size" do not makes sense in this case.</p>
<p>Here is my model definition:</p>
<pre><code>def build_net(input_shape=(400, 300, 3),output_class_count=6):
model=keras.Sequential([
layers.Input(shape=input_shape,name='Input'),
layers.Conv2D(filters=128, kernel_size=3, strides=1,activation='relu',padding='same',name='C5'),
layers.Conv2D(filters=64, kernel_size=3, strides=1,activation='relu',padding='same',name='C7'),
layers.MaxPooling2D(pool_size=3, strides=2,name='MP8'),
layers.Flatten(),
layers.Dense(512, activation='relu',name='F10'),
layers.Dropout(rate=0.5),
layers.Dense(units=output_class_count,activation='softmax',name='Output')])
return model
model=build_net()
</code></pre>
<p>I have already used this code:</p>
<pre><code>gpu_devices = tf.config.experimental.list_physical_devices('GPU')
for device in gpu_devices:
tf.config.experimental.set_memory_growth(device, True)
</code></pre>
<p>My <code>nvidia-smi</code> output is:</p>
<p><a href="https://i.stack.imgur.com/OOnF3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OOnF3.png" alt="enter image description here" /></a></p>
<p>So the memory is not even completely full.</p>
<p>Here are the stats of the error.</p>
<pre><code>Limit: 10117251072
InUse: 7773144576
MaxInUse: 7773144832
NumAllocs: 22
MaxAllocSize: 3886415872
Reserved: 0
PeakReserved: 0
LargestFreeBlock: 0
</code></pre>
<p>Here is the Error:</p>
<pre><code>/tmp/ipykernel_19436/1499846676.py in build_mini_alexnet(input_shape, output_class_count)
14 layers.Dense(512, activation='relu',name='F10'),
15 layers.Dropout(rate=0.5),
---> 16 layers.Dense(units=output_class_count,activation='softmax',name='Output')])
17 return model
/python3.7/site-packages/tensorflow/python/training/tracking/base.py in _method_wrapper(self, *args, **kwargs)
585 self._self_setattr_tracking = False # pylint: disable=protected-access
586 try:
--> 587 result = method(self, *args, **kwargs)
588 finally:
589 self._self_setattr_tracking = previous_value # pylint: disable=protected-access
/python3.7/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
65 except Exception as e: # pylint: disable=broad-except
66 filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67 raise e.with_traceback(filtered_tb) from None
68 finally:
69 del filtered_tb
/python3.7/site-packages/keras/backend.py in random_uniform(self, shape, minval, maxval, dtype)
1920 return tf.random.uniform(
1921 shape=shape, minval=minval, maxval=maxval, dtype=dtype,
-> 1922 seed=self.make_legacy_seed())
1923
1924 def truncated_normal(self, shape, mean=0., stddev=1., dtype=None):
ResourceExhaustedError: failed to allocate memory [Op:AddV2]
</code></pre>
<p>Thank you for your help.</p>
| 3 | 1,454 |
pass coordinates from googlemaps react child to parent in functional component typescript
|
<p>I'm using @googlemaps/react-wrapper to make a map component in my react application using the example from <a href="https://developers.google.com/maps/documentation/javascript/react-map" rel="nofollow noreferrer">googlemaps</a>, and adding an event on drag marker to refresh coordinates, this works fine now. but i need to call the map component outside to refresh a input value with the coordiantes.
The error i get it is:</p>
<blockquote>
<p>Binding element 'childToParent' implicitly has an 'any' type.*
Please could help me to understand how i could send the values to paren using typescript
Greetings
In parent i have this</p>
</blockquote>
<pre><code> const [coordinate,SetCoordinate]=useState("");
return (
<FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
<Stack spacing={3}>
<RHFTextField name="lat" label="Coord X" />
<RHFTextField name="lng" label="Coord Y" />
</Stack>
<Stack>
<br/>
<LocationMap childToParent={setCoordinate}/>
</Stack>
<Stack>
<LoadingButton
fullWidth
size="large"
type="submit"
variant="contained"
>
Save
</LoadingButton>
</Stack>
</FormProvider>
);
</code></pre>
<p>My Location map component is like this</p>
<pre><code>const render = (status: Status) => {
return <h1>{status}</h1>;
};
interface MapProps extends google.maps.MapOptions {
style: { [key: string]: string };
onClick?: (e: google.maps.MapMouseEvent) => void;
onIdle?: (map: google.maps.Map) => void;
}
//function to pass value to parent
interface LocationProps {
childToParent: (arg0: string)=>string;
}
export default function LocationMap({childToParent,...props}){
const [clicks, setClicks] = useState<google.maps.LatLng[]>([]);
const [zoom, setZoom] = useState(3); // initial zoom
const [center, setCenter] = useState<google.maps.LatLngLiteral>({
lat: 0.0,
lng: 0.0,
});
const [markerLocation, setMarkerLocation] = useState<google.maps.LatLng>();
const dragend = (e: google.maps.MapMouseEvent) => {
// avoid directly mutating state
setMarkerLocation(e.latLng!)
setClicks([...clicks, e.latLng!]);
};
const onClick = (e: google.maps.MapMouseEvent) => {
};
const onIdle = (m: google.maps.Map) => {
//.log("onIdle");
setZoom(m.getZoom()!);
setCenter(m.getCenter()!.toJSON());
};
const ref = useRef<HTMLDivElement>(null);
const [map, setMap] = useState<google.maps.Map>();
useEffect(() => {
if (ref.current && !map) {
setMap(new window.google.maps.Map(ref.current, {}));
}
}, [ref, map]);
return (
<>
<div style={{ display: "flex", height: "100%" }}>
<Wrapper apiKey={apiKey} render={render}>
<Map
center={center}
onClick={onClick}
onIdle={onIdle}
zoom={zoom}
style={{ flexGrow: "1", height: "25em", width: "400px" }}
>
<Marker key="point" draggable={true} dragend={dragend} />
</Map>
</Wrapper>
</div>
<div id="coordinate">
{clicks.map(function (latLng, i, row) {
var element = document.getElementById("coordenadas");
if (element === null) {
console.error("error cleaning coordinates");
} else {
element.innerHTML = "";
}
return (
childToParent(latLng.toJSON())
);
})
}
</div>
</>
)
};
interface MapProps extends google.maps.MapOptions {
onClick?: (e: google.maps.MapMouseEvent) => void;
onIdle?: (map: google.maps.Map) => void;
}
const Map: React.FC<MapProps> = ({
onClick,
onIdle,
children,
style,
...options
}) => {
const ref = useRef<HTMLDivElement>(null);
const [map, setMap] = useState<google.maps.Map>();
useEffect(() => {
if (ref.current && !map) {
setMap(new window.google.maps.Map(ref.current, {}));
}
}, [ref, map]);
// because React does not do deep comparisons, a custom hook is used
// see discussion in https://github.com/googlemaps/js-samples/issues/946
useDeepCompareEffectForMaps(() => {
if (map) {
map.setOptions(options);
}
}, [map, options]);
useEffect(() => {
if (map) {
["click", "idle"].forEach((eventName) =>
google.maps.event.clearListeners(map, eventName)
);
if (onClick) {
map.addListener("click", onClick);
}
if (onIdle) {
map.addListener("idle", () => onIdle(map));
}
}
}, [map, onClick, onIdle]);
return (
<>
<div ref={ref} style={style} />
{Children.map(children, (child) => {
if (isValidElement(child)) {
// set the map prop on the child component
return cloneElement(child, { map });
}
})}
</>
);
};
interface MarkerProps extends google.maps.MarkerOptions {
dragend?: (e: google.maps.MapMouseEvent) => void;
}
const Marker: React.FC<MarkerProps> = ({
dragend,
...options
}) => {
const [marker, setMarker] = useState<google.maps.Marker>();
console.log(options);
useEffect(() => {
if (!marker) {
setMarker(new google.maps.Marker({
position: {
lat: 0,
lng: 0,
},
}));
}
// remove marker from map on unmount
return () => {
if (marker) {
marker.setMap(null);
}
};
}, [marker]);
useEffect(() => {
if (marker) {
marker.setOptions(options);
}
}, [marker, options]);
useEffect(() => {
if (marker) {
["dragend"].forEach((eventName) =>
google.maps.event.clearListeners(marker, eventName)
);
marker.setOptions(options);
if (dragend) {
//map.addListener("click", onClick);
marker.addListener("dragend", dragend);
}
}
}, [marker, dragend, options]);
return null;
};
const deepCompareEqualsForMaps = createCustomEqual(
(deepEqual) => (a: any, b: any) => {
if (
isLatLngLiteral(a) ||
a instanceof google.maps.LatLng ||
isLatLngLiteral(b) ||
b instanceof google.maps.LatLng
) {
return new google.maps.LatLng(a).equals(new google.maps.LatLng(b));
}
// TODO extend to other types
// use fast-equals for other objects
return deepEqual(a, b);
}
);
function useDeepCompareMemoize(value: any) {
const ref = useRef();
if (!deepCompareEqualsForMaps(value, ref.current)) {
ref.current = value;
}
return ref.current;
}
function useDeepCompareEffectForMaps(
callback: React.EffectCallback,
dependencies: any[]
) {
useEffect(callback, dependencies.map(useDeepCompareMemoize));
}
export default LocationMap;
</code></pre>
| 3 | 3,438 |
How to close Modal in Reactjs?
|
<p>On button click i was trying to open a model (and modal opening too) and in a same modal it contain a button and on button click i was trying to open another model (and second modal opening too), but when second modal is opening i want first model to be closed. can it be possible?</p>
<p>Here is my sandbox demo <a href="https://codesandbox.io/embed/dreamy-herschel-cyetn?fontsize=14&hidenavigation=1&theme=dark" rel="nofollow noreferrer">https://codesandbox.io/embed/dreamy-herschel-cyetn?fontsize=14&hidenavigation=1&theme=dark</a></p>
<pre><code>const Practice = () => {
const [modalShow, setModalShow] = useState(false);
const handleSubmit = event => {
setModalShow(true);
};
return (
<div>
<Button onSubmit={handleSubmit} type="submit">
Submit
</Button>
<Modals show={modalShow} onhide={() => setModalShow(false)} />
</div>
);
};
</code></pre>
<p>here is my modal part</p>
<pre><code>const Modals = ({ show, onhide }) => {
const [modalShowsec, setModalShowsec] = useState(false);
const Validation = () => {
setModalShowsec(true);
};
return (
<div>
<Modal show={show} onHide={onhide} size="sm" aria-labelledby="contained-modal-title-vcenter" centered>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">HELLO</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Hi</p>
</Modal.Body>
</Modal>
<button onClick={Validation}> Validate </button>
<Modal show={modalShowsec} onHide={() => setModalShowsec(false)}>
<Modal.Header closeButton />
<Modal.Body>
<p>Hi cool</p>
</Modal.Body>
</Modal>
</div>
);
};
</code></pre>
| 3 | 1,057 |
SFSafariViewController : Overlay is not appearing sometimes
|
<p>I am using SFSafariViewController, and as i did not wanted to show the status bar of safari and i have hidden it by adding a overlay. I have my own button on the overlay and its working fine. The safari status bar is hidden and it shows my overlay but somehow sometimes the overlay disappears and the safari status bar is visible. I doubt that its because the link is being reloaded automatically but how? I am only calling it once. I am not sure why overlay is disappear for sometimes only. below is my code - </p>
<pre><code>self.navigationController?.presentViewController(sfController!, animated: true, completion: {
let bounds = UIScreen.mainScreen().bounds
let overlay = UIView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 65))
overlay.backgroundColor = UIColor(netHex: 0x275E37)
let completedBtn = UIButton()
let favBtn = UIButton()
let image = UIImage(named: "home.png") as UIImage?
let homeBtn = UIButton(type: UIButtonType.Custom) as UIButton
homeBtn.frame = CGRectMake(20, 25, 35, 35)
homeBtn.setImage(image, forState: .Normal)
homeBtn.addTarget(self, action: #selector(DetailsViewController.HomeBtnAction), forControlEvents:.TouchUpInside)
completedBtn.setTitle("Mark as Completed",forState: .Normal)
completedBtn.titleLabel!.font = UIFont(name: "FidelitySans-Regular", size: 20)
completedBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
completedBtn.frame = CGRectMake((bounds.size.width - 210), 25, 200, 35)
completedBtn.backgroundColor = UIColor(netHex: 0x6F9824)
completedBtn.addTarget(self, action: #selector(DetailsViewController.CompletedAction), forControlEvents: UIControlEvents.TouchUpInside)
favBtn.setTitle("Save as Favorite", forState: .Normal)
favBtn.titleLabel!.font = UIFont(name: "FidelitySans-Regular", size: 20)
favBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
favBtn.frame = CGRectMake((bounds.size.width - 420), 25, 200, 35)
favBtn.backgroundColor = UIColor(netHex: 0x6F9824)
favBtn.addTarget(self, action: #selector(DetailsViewController.FavoriteAction), forControlEvents: UIControlEvents.TouchUpInside)
overlay.addSubview(favBtn)
overlay.addSubview(completedBtn)
overlay.addSubview(homeBtn)
self.sfController!.view.addSubview(overlay)
})
</code></pre>
<p>Any help will be much appreciated as i am stuck in this issue from long time and cant fine solution. Thanks!</p>
| 3 | 1,051 |
Node.js promise and for loop. Wait for async function inside a loop
|
<p>I'm pretty new to Node and also to JS. I already read a lot here at stackoverflow and I think I personally have one in my brain for the last view days trying to fix this issue ;-).</p>
<p>The purpose of this code is to get the steam name for each player from steam API and put it into json object. after that the json object is using to present the steam data on a web page.</p>
<p>I got everithing working, but the first time the web page is loading it is empty. The second time which page is loading there are all data available.</p>
<p>The steam user ID is held in a simple array. This array is put to a forEach method and inside this method the steam API is called to return each player name. This player names are returned into the final json object, which held both, the steam id and the steam name.</p>
<pre><code>input = steam ID's from array
process = get steam name from steam ID
output = json object with all steam ID's and names.
</code></pre>
<p>Important thing is, that the page has to wait for the API calls to finish.</p>
<p>I have the following code:</p>
<pre class="lang-js prettyprint-override"><code>var cfg = require('config');
var Promise = require('bluebird');
//access steam API for steamId resolution
var Steam = require('steam-webapi');
// Set global Steam API Key
Steam.key = cfg.get('steam.api.key');
// Create a file called STEAM_KEY and stick your API key in it
// (or insert it here)
var steamAPIKey = Steam.key;
if (steamAPIKey.length === 0) {
try { steamAPIKey = fs.readFileSync('../STEAM_KEY').toString();}
catch(e) {
try { steamAPIKey = fs.readFileSync('./STEAM_KEY').toString(); }
catch(e) { console.log('No API key provided'); }
}
}
var steamconnect = function() {
return new Promise(function (resolve, reject) {
Steam.ready(steamAPIKey, function (err, data) {
if (err) return console.log(err);
else {
var steam = new Steam({key: steamAPIKey});
resolve(steam);
}
});
});
};
var getsteaminfoforeach = function(arrsid, steam){
return new Promise(function(resolve, reject){
dataarr = [];
var i = 0;
arrsid.forEach(function(entry, callback) {
if (entry !== "") {
getsteaminfo(steam, entry)
.then(function(playername) {
console.log(playername);
dataarr.push({"name": playername, "id": entry});
resolve(dataarr);
});
}
});
});
};
var getsteaminfo = function(steam, entry) {
return new Promise(function (resolve, reject) {
Promise.promisifyAll(Steam.prototype); // Creates an promise wielding function for every method (with Async attached at the end)
steam.getPlayerSummariesAsync({steamids: entry})
.then(function (data) {
playername = data.players[0]["personaname"]; //extract user name from steam user object
//dataarr.push({"name": playername, "id": entry});
console.log("get steam user: " + "name: "+playername+ " id: "+ entry);
resolve(playername);
});
});
};
var donext = function() {
return new Promise(function (resolve, reject) {
console.log("do next: "+dataarr);
});
};
arrsid = ["765611980504","765611970371",""];
steamconnect()
.then(function(steam){
console.log("arrsid: "+arrsid);
getsteaminfoforeach(arrsid, steam)
.then(function (dataarr) {
console.log("Player name: " + dataarr);
donext()
});
});
</code></pre>
<p>This is the output:</p>
<pre><code>arrsid: 765611980504,765611970371,
get steam user: name: steamname1 id: 765611980504
steamname1
Player name: [object Object]
do next: [object Object]
get steam user: name: steamname2 id: 765611970371
steamname2
</code></pre>
<p>My issue is, that steamname... should be the first output (for each steamname) and after that do next: [] has to be called.</p>
<p>I'm sure there is a simple solution. Thank you very much! </p>
| 3 | 1,617 |
Nginx Ingress on Kubernetes Cluster
|
<p>`I had a working Ingress controller version 1.0.0 (Bitnami). It stopped working one fine morning, and it appeared that the error was due to the version being depricated. Now I tried to upgrade this version, but started getting errors. I delete ingress and reinstalled it again, and this time from Bitnami repo which pulled the latest image. It is throwing errors. I created a new AKS cluster and installed ingress on it from the same repo, and it seems to work perfectly fine. Can somebody help me understand how this can be fixed please? I have over 120 services running on this cluster, and starting over would mean a lot of effort and time.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>E0419 10:57:29.245933 1 queue.go:130] "requeuing" err="\n-------------------------------------------------------------------------------\nError: exit status 1\n2022/04/19 10:57:29 [warn] 25#25: the \"http2_max_field_size\" directive is obsolete, use the \"large_client_header_buffers\" directive instead in /tmp/nginx-cfg2573211911:143\nnginx: [warn] the \"http2_max_field_size\" directive is obsolete, use the \"large_client_header_buffers\" directive instead in /tmp/nginx-cfg2573211911:143\n2022/04/19 10:57:29 [warn] 25#25: the \"http2_max_header_size\" directive is obsolete, use the \"large_client_header_buffers\" directive instead in /tmp/nginx-cfg2573211911:144\nnginx: [warn] the \"http2_max_header_size\" directive is obsolete, use the \"large_client_header_buffers\" directive instead in /tmp/nginx-cfg2573211911:144\n2022/04/19 10:57:29 [warn] 25#25: the \"http2_max_requests\" directive is obsolete, use the \"keepalive_requests\" directive instead in /tmp/nginx-cfg2573211911:145\nnginx: [warn] the \"http2_max_requests\" directive is obsolete, use the \"keepalive_requests\" directive instead in /tmp/nginx-cfg2573211911:145\n2022/04/19 10:57:29 [emerg] 25#25: \"location\" directive is not allowed here in /tmp/nginx-cfg2573211911:783\nnginx: [emerg] \"location\" directive is not allowed here in /tmp/nginx-cfg2573211911:783\nnginx: configuration file /tmp/nginx-cfg2573211911 test failed\n\n-------------------------------------------------------------------------------\n" key="initial-sync"
I0419 10:57:29.246021 1 event.go:282] Event(v1.ObjectReference{Kind:"Pod", Namespace:"nginx-ingress", Name:"nginx-nginx-ingress-controller-5575846679-bjwkp", UID:"9e5641ae-345c-4d3c-a840-83c143f07fd3", APIVersion:"v1", ResourceVersion:"5932936", FieldPath:""}): type: 'Warning' reason: 'RELOAD' Error reloading NGINX:
-------------------------------------------------------------------------------
Error: exit status 1
2022/04/19 10:57:29 [warn] 25#25: the "http2_max_field_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg2573211911:143
nginx: [warn] the "http2_max_field_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg2573211911:143
2022/04/19 10:57:29 [warn] 25#25: the "http2_max_header_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg2573211911:144
nginx: [warn] the "http2_max_header_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg2573211911:144
2022/04/19 10:57:29 [warn] 25#25: the "http2_max_requests" directive is obsolete, use the "keepalive_requests" directive instead in /tmp/nginx-cfg2573211911:145
nginx: [warn] the "http2_max_requests" directive is obsolete, use the "keepalive_requests" directive instead in /tmp/nginx-cfg2573211911:145
2022/04/19 10:57:29 [emerg] 25#25: "location" directive is not allowed here in /tmp/nginx-cfg2573211911:783
nginx: [emerg] "location" directive is not allowed here in /tmp/nginx-cfg2573211911:783
nginx: configuration file /tmp/nginx-cfg2573211911 test failed</code></pre>
</div>
</div>
</p>
| 3 | 1,318 |
VideoTexture Crashes iPad
|
<p>I'm running a video texture in Away3d in an Adobe Air app which runs fine on desktop and Android, however on iOS it crashes as soon as it tests for VideoTexture support</p>
<p>I create the video as such</p>
<pre><code> sphereGeometry = new SphereGeometry(5000, 64, 48);
panoTexture2DBase = new NativeVideoTexture(Model.config.getAssetUrl(Model.currentScene.video), true, true);
panoTexture2DBase.addEventListener(NativeVideoTexture.VIDEO_START,function(e:Event =null){setTimeout(onVideoStart,1000)});
panoTextureMaterial = new TextureMaterial(panoTexture2DBase, false, false, false);
panoVideoMesh = new Mesh(sphereGeometry, panoTextureMaterial);
panoVideoMesh.scaleX *= -1;
panoVideoMesh.rotate(Vector3D.Y_AXIS,-90);
scene.addChild(panoVideoMesh);
view.render();
panoTexture2DBase.player.pause();
</code></pre>
<p>And the iPad appears to crash as soon as it plays</p>
<pre><code> _player.play();
</code></pre>
<p>In NativeVideoClass</p>
<p>Does anyone know how to stop the iPad crashing when I try and use VideoTexture or is this doomed to failiure? </p>
<p>This is the Air 21. </p>
<p>I've tried taking the video out of Away3d and into Starling. I've changed the codecs and managed to get it running in Starling. </p>
<p>The same video is still crashing in Away3D tho. It's when it's gets added to the stage. </p>
<p>I'm also getting NetStream.Play.Failed in the netstats event before it fails.</p>
<p>The crash report </p>
<pre><code> Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x00000000000000d8
Triggered by Thread: 0
Filtered syslog:
None found
Global Trace Buffer (reverse chronological seconds):
63.498324 CFNetwork 0x0000000184c53a30 TCP Conn 0x12955be00 complete. fd: 10, err: 0
63.499758 CFNetwork 0x0000000184c54f5c TCP Conn 0x12955be00 event 1. err: 0
63.776992 CFNetwork 0x0000000184c55034 TCP Conn 0x12955be00 started
65.311738 CFNetwork 0x0000000184c53a30 TCP Conn 0x1275da440 complete. fd: 10, err: 0
65.312713 CFNetwork 0x0000000184c54f5c TCP Conn 0x1275da440 event 1. err: 0
65.561496 CFNetwork 0x0000000184c55034 TCP Conn 0x1275da440 started
65.824002 CFNetwork 0x0000000184c53a30 TCP Conn 0x1275d7370 complete. fd: 10, err: 0
65.825093 CFNetwork 0x0000000184c54f5c TCP Conn 0x1275d7370 event 1. err: 0
66.092512 CFNetwork 0x0000000184c55034 TCP Conn 0x1275d7370 started
66.434776 CFNetwork 0x0000000184bb1a18 TCP Conn 0x12756c8a0 SSL Handshake DONE
67.267381 CFNetwork 0x0000000184bb1928 TCP Conn 0x12756c8a0 starting SSL negotiation
67.268033 CFNetwork 0x0000000184c53a30 TCP Conn 0x12756c8a0 complete. fd: 10, err: 0
67.268518 CFNetwork 0x0000000184c54f5c TCP Conn 0x12756c8a0 event 1. err: 0
67.642271 CFNetwork 0x0000000184c55034 TCP Conn 0x12756c8a0 started
67.648583 CFNetwork 0x0000000184caa608 Creating default cookie storage with default identifier
67.648583 CFNetwork 0x0000000184caa5d4 Faulting in CFHTTPCookieStorage singleton
67.648583 CFNetwork 0x0000000184cfc394 Faulting in NSHTTPCookieStorage singleton
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 Video Test 0x000000010042d52c 0x1000b0000 + 3659052
1 Video Test 0x0000000100187688 0x1000b0000 + 882312
2 Video Test 0x0000000100182b94 0x1000b0000 + 863124
3 Video Test 0x0000000100182ab0 0x1000b0000 + 862896
4 Video Test 0x000000010042bfb4 0x1000b0000 + 3653556
5 Video Test 0x0000000100185ec0 0x1000b0000 + 876224
6 Video Test 0x00000001000c3f78 0x1000b0000 + 81784
7 UIKit 0x000000018aaaf014 0x18aa2c000 + 536596
8 UIKit 0x000000018ace9adc 0x18aa2c000 + 2874076
9 FrontBoardServices 0x000000018f0ecb68 0x18f0d4000 + 101224
10 Foundation 0x00000001863b6098 0x186300000 + 745624
11 BaseBoard 0x000000018c94f704 0x18c92c000 + 145156
12 FrontBoardServices 0x000000018f0e7bb8 0x18f0d4000 + 80824
13 FrontBoardServices 0x000000018f0ec940 0x18f0d4000 + 100672
14 UIKit 0x000000018aceaef4 0x18aa2c000 + 2879220
15 UIKit 0x000000018aceab9c 0x18aa2c000 + 2878364
16 FrontBoardServices 0x000000018f0fb7c4 0x18f0d4000 + 161732
17 FrontBoardServices 0x000000018f0fbb44 0x18f0d4000 + 162628
18 CoreFoundation 0x0000000185468544 0x18538c000 + 902468
19 CoreFoundation 0x0000000185467fd8 0x18538c000 + 901080
20 CoreFoundation 0x0000000185465cd8 0x18538c000 + 892120
21 CoreFoundation 0x0000000185394ca0 0x18538c000 + 36000
22 GraphicsServices 0x00000001903fc088 0x1903f0000 + 49288
23 UIKit 0x000000018aaacffc 0x18aa2c000 + 528380
24 Video Test 0x00000001001a02e8 0x1000b0000 + 983784
25 libdyld.dylib 0x000000019a8428b8 0x19a840000 + 10424
</code></pre>
| 3 | 2,770 |
Html in Python communicating with JavaScript in Python
|
<p>I have an html form that places text field data into a Javascript array. The code is shown here:<a href="http://jsbin.com/maniwu/3/edit?html,js,output" rel="nofollow noreferrer">http://jsbin.com/maniwu/3/edit?html,js,output</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var message = [];
var receiverInput = document.getElementById("Receiver");
var classificationInput = document.getElementById("Classification");
var titleInput = document.getElementById("Title");
var senderInput = document.getElementById("Sender");
var dateInput = document.getElementById("Date");
var messageBox = document.getElementById("display");
function insert() {
message.push(receiverInput.value);
message.push(classificationInput.value);
message.push(titleInput.value);
message.push(senderInput.value);
message.push(dateInput.value);
clearAndShow();
}
function clearAndShow() {
// Clear our fields
receiverInput.value = "";
classificationInput.value = "";
titleInput.value = "";
senderInput.value = "";
dateInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "Sent Header " + message + "<br/>";
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<form>
<input id="Receiver" type="text" placeholder="Receiver" />
<input id="Classification" type="text" placeholder="Classification" />
<input id="Title" type="text" placeholder="Title" />
<input id="Sender" type="text" placeholder="Sender" />
<input id="Date" type="text" placeholder="Date" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
</html></code></pre>
</div>
</div>
But I want each embedded in Python 2.7 (windows, IDE: spyder) as shown below. How do I get them to communicate?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import js2py
js = ""
"
function classCollection() {
var message = [];
var receiverInput = document.getElementById("Receiver");
var classificationInput = document.getElementById("Classification");
var titleInput = document.getElementById("Title");
var senderInput = document.getElementById("Sender");
var dateInput = document.getElementById("Date");
var messageBox = document.getElementById("display");
function insert() {
message.push(receiverInput.value);
message.push(classificationInput.value);
message.push(titleInput.value);
message.push(senderInput.value);
message.push(dateInput.value);
clearAndShow();
}
function clearAndShow() {
receiverInput.value = "";
classificationInput.value = "";
titleInput.value = "";
senderInput.value = "";
dateInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Sent Header " + message + "<br/>";
}
document.write(message)
}
classCollection()
""
".replace("
document.write ", "
return ")
result = js2py.eval_js(js)
print result</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>import webbrowser f = open('classInformation.html','w') records = """
<html>
<body>
<form>
<input id="Receiver" type="text" placeholder="Receiver" />
<input id="Classification" type="text" placeholder="Classification" />
<input id="Title" type="text" placeholder="Title" />
<input id="Sender" type="text" placeholder="Sender" />
<input id="Date" type="text" placeholder="Date" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
</html>""" f.write(records) f.close() webbrowser.open_new_tab('classInformation.html')</code></pre>
</div>
</div>
</p>
| 3 | 1,472 |
How to Avoid very long time python calculations while iterating through pandas dataframe
|
<p>I am trying to add 2 columns to dataframe to calculate vehicle surroundings neighbor 50 and neighbor 100 for each vehicle in each direction and in each time frame based on distance, if distance below 50 I add one count to the neighbor 50 and so on, I should do this task using Pandas only</p>
<p>I should calculate distance based on x and y position of each vehicle through the equation:</p>
<p>distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5</p>
<p>I have used this code:</p>
<pre><code>#import numpy as np
df['neighbor_50'] = 0
df['neighbor_100'] = 0
frame_group = df.groupby(['frame','direction'])
list_keys = list(frame_group.indices.keys())
for key in list_keys :
frame , direction = key[0] , key[1]
#new_df = df.loc[(df['frame'] == frame) & (df['direction'] == direction)]
mask1 = (df['frame'] == frame) & (df['direction'] == direction)
ids = df[mask1]['id']
for i in ids:
for j in ids:
if i != j:
#distance = sqrt((x2-x1)**2 + (y2-y1)**2)
maski = (df['frame'] == frame) & (df['direction'] == direction)& (df['id'] == i)
maskj = (df['frame'] == frame) & (df['direction'] == direction)& (df['id'] == j)
x2 = df[maski]['x'].iloc[0]
x1 = df[maskj]['x'].iloc[0]
y2 = df[maski]['y'].iloc[0]
y1 = df[maskj]['y'].iloc[0]
distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5
#distance = np.hypot((x2 - x1),(y2 - y1))
mask = (df['frame'] == frame) & (df['direction'] == direction) &( df['id']== i)
if distance <= 50:
df.loc[mask , 'neighbor_50'] += 1
if distance <= 100 :
df.loc[mask ,'neighbor_100'] += 1
</code></pre>
<p>the problem is that it takes forever to complete because the data is big even when i use NumPy.</p>
<p>input sample
<a href="https://i.stack.imgur.com/bYF7m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bYF7m.png" alt="input sample" /></a></p>
<p>output sample
<a href="https://i.stack.imgur.com/7tmKP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7tmKP.png" alt="enter image description here" /></a></p>
<p>update:
I have managed to reduce the time by half by avoiding repeating calculations for same ids , but still so slow</p>
<pre><code>import numpy as np
df['neighbor_50'] = 0
df['neighbor_100'] = 0
frame_group = df.groupby(['frame','direction'])
list_keys = list(frame_group.indices.keys())
for key in list_keys :
frame , direction = key[0] , key[1]
#new_df = df.loc[(df['frame'] == frame) & (df['direction'] == direction)]
mask = (df['frame'] == frame) & (df['direction'] == direction)
ids = df[mask]['id'].values
for i in range(len(ids)-1):
id1 = ids[i]
for j in range(i+1,len(ids)):
id2 = ids[j]
maski = (df['frame'] == frame) & (df['direction'] == direction)& (df['id'] == id1)
maskj = (df['frame'] == frame) & (df['direction'] == direction)& (df['id'] == id2)
x2 = df[maski]['x'].iloc[0]
x1 = df[maskj]['x'].iloc[0]
y2 = df[maski]['y'].iloc[0]
y1 = df[maskj]['y'].iloc[0]
#distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5
distance = np.hypot((x2 - x1),(y2 - y1))
if distance <= 100 :
df.loc[maski ,'neighbor_100'] += 1
df.loc[maskj ,'neighbor_100'] += 1
if distance <= 50:
df.loc[maski , 'neighbor_50'] += 1
df.loc[maskj , 'neighbor_50'] += 1
</code></pre>
| 3 | 1,862 |
Project.exe has triggered a breakpoint (C)
|
<p>I'm a beginner programmer, I got a home assignment to seperate a string into words, and put each word in an array of strings. We are practicing dynamic memory allocations. the assignment says that the size of the array must be [10] and i need to change the size of the array with malloc accoring to the number of words in the string, and allocate room for every word in the array. when i reach the end of the programm and free the allocated memory it says "Project.exe has triggered a breakpoint" and i can't find my mistake in the code.</p>
<p>P.S this is my first question on stack so i apologize in advance if I posted wrong somehow.</p>
<pre><code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fillArray(char string[], char* array[], int* pointer);
int countCharacters(char string[], int index, int* pointer);
void freeArray(char* arr[], int size);
void main()
{
char string[] = { "i have two dreams" };
printf("Your sentence is: %s", string);
int sentenceLength = 1;
for (int i = 0; string[i] != '\0'; i++)
{
if (string[i] == ' ') sentenceLength++;
}
int* point = &sentenceLength;
char* array[10];
fillArray(string, array, point);
printf("\n\nYour array is: \n");
for (int i = 0; i < *point; i++) puts(array[i]);
freeArray(array, *point);
}
void fillArray(char string[], char* array[], int* pointer)
{
*array = (char*)malloc(*pointer * sizeof(char));
if (array == NULL)
{
printf("--NO MEMORY--");
exit(1);
}
int i = 0;
int j = 0;
for (i; i < *pointer; i++)
{
array[i] = (char*)malloc(sizeof(char) * countCharacters(string, j, pointer));
if (array[i] == NULL)
{
printf("--NO MEMORY--");
exit(1);
}
for (j; string[j] != ' '; j++)
{
if (string[j] == '\0')
{
array[i][j] = '\0';
return;
}
array[i][j] = string[j];
}
if (string[j] == ' ' || string[j] == '\0')
{
array[i][j] = '\0';
j++;
}
}
}
int countCharacters(char string[], int index, int* pointer)
{
int size = 1;
if (string[index] == ' '&& index<= *pointer) index++;
for (index; string[index] !=' '&& string[index]!='\0'; index++)
{
size++;
}
return size;
}
void freeArray(char* arr[], int size)
{
for (int i = 0; i < size; i++)
{
free(arr[i]);
arr[i] = NULL;
}
}
</code></pre>
| 3 | 1,188 |
Post Rocket route is forwarded (Rust)
|
<p>Sorry to ask such a basic question, there's little info about this in Stack Overflow and GitHub. This must be something silly, but I'm not getting it.</p>
<p>I'm trying to send via JavaScript's <code>fetch</code> to a Rust post endpoint with Rocket 0.5 RC1. But I'm getting hit by:</p>
<blockquote>
<p>No matching routes for POST /api/favorites application/json.</p>
</blockquote>
<p>Here's the complete log:</p>
<pre><code> POST /api/favorites application/json:
Matched: (post_favorites) POST /api/favorites
`Form < FavoriteInput >` data guard is forwarding.
Outcome: Forward
No matching routes for POST /api/favorites application/json.
No 404 catcher registered. Using Rocket default.
Response succeeded.
</code></pre>
<p>Here's my main.rs file (Irrelevant parts omitted):</p>
<pre class="lang-rust prettyprint-override"><code>#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
let cors = CorsOptions::default()
.allowed_origins(AllowedOrigins::all())
.allowed_methods(
vec![Method::Get, Method::Post, Method::Patch]
.into_iter()
.map(From::from)
.collect(),
)
.allow_credentials(true)
.to_cors()?;
rocket::build()
.mount("/api", routes![index, upload::upload, post_favorites])
.attach(cors)
.launch()
.await?;
Ok(())
}
#[post("/favorites", data = "<input>")]
async fn post_favorites(input: Form<FavoriteInput>) -> Json<Favorite> {
let doc = input.into_inner();
let fav = Favorite::new(doc.token_id, doc.name);
let collection = db().await.unwrap().collection::<Favorite>("favorites");
collection.insert_one(&fav, None).await.unwrap();
Json(fav)
}
</code></pre>
<p>Here's my cargo.toml:</p>
<pre><code>
[dependencies]
rocket = {version ="0.5.0-rc.1", features=["json"]}
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
reqwest = {version = "0.11.6", features = ["json"] }
serde= {version = "1.0.117", features= ["derive"]}
mongodb = "2.1.0"
rand = "0.8.4"
uuid = {version = "0.8", features = ["serde", "v4"] }
</code></pre>
<p>Here are my structs:</p>
<pre class="lang-rust prettyprint-override"><code>#[path = "./paste.rs"]
mod paste;
#[derive(Serialize, Deserialize, Debug)]
pub struct Favorite {
pub id: String,
pub token_id: String,
pub name: String,
}
impl Favorite {
pub fn new(token_id: String, name: String) -> Favorite {
let id = Uuid::new_v4().to_string();
let fav = Favorite { token_id, name, id };
fav
}
}
#[derive(FromForm, Serialize, Deserialize, Debug)]
pub struct FavoriteInput {
pub token_id: String,
pub name: String,
}
</code></pre>
<p>Here's the token payload:</p>
<p><a href="https://i.stack.imgur.com/bbne0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bbne0.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/MmKlk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MmKlk.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/BGnW9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BGnW9.png" alt="enter image description here" /></a></p>
<p>I've tried with parameter-less get requests and they were successful.</p>
<p>I thought the <code>Form</code> struct was reading and correctly parsing the <code>FavoriteInput</code> as it allows for missing/extra fields.</p>
<p>There must be something silly that I'm doing wrong. Any ideas?</p>
| 3 | 1,576 |
Apply CSS to ul class then li then a
|
<p>I want to change the color of my footer items using CSS. I want to change the color of all <code>a</code> items as I have given same classes but do not know how to apply CSS.
Here is the code:</p>
<pre><code> <div class="col-lg-3 col-md-6 footer-links">
<h4>Our products</h4>
<ul class="footer-items">
<li><a href="#">About trade banner printing</a></li>
<li><a href="#">Delivery options</a></li>
<li><a href="#">Frequently added questions</a></li>
<li><a href="#">What our customer think of us</a></li>
<li><a href="#">Register for trade access</a></li>
<li><a href="#">Contact us</a></li>
</ul>
</div>
<div class="col-lg-3 col-md-6 footer-links">
<h4>Promo and Details</h4>
<ul class="footer-items">
<li><a href="#">About trade banner printing</a></li>
<li><a href="#">Delivery options</a></li>
<li><a href="#">Frequently added questions</a></li>
<li><a href="#">What our customer think of us</a></li>
<li><a href="#">Register for trade access</a></li>
<li><a href="#">Contact us</a></li>
</ul>
</div>
<div class="col-lg-3 col-md-6 footer-links">
<h4>About Our Services</h4>
<ul class="footer-items">
<li><a href="#">About trader banner printing</a></li>
<li><a href="#">Delivery options</a></li>
<li><a href="#">Frequently added questions</a></li>
<li><a href="#">What our customer think of us</a></li>
<li><a href="#">Register for trade access</a></li>
<li><a href="#">Contact us</a></li>
</ul>
</div>
</code></pre>
| 3 | 1,436 |
React Bootstrap button not recognising function onClick
|
<p>I have a React Bootstrap app with onclick Buttons. The first 2 buttons, play and pause work. The next buttons however do not even show in the react console as having an attached function prop.</p>
<p>All buttons link to functions within the same scope and they are all near identical.</p>
<p>I've tried changing the onClick calls and reducing the unrecognised functions to <code>console.log</code>s in case it was a function breaking them.</p>
<pre><code>class Buttons extends React.Component{
handleSelect =(e) => {
this.props.gridSize(e);
}
render(){
return(
<div className="buttonsDiv">
<ButtonToolbar>
<button className="btn" onClick={this.props.playButton}>Play</button>
<button className="btn" onClick={this.props.pauseButton}>Pause</button>
<button className="btn" onClick={this.props.clear}>Clear</button>
<button className="btn" onClick={this.props.fast}>Fast</button>
<button className="btn" onClick={this.props.slow}>Slow</button>
<button className="btn" onClick={this.props.seed}>Seed</button>
<DropdownButton
title="Grid Size"
id="size-menu"
onSelect={this.handleSelect} >
<Dropdown.Item eventKey="1">20x10</Dropdown.Item>
<Dropdown.Item eventKey="2">50x30</Dropdown.Item>
<Dropdown.Item eventKey="3">70x50</Dropdown.Item>
</DropdownButton>
</ButtonToolbar>
</div>
)
}
}
class Main extends React.Component {
constructor() {
super();
this.speed = 1100;
this.rows = 30;
this.cols = 50;
this.state = {
generation: 0,
gridFull: Array(this.rows)
.fill()
.map(() => Array(this.cols).fill(false)) //make array of Rows and foreach row make an array of all the columns - making a grid.
};
}
selectBox = (row, col) =>{
this.setState((previousState)=>{
let {gridFull} = previousState;
gridFull[row][col] = !gridFull[row][col]
return {gridFull: gridFull }
});
}
seed = () => {
this.setState((prevState)=> {
let {gridFull} = prevState;
for (let i=0; i<this.rows; i++){
for (let j=0; j< this.cols; j++){
if(Math.floor(Math.random() * 4) === 1){
gridFull[i][j] = true;
}
}
}
return {gridFull:gridFull}
});
}
playButton =() => {
clearInterval(this.intervalId)
this.intervalId = setInterval(this.play, this.speed);
}
pauseButton =() => {
clearInterval(this.intervalId);
}
slow =() => {
console.log('hi')
// this.speed=100;
// this.playButton();
}
fast = () => {
console.log(this.speed)
this.speed =1000;
this.playButton();
}
clear = () => {
var grid = Array(this.rows).fill().map(() =>
Array(this.cols).fill(false));
this.setState({
gridFull: grid,
generation : 0
});
}
play = () => {
code
}
componentDidMount(){
this.playButton();
this.seed();
}
render() {
return (
<div>
<h1>React Application</h1>
<Buttons playButton ={this.playButton}
pauseButton={this.pauseButton}
/>
<Grid
gridFull={this.state.gridFull}
rows={this.rows}
selectBox={this.selectBox}
cols={this.cols}
/>
<h2>Generations: {this.state.generation}</h2>
</div>
);
}
}
</code></pre>
<p>So in the buttons toolbar the first 2 buttons work and the rest do not even show functions as props in the react console.</p>
<p>As you can see they both call functions within the same scope, so I don't know what's happening.</p>
| 3 | 1,765 |
Bug with react-accessible-accordion
|
<p>Im using the following npm librarie : </p>
<pre><code>"react-accessible-accordion": "2.3.1",
</code></pre>
<p>it is returning an error to me : </p>
<pre><code>ReferenceError: babelHelpers is not defined
(anonymous function)
C:/Users/tabm005/www/node_modules/react-accessible-accordion/dist/umd/index.js:1037
1034 |
1035 | var createReactContext = unwrapExports(lib);
1036 |
> 1037 | var _typeof = typeof Symbol === "function" && babelHelpers.typeof(Symbol.iterator) === "symbol" ? function (obj) {
1038 | return typeof obj === 'undefined' ? 'undefined' : babelHelpers.typeof(obj);
1039 | } : function (obj) {
1040 | return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : babelHelpers.typeof(obj);
View compiled
./node_modules/react-accessible-accordion/dist/umd/index.js.React__default
http://localhost:3000/static/js/bundle.js:121672:10
121669 | /***/ (function(module, exports, __webpack_require__) {
121670 |
121671 | (function (global, factory) {
> 121672 | true ? factory(exports, __webpack_require__(/*! react */ "./node_modules/react/index.js")) :
| ^ 121673 | typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
121674 | (factory((global.reactAccessibleAccordion = {}),global.React));
121675 | }(this, (function (exports,React) { 'use strict';
View source
./node_modules/react-accessible-accordion/dist/umd/index.js
C:/Users/tabm005/www/node_modules/react-accessible-accordion/dist/umd/index.js:5
2 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3 | typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4 | (factory((global.reactAccessibleAccordion = {}),global.React));
> 5 | }(this, (function (exports,React) { 'use strict';
6 |
7 | var React__default = 'default' in React ? React['default'] : React;
8 |
View compiled
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/Summary/summaryAccordion.js
http://localhost:3000/static/js/bundle.js:198742:85
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/stepsFormsContainer/stepsFormsContainer.js
http://localhost:3000/static/js/bundle.js:206311:84
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/stepsFormsContainer/index.js
C:/Users/tabm005/www/src/components/stepsFormsContainer/index.js:1
> 1 | import StepsFormsContainer from './stepsFormsContainer';
2 |
3 | export default StepsFormsContainer;
4 |
View compiled
▶ 5 stack frames were collapsed.
./src/components/stepperManager/index.js
C:/Users/tabm005/www/src/components/stepperManager/index.js:1
> 1 | import StepperManager from './stepperManager';
2 |
3 | export default StepperManager;
4 |
View compiled
▶ 12 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.
</code></pre>
<p>I tried several manipulations : remove my node_modules and package-lock.json and re-install the application. I tried a newer version of accordion too and no solution worked for me.</p>
<p>Any Idea ?</p>
| 3 | 2,851 |
BrowserSync refreshing before injection (Gulp)
|
<p>I have my gulpfile:</p>
<pre><code>var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var sourcemaps = require('gulp-sourcemaps');
var fileinclude = require('gulp-file-include');
var browserify = require('browserify');
var rename = require('gulp-rename');
var streamify = require('gulp-streamify'); // required for uglify
var uglify = require('gulp-uglify'); // minify JS
var source = require('vinyl-source-stream'); // required to dest() for browserify
var browserSync = require('browser-sync').create();
var localSettings = require('./gulp/localConfig.js');
gulp.task('sass', function () {
return gulp.src('./assets/sass/main.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError)) // .on('error', sass.logError) prevents gulp from crashing when saving a typo or syntax error
.pipe(sourcemaps.write())
.pipe(gulp.dest('./assets/sass'))
.pipe(browserSync.stream()); // causes injection of styles on save
});
gulp.task('compileHTML', function() {
return gulp.src(['static/src/*.html'])
.pipe(fileinclude({
prefix: '@@',
basepath: '@root'
}))
.pipe(gulp.dest('./static/compiled'))
.pipe(browserSync.stream()); // causes injection of html changes on save
});
// Static Server for browsersync
gulp.task('sync', ['sass'], function() {
browserSync.init({
startPath: "static/compiled/index.html",
open: localSettings.openBrowserSyncServerOnBuild,
server: {
baseDir: "./",
}
});
});
gulp.task('watch', function() {
gulp.watch('./assets/sass/**/*.scss', ['sass']);
gulp.watch(['./static/src/**/*.html', '!partials', '!components'], ['compileHTML']);
gulp.watch('./assets/js/**/*.js', ['javascript']);
});
gulp.task('javascript', function() {
var bundleStream = browserify('./assets/js/main.js').bundle();
bundleStream
.pipe(source('main.js'))
.pipe(rename('bundle.js'))
.pipe(gulp.dest('./assets/js/'))
.pipe(browserSync.stream());
})
// Default Task
gulp.task('default', ['compileHTML', 'javascript', 'sass', 'watch', 'sync']);
</code></pre>
<p>Mostly everything with my build works great, however I am having one issue with my compileHTML task. When any modifications are made to my html, it is compiled and injected into the page with BrowserSync. The problem is that BrowserSync is injecting the markup into the page AFTER it reloads, so that I have to manually refresh or save the file again.</p>
<p>Although I am doing the exact same thing with my SASS task, I have no problems with that task. Why do my styles inject into the page before the reload, but the HTML does not?</p>
<p>Just for testing, I tried adding a setTimout surrounding the BrowserSync injection, but it did not affect the timing of the injection other than adding a delay.</p>
| 3 | 1,038 |
Need to access and edit an attribute in a database
|
<p>Orders are created and saved in this method</p>
<pre><code>public async Task<ActionResult> FirstClassCreate(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
var customer = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
var cart = ShoppingCart.GetCart(this.HttpContext);
try
{
order.DeliveryDate = DateTime.Now.AddDays(1);
order.DeliveryMethod = "First Class";
order.FirstName = customer.FirstName;
order.LastName = customer.LastName;
order.PostalCode = customer.PostalCode;
order.State = customer.State;
order.City = customer.City;
order.Email = customer.Email;
order.Country = customer.Country;
order.Phone = customer.PhoneNumber;
order.Address = customer.Address;
order.HasPaid = false;
order.Username = customer.Email;
order.OrderDate = DateTime.Now;
var currentUserId = User.Identity.GetUserId();
order.Total = cart.GetFirstClass();
if (order.SaveInfo && !order.Username.Equals("guest@guest.com"))
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var ctx = store.Context;
var currentUser = manager.FindById(User.Identity.GetUserId());
//Save this back
//http://stackoverflow.com/questions/20444022/updating-user-data-asp-net-identity
//var result = await UserManager.UpdateAsync(currentUser);
await ctx.SaveChangesAsync();
await storeDB.SaveChangesAsync();
}
//Save Order
storeDB.Orders.Add(order);
await storeDB.SaveChangesAsync();
//Process the order
cart = ShoppingCart.GetCart(this.HttpContext);
order.Total = cart.GetFirstClass();
order = cart.CreateOrder(order);
return RedirectToAction("FirstClass", "Checkouts", order);
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
</code></pre>
<p>I need to be access the orders database and change attributes of a specific order, using the email as the Unique Identifier and search for the newest (find the newest using the Order Date where <code>'haspaid' = false</code>).</p>
<pre><code> using ()//Insert database context here)
{
//Search for order in the database, try using the email as the Unique Identifire and search for the newest where haspaid = false
//Change the haspaid attribute to true
var orders = from o in db.Orders
where o.Email == User.Identity.Name, o.HasPaid = false, //Newest
select o;
order.HasPaid = true;
db.Orders.SaveChanges();
//save database changes
}
</code></pre>
| 3 | 1,430 |
Why does Play port not get started with library subproject?
|
<p>In <code>build.sbt</code> I have the lines like:</p>
<pre><code>lazy val sparkCommon = (project in file("spark-common"))//.enablePlugins(PlayScala)
lazy val root = (project in file(".")).enablePlugins(PlayScala)
.dependsOn(sparkCommon).aggregate(sparkCommon)
</code></pre>
<p>In <code>spark-common</code> project I have code in <code>src/main/scala/SimpleApp.scala</code>:</p>
<pre><code> object SimpleApp {
def getStr = "{ name = 'adf'}"
}
</code></pre>
<p>In my Spark project <code>root</code> I am trying to use that code.</p>
<p>With the <code>build.sbt</code> file above port listening is not started and I cannot access my service (but it compiles projects successfully, can make both packages and publish them to repo).</p>
<p>If I uncomment line <code>enablePlugins(PlayScala)</code> for my library <code>spark-common</code> project in the <code>build.sbt</code> file, it does not see <code>SimpleApp</code> (as I understand Play projects have a bit different structure, thus compilation error is reasonable, as code located under <code>/spark-common/src/main/scala/SimleApp.scala</code>).</p>
<p>It seems that I follow <a href="https://groups.google.com/forum/#!searchin/play-framework/2.3$20playscala$20/play-framework/lnEcyiPewn0/z49BVJD1Z60J" rel="nofollow">guideline </a> (I use Play 2.3.4), but it does not work. What can be an issue?</p>
<p>activator run / sbt run command result:</p>
<pre><code>[info] Done updating.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/tkacheni/.ivy2/cache/org.slf4j/slf4j-log4j12/jars/slf4j-log4j12-1.7.5.jar!/o
rg/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/tkacheni/.ivy2/cache/ch.qos.logback/logback-classic/jars/logback-classic-1.1
.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
--- (Running the application from SBT, auto-reloading is enabled) ---
log4j:WARN No appenders could be found for logger (org.jboss.netty.channel.socket.nio.SelectorUtil).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
(Server started, use Ctrl+D to stop and go back to the console...)
</code></pre>
<p>Projects command results:</p>
<pre><code>[rest-service] $ projects
[info] In file:/C:/Git/rest-service/
[info] * root
[info] sparkCommon
[rest-service] $
</code></pre>
<p>If I run last run I can see such an error:</p>
<pre><code>java.lang.RuntimeException: No main class detected.
at scala.sys.package$.error(package.scala:27)
...
</code></pre>
<p>I have found a similar issue in <a href="https://groups.google.com/forum/#!searchin/play-framework/2.3$20playscala$20/play-framework/lnEcyiPewn0/z49BVJD1Z60J" rel="nofollow">Google groups</a>, but it doesn't help me</p>
| 3 | 1,138 |
dynamic css circle navigation
|
<p>This question is a follow-up question (not sure if thats allowed) on something I asked earlier -> <a href="https://stackoverflow.com/questions/34307941/dynamic-css-circle-inside-div">dynamic css circle inside div</a></p>
<p>The solution to that thread turned out not be what I wanted to achieve since I need the divs adjacent to the centered circle to be independent of it in order not to be affected by styles such as opacity i want to apply to the circle.</p>
<p>What I want to create is a page in which I have a fixed header and footer and a circle in the content area that dynamically changes size depending on the space available - i dont want to user to scroll.</p>
<p>Abovementioned circle has a div (the navigational part) on either side that will also change size. </p>
<p>The code that I have so far seems to work as expected when the x-axis of the wrapper is bigger than the y-axis (width > height) but for some reason when the height of the wrapper is bigger than width, it gets all distorted.</p>
<p><a href="https://jsfiddle.net/h1xfqwh6/" rel="nofollow noreferrer">https://jsfiddle.net/h1xfqwh6/</a></p>
<p>looking at in in fiddle it actually looks half decent - besides the hidious colors - which are a feature... but if i look at in the firefox responsive design developer mode the circle takes always more space than it should when the wrapper containers height is larger than its width - </p>
<p><a href="https://i.stack.imgur.com/vTH7L.png" rel="nofollow noreferrer">oversized circle</a></p>
<p>html</p>
<pre><code> <div class="wrapper">
<div id="left"><i class="fa fa-arrow-left"></i></div>
<div id="circle">
<p> Make me into a real circle </p>
</div>
<div id="right"><i class="fa fa-arrow-right"></i></div>
</div>
</code></pre>
<p>css</p>
<pre><code> .wrapper {
top: 4em;
bottom: 4em;
left: 50%;
margin-right: -50%;
transform: translate(-50%);
position: absolute;
max-height: 100%;
background-color: blue;
margin: 0 auto;
padding-top: 1em;
padding-bottom: 1em;
}
#left{
background:#00ffff;
height: 100%;
border: 1px black solid;
display: inline-block;
}
#right{
background:#00ff03;
display: inline-block;
height: 100%;
float: right;
text-align: right;
border: 1px black solid;
}
#circle {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: inline-block;
min-width: 5em;
height: 100%;
border-radius: 50%;
width: 50%;
background-color: green;
background-image: url('http://i.stack.imgur.com/MlIL8.png');
background-repeat: no-repeat;
background-size: 100%;
border: black 2px solid;
}
</code></pre>
<p>jquery</p>
<pre><code>function f()
{
if($('.wrapper').height() > $('.wrapper').width())
{
$('#circle').height($('.wrapper').width() - $('#left').width() - $('#right').width());
$('#circle').width($ ('.wrapper').height() - $('#left').width() - $('#right').width());
$('.wrapper').width($('#circle').width() + $('#left').width() + $('#right').width());
}
else if( $('.wrapper').width() > $('.wrapper').height() )
{
$('.wrapper').width($('#circle').width() + $('#left').width() + $('#right').width());
$('#circle').width($('.wrapper').height() );
$('#circle').height($('.wrapper').height() );
}
$('#circle').height($('#circle').width());
}
f();
$(window).on('resize', function() {
f();
});
</code></pre>
| 3 | 1,259 |
Display an error if a latitude or longitude has improper formatting
|
<p>My WPF application has a dialog where the user can enter a latitude & a longitude. I have written an <code>IValueConverter</code> which can handle values entered as decimal degrees or in degree-minute-second format:</p>
<pre><code>[ValueConversion( typeof( double? ), typeof( string ) )]
public class CoordinateConverter : IValueConverter {
#region IValueConverter Members
public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
double angle = 0.0;
if ( value is string ) {
if ( !double.TryParse( value as string, NumberStyles.Float, CultureInfo.InvariantCulture, out angle ) ) {
return value;
}
} else if ( value is double || value is double? ) {
angle = (double) value;
} else {
return value.ToString();
}
bool isNegative = angle < 0;
if ( isNegative ) angle = -angle;
double degrees = Math.Truncate( angle );
double remainder = ( angle - degrees ) * 60.0;
double minutes = Math.Truncate( remainder );
double seconds = ( remainder - minutes ) * 60.0;
string result = degrees.ToString( "##0", culture.NumberFormat ) + "° " +
minutes.ToString( "#0", culture.NumberFormat ) + "' " +
seconds.ToString( "#0.00", culture.NumberFormat ) + "\" ";
// The parameter contains "NS" for Latitudes and "EW" for Longitudes.
if ( parameter != null ) {
result += ( (string) parameter ).Substring( ( isNegative ? 1 : 0 ), 1 );
} else {
result = ( isNegative ? "-" : string.Empty ) + result;
}
return result;
}
public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
string strValue = value as string;
if ( string.IsNullOrEmpty( strValue ) ) {
return null;
}
double adjustForSign = 1.0;
if ( strValue.IndexOf( "-" ) >= 0 ) {
adjustForSign = -1.0;
strValue = strValue.Substring( strValue.IndexOf( "-" ) + 1 );
}
// Parse the value in the field. It's in three parts: Degrees, minutes & seconds
int degreeSymbol = strValue.IndexOf( "°" );
int minuteSymbol = strValue.IndexOf( "'" );
int secondSymbol = strValue.IndexOf( '"' );
string degrees = null, minutes = null, seconds = null;
double angle, d, m, s;
if ( degreeSymbol < 0 ) {
if ( double.TryParse( strValue, NumberStyles.Number, culture.NumberFormat, out angle ) ) {
return angle;
} else {
return value;
}
} else {
degrees = strValue.Substring( 0, degreeSymbol );
if ( minuteSymbol >= 0 ) {
minutes = strValue.Substring( degreeSymbol + 2, minuteSymbol - degreeSymbol - 2 );
}
if ( secondSymbol < 0 ) {
seconds = "0" + culture.NumberFormat.NumberDecimalSeparator + "0";
} else {
seconds = strValue.Substring( minuteSymbol + 2, secondSymbol - minuteSymbol - 2 );
}
}
if ( !double.TryParse( degrees, NumberStyles.Integer, culture.NumberFormat, out d ) ) return value;
if ( !double.TryParse( minutes, NumberStyles.Integer, culture.NumberFormat, out m ) ) return value;
if ( !double.TryParse( seconds, NumberStyles.Float , culture.NumberFormat, out s ) ) return value;
angle = d + m / 60.0 + s / 3600.0;
if ( parameter != null ) {
if ( strValue.Contains( ( (string) parameter ).Substring( 1, 1 ) ) ) {
angle = -angle;
}
} else {
angle *= adjustForSign;
}
return angle;
}
</code></pre>
<p>In the dialog, I'm using this <code>ControlTemplate</code> to display errors:</p>
<pre><code><ControlTemplate x:Key="InputErrorTemplate">
<DockPanel LastChildFill="True">
<Image DockPanel.Dock="Right"
Height="20"
Margin="-30,0,0,0"
Source="{StaticResource ErrorImage}"
ToolTip="{x:Static res:Car.Common_InvalidData}"
VerticalAlignment="Center"
Width="20" />
<Border BorderBrush="Red"
BorderThickness="5"
Margin="5,0,30,0">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</code></pre>
<p>If one of the <code>TextBoxes</code> has a string in it like , it doesn't parse, no exceptions are thrown, and my dialog's error template is displayed. When I hover the mouse over the <code>TextBox</code>, the error message displayed is "Input string is not in a correct format"</p>
<p>I have a couple of questions:</p>
<ol>
<li>Where is that error message coming from? It's not in my code and if the converter throws an exception, the program dies as it's unhandled. </li>
<li>In the end, I want to display an error if the value in the <code>TextBox</code> can't be parsed. The dialog's View Model object does implement <code>IDataErrorInfo</code>, but the conversion from string to double isn't being done by that object. How do I make that happen?</li>
</ol>
| 3 | 2,293 |
Ajax URL Not Executing The Correct Function in views.py As Defined in urls.py
|
<p>I am leveraging Ajax for some pie charts but data-ajax-url is not working as intended (or as I thought). Per urls.py, reptibase:item-update should execute the item_update function in my views.py file. item_update never gets executed though and instead the same function associated with the current pages url is executed again.</p>
<p>Currently, am getting a parsing error because HTML is coming back instead of json. json is returned from my item_update function though.</p>
<p>item.js</p>
<pre><code>window.onload = function () {
console.log("Child: ", document.getElementById("piee"))
var ctx = document.getElementById("piee").getContext('2d');
var rep_name = $("#pie1").attr("data-rep-name")
var ajax_url = $("#pie1").attr('data-ajax-url')
var _data = []
var _labels = []
// Using the core $.ajax() method
$.ajax({
// The URL for the request
url: ajax_url,
// The data to send (will be converted to a query string)
data: {
name: rep_name
},
// Whether this is a POST or GET request
type: "POST",
// The type of data we expect back
dataType: "json",
headers: {'X-CSRFToken': csrftoken},
context: this
})
// Code to run if the request succeeds (is done);
// The response is passed to the function
.done(function (json) {
if (json.success == 'success') {
var newMale = json.malePerc
var newFemale = json.femalePerc
console.log(newMale, newFemale)
_labels.push("male", "female")
_data.push(parseFloat(newMale), parseFloat(newFemale))
window.myPie.update()
var newUVB = json.uvbPerc
var newSize = json.specSize
} else {
alert("Error: " + json.error);
}
})
// Code to run if the request fails; the raw request and
// status codes are passed to the function
.fail(function (xhr, status, errorThrown) {
alert("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
console.warn(xhr.responseText)
})
// Code to run regardless of success or failure;
.always(function (xhr, status) {
//alert("The request is complete!");
});
var config = {
type: 'pie',
data: {
datasets: [{
data: _data,
backgroundColor: ['#ff0000', "#0000ff"],
label: "Temp"
}],
labels: _labels,
},
options: {
responsive: true
}
};
console.log("data", _data);
console.log("config", config)
window.myPie = new Chart(ctx, config);
console.log("window", window.myPie)
}
</code></pre>
<p>urls.py</p>
<pre><code>app_name = 'reptibase'
urlpatterns = [
path('', views.index, name='home'),
path('search', views.reptile_search, name='search'),
path('add', views.reptile_add, name='add'),
path('list', views.reptile_list, name='list'),
path('listD', views.reptile_listDelete, name='listDelete'),
#path('<int:rep_id>', views.reptile_item, name='item'),
path('<str:scientific>', views.reptile_itemAlt, name='itemAlt'),
path('<int:rep_id>,<int:specific_id>', views.reptile_itemAlt_Edit, name='itemAltEdit'),
path('<str:reptile>,<int:id>', views.comments, name='comments'),
path('update', views.item_update, name='item-update'),
path('edit', views.reptile_edit, name='edit'),
]
</code></pre>
<p>itemAlt.html</p>
<pre><code><div class="pie-chart" id="pie1" data-rep-name="{{ reptile.scientific }}"
data-ajax-url="{% url "reptibase:item-update" %}">
<canvas id="piee"></canvas>
<div class="graph-popout">
<div class="data">
<p>{{ femalePerc }}% Female, {{ malePerc }}% Male. {{ size }} Individuals</p>
</div>
<p><a href="#">Report Issue</a></p>
<p><a href="#" class="share">Share</a></p>
</div>
<h3>Sex</h3>
<div class="background"></div>
<div id="slice1" class="pie-slice">
<div class="pie"></div>
</div>
<div id="slice2" class="pie-slice">
<div class="pie"></div>
</div>
<div id="slice3" class="pie-slice">
<div class="pie"></div>
</div>
</div>
</code></pre>
| 3 | 2,766 |
How can I get rows with specific conditions in r
|
<p>Say that I have a <code>df</code>.</p>
<p>I want to get the <code>id</code> with two conditions at the same time:</p>
<ol>
<li><p>the <code>id</code>'s <code>code</code> should contaions a capital <code>I</code>, regardless of the number that follows it. For example <code>I11</code>, <code>I31</code>...</p>
</li>
<li><p>the <code>id</code>'s <code>code</code> should contaions specific <code>code</code>: <code>E12</code>.</p>
</li>
</ol>
<p>On the example below, the filtered <code>id</code> should be <code>id = 1</code> and <code>id = 2</code>. Because they all contain <code>I</code> and <code>E12</code>.</p>
<p>Same <code>id</code> in the example means in the same group.</p>
<pre><code>structure(list(id = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3,
3, 3, 3, 4, 4, 4, 4, 4, 4), diag = c("main", "other", "main",
"other", "main", "other", "main", "other", "main", "other", "main",
"other", "main", "other", "main", "other", "main", "other", "main",
"other", "main", "other"), code = c("I11", "E12", "I11", "Q34",
"I31", "C33", "E12", "I34", "E12", "I45", "E12", "Z11", "E13",
"Z12", "E14", "Z13", "I25", "E1", "I25", "E2", "I25", "E3")), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -22L), groups = structure(list(
id = c(1, 2, 3, 4), .rows = structure(list(1:6, 7:10, 11:16,
17:22), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -4L), .drop = TRUE))
> df
# A tibble: 22 × 3
# Groups: id [4]
id diag code
<dbl> <chr> <chr>
1 1 main I11
2 1 other E12
3 1 main I11
4 1 other Q34
5 1 main I31
6 1 other C33
7 2 main E12
8 2 other I34
9 2 main E12
10 2 other I45
# … with 12 more rows
</code></pre>
| 3 | 1,245 |
boostrap 3 + datatables buttons: misalignment
|
<p>I'm experiencing misalignment when using boostrap 3 and datatables buttons (<a href="https://datatables.net/extensions/buttons/" rel="nofollow noreferrer">https://datatables.net/extensions/buttons/</a>). How to align them propery?
<a href="https://i.stack.imgur.com/Eyki8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eyki8.png" alt="enter image description here" /></a></p>
<p>everything works fine when on <code>div.dt-buttons</code> margin is set <code>margin-top:2px;</code>, don't know why, but it feels wrong is there any "standard way"?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(myApp) {
myApp.myDataTable = $('.my-table').DataTable({
fixedHeader: true,
paging: true,
buttons: {
dom: {
button: {
className: ''
}
},
buttons: [{
extend: 'colvis',
tag: 'button',
className: 'btn btn-default'
}]
}
});
}(window.myApp = window.myApp || {}));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.11.0/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.0/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.0/css/dataTables.bootstrap.min.css" />
<div class="row">
<div class="col-sm-6">
<div class="dataTables_info" id="DataTables_Table_0_info" role="status" aria-live="polite">Showing 1 to 12 of 24 entries</div>
</div>
<div class="col-sm-3">
<div class="dataTables_paginate paging_simple_numbers" id="DataTables_Table_0_paginate">
<ul class="pagination">
<li class="paginate_button previous disabled" id="DataTables_Table_0_previous">
<a href="#" aria-controls="DataTables_Table_0" data-dt-idx="0" tabindex="0">Previous</a>
</li>
<li class="paginate_button active">
<a href="#" aria-controls="DataTables_Table_0" data-dt-idx="1" tabindex="0">1</a>
</li>
<li class="paginate_button ">
<a href="#" aria-controls="DataTables_Table_0" data-dt-idx="2" tabindex="0">2</a>
</li>
<li class="paginate_button next" id="DataTables_Table_0_next">
<a href="#" aria-controls="DataTables_Table_0" data-dt-idx="3" tabindex="0">Next</a>
</li>
</ul>
</div>
</div>
<div class="col-sm-3">
<div class="dt-buttons">
<button tabindex="0" aria-controls="DataTables_Table_0" type="button" class="buttons-collection buttons-colvis btn btn-default" aria-haspopup="true" aria-expanded="false">
<span>Column visibility</span>
<span class="dt-down-arrow">▼</span>
</button>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| 3 | 1,937 |
Decrypt AES with wrong IV size
|
<p>I have a file encrypted in AES 128 CBC (with openssl in cpp). The encryption has been done with a wrong iv size (8 instead of 16). It's a fact, it's wrong and I can't do anything about it.
The file I get is like this:<br>
[8 bit of IV][Encrypted data]</p>
<p>I have to read this file with Java (android) but I cannot get a correct result.</p>
<p>Here is what I'm using to decrypt the file: </p>
<pre><code>public String decrypt(byte[] key, byte[] datasencrypted) {
// Split IV and actual Datas into 2 differents buffers
int dataSize = datasencrypted.length - 8; // 8 = wrong iv size
byte[] encrypted = new byte[dataSize];
byte[] ivBuff = new byte[8];
System.arraycopy(datasencrypted,0,ivBuff,0,8);
System.arraycopy(datasencrypted,8,encrypted,0,dataSize);
try {
IvParameterSpec iv = new IvParameterSpec(ivBuff);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(encrypted);
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
</code></pre>
<p>Obviously this code throw me an InvalidAlgorithmParameterException: expected IV length of 16. If I change the size of the iv's buffer to 16 no more exception but the end result is just gibberish.</p>
<p>Also the key is defined as unsigned char[] in CPP so to convert it to byte[] in java I simply cast the values like this: </p>
<pre><code>mKey = new byte[]{(byte)0x8c,(byte)0x96,0x5f,.....}};
</code></pre>
<ul>
<li>Is it possible to decrypt this file in java (it's working on the cpp side)?</li>
<li>How should I know which kind of padding to use?</li>
<li>Does the cast of the key value may be a problem?</li>
</ul>
<p>--- EDIT ---
As suggested here is the CPP code that manage to decrypt the file :.
AES_KEYLEN = 128.<br>
AES_ROUND = 5. </p>
<pre><code>size_t Helper::DecryptAES(unsigned char* encMsg, size_t encMsgLen, unsigned char** decMsg)
{
size_t decLen = 0;
size_t blockLen = 0;
*decMsg = (unsigned char*)malloc(encMsgLen);
if (*decMsg == nullptr) return 0;
if (!EVP_DecryptUpdate(mAESDecryptCtx, (unsigned char*)*decMsg, (int*)&blockLen, encMsg, (int)encMsgLen)) {
return 0;
}
decLen += blockLen;
if (!EVP_DecryptFinal_ex(mAESDecryptCtx, (unsigned char*)*decMsg + decLen, (int*)&blockLen)) {
return 0;
}
decLen += blockLen;
return decLen;
}
bool Helper::InitAES(unsigned char* key, unsigned char* salt)
{
mAESEncryptCtx = static_cast<EVP_CIPHER_CTX*>(malloc(sizeof(EVP_CIPHER_CTX)));
mAESDecryptCtx = static_cast<EVP_CIPHER_CTX*>(malloc(sizeof(EVP_CIPHER_CTX)));
mAESKey = static_cast<unsigned char*>(malloc(AES_KEYLEN / 8));
mAESIv = static_cast<unsigned char*>(malloc(AES_KEYLEN / 8));
int size = EVP_BytesToKey(EVP_aes_128_cbc(), EVP_sha256(), salt, key, AES_KEYLEN / 8, AES_ROUNDS, mAESKey, mAESIv);
if (size != AES_KEYLEN / 8)
{
return false;
}
EVP_CIPHER_CTX_init(mAESEncryptCtx);
if (!EVP_EncryptInit_ex(mAESEncryptCtx, EVP_aes_128_cbc(), nullptr, mAESKey, mAESIv))
return false;
EVP_CIPHER_CTX_init(mAESDecryptCtx);
if (!EVP_DecryptInit_ex(mAESDecryptCtx, EVP_aes_128_cbc(), nullptr, mAESKey, mAESIv))
return false;
return true;
}
</code></pre>
<p>IvSIze is ok here , but it's when the iv is concatened to the file that only 8 bits are read instead of 16.</p>
| 3 | 1,523 |
Typescript - Why does this recursive function skips some numbers?
|
<p>From the server, I receive this JSON object. It represents an organigram of a company and the associated departments. </p>
<p>I need to be able to choose a company, and with the ID of the company, I need to pass to an array of numbers the ID's of the associated departments.</p>
<p>For that, I've created this recursive function. It works, but, skips 3 departments, which are placed within another department</p>
<p>This is the JSON file</p>
<pre><code>{
"cd": 1,
"cd_base": 0,
"nome": "EMPRESA A",
"children": [
{
"cd": 2,
"cd_base": 1,
"nome": "Departamento A",
"children": [
{
"cd": 4,
"cd_base": 2,
"nome": "Serviço A1",
"children": []
},
{
"cd": 15,
"cd_base": 2,
"nome": "Serviço A2",
"children": []
}
]
},
{
"cd": 3,
"cd_base": 1,
"nome": "Departamento B",
"children": [
{
"cd": 7,
"cd_base": 3,
"nome": "Serviço B1",
"children": []
}
]
},
{
"cd": 186,
"cd_base": 1,
"nome": "Departamento XX",
"children": []
}
]
}
</code></pre>
<p>And this is the function in Typescript</p>
<pre><code>recursiveFunction(res: any): any[] {
const numbers = new Array(); // to store the ID
console.log('Im on ' + res.cd + ' | ' + res.nome);
numbers.push(res.cd);
if (res.children.length > 0) {
console.log(res.cd + ' | ' + res.nome + ' has children');
res.children.forEach((row) => {
numbers.push(row.cd);
this.recursiveFunction(row);
});
} else {
console.log(res.cd + ' | ' + res.nome + ' doesn\'t have any children');
}
return numbers;
}
</code></pre>
<p>And this is the return of that function to the console</p>
<pre><code>Im on 1 | EMPRESA A
1 | EMPRESA A has c
Im on 2 | Departamento A
2 | Departamento A has children
Im on 4 | Serviço A1
4 | Serviço A1 doesn't have any children
Im on 15 | Serviço A2
15 | Serviço A2 doesn't have any children
Im on 3 | Departamento B
3 | Departamento B has children
Im on 7 | Serviço B1
7 | Serviço B1 doesn't have any children
Im on 186 | Departamento XX
186 | Departamento XX doesn't have any children
</code></pre>
<p>Then I log the <em>numbers</em> array and the result is <em>1,2,3,186</em></p>
<pre><code> this.numbers.forEach(row => {
console.log(row);
});
// 1, 2, 3, 186
</code></pre>
<p>It adds the CD 1, 2, 3 and 186, but skips the 4, 7 and 15.
All of those are a branch/node <strong>within</strong> another branch/node</p>
<p>What am I missing? Is recursive the best way to do this? Is there a simpler way?</p>
<p>Any help is appreciated</p>
| 3 | 1,266 |
an issue with slf4j in a Java application
|
<p>I am trying to config slf4j on Netbeans using Java application(not web).
I added libraries : </p>
<ul>
<li>slf4j-log4j12-1.6.4.jar</li>
<li>slf4j-api-1.6.4.jar</li>
</ul>
<p>My code likes this:</p>
<pre><code>public class TestLogger {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Logger logger = LoggerFactory.getLogger(TestLogger.class);
logger.info("Hello worlds");
}
}
</code></pre>
<p>and I don't have any pom.xml which is mentioned a lot in some guides I read.
what is it?</p>
<p>My output:</p>
<pre><code>run:
Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: org/apache/log4j/Level
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:128)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:108)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:279)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:252)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:265)
at testlogger.TestLogger.main(TestLogger.java:22)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Level
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Level
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:128)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:108)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:279)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:252)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:265)
at testlogger.TestLogger.main(TestLogger.java:22)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Level
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
</code></pre>
<p>I know I must config a .xml file so that slf4j could run smoothly.
but I don't know how and where.</p>
<p>P/s: what is pom.xml? I saw it a lot in some tutorials. </p>
| 3 | 1,044 |
Java components being hidden in JPanel
|
<p>I have two <code>JPanels</code>, each with a bunch of <code>JButtons</code> in them. The <code>JPanel</code> containing the other two has a <code>BoxLayout</code> and the two other <code>JPanels</code> are <code>FlowLayout</code>. The problem is when the window is resized to make the buttons wrap, the buttons in the first and second panel (<code>p0</code>,<code>p2</code>) are covered up by the edge of their corresponding panels. Any ideas?</p>
<p><img src="https://i.stack.imgur.com/5G7AO.png" alt="enter image description here"></p>
<pre><code>import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p0 = new JPanel();
p0.setLayout(new FlowLayout());
p0.setBorder(new TitledBorder("p0"));
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.setBorder(new TitledBorder("p1"));
CustomPanel panel = new CustomPanel();
JScrollPane sp = new JScrollPane(panel);
panel.add(p0);
panel.add(p1);
frame.add(sp);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p0.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
p1.add(new JButton("Hello World!"));
frame.setVisible(true);
}
}
class CustomPanel extends JPanel implements Scrollable {
@Override
public Dimension getPreferredScrollableViewportSize() {
return null;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 0;
}
@Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 0;
}
}
</code></pre>
| 3 | 1,172 |
Adding calls inside QgraphicsRectItem subclass triggers infinite redraw
|
<p>I have a hierarchy of object types, inheriting from a custom interface and <code>QGraphicsItem</code>.</p>
<p>In hope of optimizing the code, I would like to inherit from <code>QGraphicsSomethingItem</code>. Example: rectangle</p>
<pre><code>class RectangleItem : public Item, public QGraphicsItem
{
RectangleItem() : Item() // Item initializes m_pen, m_brush
{
setFlags(QGraphicsItem::ItemIsMovable |
QGraphicsItem::ItemIsFocusable |
QGraphicsItem::ItemIsSelectable);
}
QRectF RectangleItem::boundingRect() const
{
return QRectF(-50, -50, 100, 100);
}
void RectangleItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
setItemPen(); // calculates m_pen in class Item
setItemBrush(); // calculates m_brush in class Item
painter->setPen(m_pen);
painter->setBrush(m_brush);
painter->drawRect(boundingRect());
}
}
</code></pre>
<p>This works perfectly.</p>
<p>Now trying the same thing but inheriting from <code>QGraphicsRectItem</code></p>
<pre><code>class RectangleItem : public Item, public QGraphicsRectItem
{
RectangleItem() : Item() // Item initializes m_pen, m_brush
{
setRect(-50, -50, 100, 100);
setFlags(QGraphicsItem::ItemIsMovable |
QGraphicsItem::ItemIsFocusable |
QGraphicsItem::ItemIsSelectable);
}
QRectF RectangleItem::boundingRect() const
{
return QRectF(-50, -50, 100, 100);
}
void RectangleItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
// setItemPen(); // calculates m_pen in class Item
// setItemBrush(); // calculates m_brush in class Item
setPen(m_pen);
setBrush(m_brush);
QGraphicsRectItem::paint(painter, option, widget);
}
}
</code></pre>
<p>This creates an infinite loop<br>
- a breakpoint on <code>setItemPen()</code> showed it kept calling it. So I removed it, along with <code>setItemBrush()</code>. (though I really need to set custom pen)<br>
- a breakpoint on <code>setPen()</code> showed it kept calling it. So I removed it. Same with <code>setBrush()</code><br>
- once there were no things being "set" inside paint, the paint worked.</p>
<p>Of course this is not functional - I need to be able to set item properties, and my understanding is that the call to <code>paint()</code> - happening when a call to update the scene - would update he items. After all, my first example, inheriting from <code>QGraphicsItem</code>, works.</p>
<p>I have found something similar in this <a href="https://stackoverflow.com/a/17338910/1217150">question</a> - but no answer on how to fix it, or no actual explanation why the call to set pen and brush causes a redraw. There is nothing in that code using any of the item's drawing properties, and even more - if I call <code>setPen(m_pen)</code> with the value from constructor, I see nothing to be recalculated...</p>
<p>What triggers the object redraw and how can I avoid it ?</p>
| 3 | 1,033 |
C# How to write each table in a Word file to its own Excel file
|
<p>I'm trying to write code in C# WinForms that allows a user to select a directory tree, and extract all of the table data from a word document into an excel file. Presently, the code compiles and you can select your directories, etc, but once it begins to iterate through the loop for each table it crashes.</p>
<p>The program successfully opens the first word file and writes the first excel file (table_1_whatever.xlsx) and saves it in the destination folder. However, on the second table in the same file I get this error on this line of code:</p>
<pre><code> worksheet.Cells[row, col] = objExcelApp.WorksheetFunction.Clean(table.Cell(row, col).Range.Text);
</code></pre>
<p>System.Runtime.InteropServices.COMException: 'The requested member of the collection does not exist.' </p>
<p>I can't seem to figure out why it doesn't exist. Each time it goes through the foreach loop it should be creating a new worksheet, but it doesn't appear to be working. Any insight, examples, or suggestions are welcome!</p>
<p>Code:</p>
<pre><code> private void WordRunButton_Click(object sender, EventArgs e)
{
var excelApp = new excel.Application();
excel.Workbooks workbooks = excelApp.Workbooks;
var wordApp = new word.Application();
word.Documents documents = wordApp.Documents;
wordApp.Visible = false;
excelApp.Visible = false;
string[] fileDirectories = Directory.GetFiles(WordSourceBox.Text, "*.doc*",
SearchOption.AllDirectories);
foreach (var item in fileDirectories)
{
word._Document document = documents.Open(item);
int tableCount = 1;
foreach (word.Table table in document.Tables)
{
if (table.Cell(1, 1).ToString() != "Doc Level")
{
string wordFile = item;
appendName = Path.GetFileNameWithoutExtension(wordFile) + "_Table_" + tableCount + ".xlsx";
var workbook = excelApp.Workbooks.Add(1);
excel._Worksheet worksheet = (excel.Worksheet)workbook.Sheets[1];
for (int row = 1; row <= table.Rows.Count; row++)
{
for (int col = 1; col <= table.Columns.Count; col++)
{
var cell = table.Cell(row, col);
var range = cell.Range;
var text = range.Text;
var cleaned = excelApp.WorksheetFunction.Clean(text);
worksheet.Cells[row, col] = cleaned;
}
}
workbook.SaveAs(Path.Combine(WordOutputBox.Text, Path.GetFileName(appendName)), excel.XlFileFormat.xlWorkbookDefault);
workbook.Close();
Marshal.ReleaseComObject(workbook);
}
else
{
WordOutputStreamBox.AppendText(String.Format("Table {0} ignored\n", tableCount));
}
WordOutputStreamBox.AppendText(appendName + "\n");
tableCount++;
}
document.Close();
Marshal.ReleaseComObject(document);
WordOutputStreamBox.AppendText(item + "\n");
}
WordOutputStreamBox.AppendText("\nAll files parsed");
excelApp.Application.Quit();
workbooks.Close();
excelApp.Quit();
WordOutputStreamBox.AppendText("\nExcel files closed");
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelApp);
WordOutputStreamBox.AppendText("\nExcel files released");
wordApp.Application.Quit();
wordApp.Quit();
WordOutputStreamBox.AppendText("\nWord files have been quit");
Marshal.ReleaseComObject(documents);
Marshal.ReleaseComObject(wordApp);
WordOutputStreamBox.AppendText("\nWord files have been released\n");
}
</code></pre>
<p>Edit 1:(Sorry for posting in the wrong place the first time!)</p>
<p>Ok, so the problem has been isolated...</p>
<p>The code logic of the code was fine, and the table was in fact there. The issue is that the second table of these files has a set of split cells in it, so, when it reaches the cell that contains it, the program crashes.</p>
<p>As a temp fix, I have just set it to ignore the table if the header == whatever. Does anyone know of a solution that actually allows to extract this data though?</p>
| 3 | 1,941 |
Not getting extra from ACTION_VIEW intent
|
<p>I am using firebase notifications and dynamic links in my application</p>
<p>I am sending deeplinks as a payload in notifications and when the user clicks on the notification i am opening the deeplink like this</p>
<pre><code> Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(pushAction.getActionDeeplink())); // contains the deeplink
if (pushNotification.getExtraData() != null) { // not extra Data from push
intent.putExtra(IntentKeys.PUSH_DATA_EXTRA, pushNotification.getExtraData());
}
PendingIntent actionPendingIntent =
PendingIntent.getActivity(context, pushNotification.getNotificationId(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(largeIcon)
.setTicker(pushNotification.getTicker())
.setContentTitle(pushNotification.getTitle())
.setContentText(pushNotification.getMessage())
.setAutoCancel(true)
.setContentIntent(actionPendingIntent);
notificationManager.notify(uniqueId, mBuilder.build());
</code></pre>
<p>I have declared an activity in my application</p>
<pre><code><activity
android:name=".ui.activities.SaveActivity"
android:label="@string/title_activity_save"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden|adjustPan">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="example.com"
android:pathPattern="/save"
android:scheme="http" />
</intent-filter>
</activity>
</code></pre>
<p>and the deeplink url, that is sent through notification is <strong><a href="http://example.com/save" rel="nofollow">http://example.com/save</a></strong></p>
<p>And in the activity I have setup to receive deeplinks like this</p>
<pre><code>public class SaveActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
setupGoogleApiClient();
}
private void setupGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(AppInvite.API)
.build();
boolean autoLaunchDeepLink = false;
AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, this, autoLaunchDeepLink)
.setResultCallback(
new ResultCallback<AppInviteInvitationResult>() {
@Override
public void onResult(@NonNull AppInviteInvitationResult result) {
if (result.getStatus().isSuccess()) {
Intent intent = result.getInvitationIntent();
String deepLink = AppInviteReferral.getDeepLink(intent);
Log.d("save getInvitation: found deeplink." + deepLink);
/**************************** ISSUE ***********************/
if(intent.hasExtra(IntentKeys.PUSH_DATA_EXTRA)) {
// there is no extra data :(
}
/**************************** ISSUE ***********************/
} else {
Log.d("save getInvitation: no deep link found.");
}
}
});
}
}
</code></pre>
<p>Everything is working as expected. The SaveActivity is getting called and it is opening the SaveActivity. But, NO extra data is received in the activity.</p>
<p>I am setting the string extra using IntentKeys.PUSH_DATA_EXTRA as the key in the intent.</p>
| 3 | 2,099 |
FusedLocationApi method getLastLocation() always null during first call
|
<p>Looking for some help with a problem in my app concerning getting the current device location. Below is the GPSLocationListener class I am using.</p>
<pre><code>import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* This class takes care of capturing the location of the device.
*/
public class GPSLocationListener implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener,
ActivityCompat.OnRequestPermissionsResultCallback {
protected static final String TAG = "location-updates-sample";
public static final int LOCATION_RESQUEST = 1;
/**
* The desired interval for location updates. Inexact. Updates may be more or less frequent.
*/
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
/**
* The fastest rate for active location updates. Exact. Updates will never be more frequent
* than this value.
*/
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Stores parameters for requests to the FusedLocationProviderApi.
*/
protected LocationRequest mLocationRequest;
/**
* Represents a geographical location.
*/
protected Location mCurrentLocation;
private Activity mActivity;
public double lat;
public double lon;
public GPSLocationListener(Activity activity) {
this.mActivity = activity;
// Kick off the process of building a GoogleApiClient and requesting the LocationServices API.
buildGoogleApiClient();
}
/**
* Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
/**
* Sets up the location request. Android has two location request settings:
* {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Navigation Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* Requests location updates from the FusedLocationApi.
*/
public void startLocationUpdates(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this.mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.mActivity, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
//return;
}else {
try {
ActivityCompat.requestPermissions(this.mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET},
LOCATION_RESQUEST);
}catch (Exception e){
e.printStackTrace();
}
}
// If the initial location was never previously requested, we use
// FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
// its value in the Bundle and check for it in onCreate().
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {@code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
public void onStart() {
mGoogleApiClient.connect();
//createLocationRequest();
// Within {@code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
}
public void onStop() {
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this.mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.mActivity, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "onConnected: Just empty if statement");
}else {
try {
ActivityCompat.requestPermissions(this.mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET},
LOCATION_RESQUEST);
}catch (Exception e){
e.printStackTrace();
}
}
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.i(TAG, "onConnected " + String.valueOf(mCurrentLocation));
}
}
}
/**
* Callback that fires when the location changes.
*/
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
Log.i(TAG, "onLocationChanged: " + String.valueOf(mCurrentLocation.getLatitude()));
Log.i(TAG, "onLocationChanged: " + String.valueOf(mCurrentLocation.getLongitude()));
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mActivity.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
switch (requestCode){
case LOCATION_RESQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
startLocationUpdates(); // Calling this here is the only place that does not make the app crash
getCurrentLocation();
}else {
Log.i(TAG, "onRequestPermissionsResult: Need Permissions");
return;
}
break;
default:
break;
}
return;
}
public void getCurrentLocation(){
if (mCurrentLocation != null){
lat = mCurrentLocation.getLatitude();
lon = mCurrentLocation.getLongitude();
Log.i(TAG, "getCurrentLocation(): " + String.valueOf(mCurrentLocation.getLatitude()));
Log.i(TAG, "getCurrentLocation(): " + String.valueOf(mCurrentLocation.getLongitude()));
}
}
public GoogleApiClient getGoogleApiClient(){
return mGoogleApiClient;
}
}
</code></pre>
<p>Trying this out on my actual device with the GPS already enabled in the settings, I get some odd behavior. If I do not at all, call the <code>startLocationUpdates()</code> method or I call it in the <code>onRequestPermissionsResult()</code> method, the app launches fine and when I grant Device Location Permissions, the <code>mCurrentLocation</code> object is null, but does not crash. I stop the app and then launch again, and the <code>mCurrentLocation</code> has latitude and longitude coordinates that I can see in the logcat, which is what I am wanting in the first place, but they only hold any values, after the second launch. Now if I uninstall the app and try to call the <code>startLocationUpdates()</code> method anywhere, the app crashes upon launch with the error: </p>
<pre><code>Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
</code></pre>
<p>But I am checking for permissions in the <code>onConnected()</code> method and also in the <code>startLocationUpdates()</code> method as well, although I do not think this is correct but this is the only way that I can get Android Studio to not underline the </p>
<pre><code>LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
</code></pre>
<p>statement in red with a Permissions warning.</p>
<p>Here is the <code>Activity</code> where I am trying to get the location updates with the <code>mapItBtnRespond()</code> method.</p>
<pre><code>package com.example.bigdaddy.as_built_weldmapper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.bigdaddy.as_built_weldmapper.utilities.BendHelper;
import com.example.bigdaddy.as_built_weldmapper.utilities.GPSLocationListener;
public class SagActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
MajorButtonFragment.OnFragmentInteractionListener, Communicator{
/* Using this to insert into the Bend Direction field. */
public static String SAG_DIRECTION = "SAG";
/* This spinner holds the bend types */
Spinner mSagBendTypesSpinner;
/* Using this string to collect what was selected for the spinner type */
private String mBendTypeSpinnerVal;
/* All the EditText for the Activity */
private EditText mSagGpsShotEt;
private EditText mSagExistingGpsEt;
private EditText mSagCoverEt;
private EditText mSagDegreeEt;
private EditText mSagDistanceFromEt;
private EditText mSagNotesEt;
private EditText mSagOccupyIdEt;
private EditText mSagStationNumEt;
private GPSLocationListener mGPSLocationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sag);
mGPSLocationListener = new GPSLocationListener(SagActivity.this);
/* checking if the MajorButtonFragment is null */
if (findViewById(R.id.majorButtonFragment) != null) {
if (savedInstanceState != null) {
return;
}
}
/* Referencing the spinner and setting the itemsSelectedListener */
mSagBendTypesSpinner = (Spinner) findViewById(R.id.bend_types_spinner);
mSagBendTypesSpinner.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
/* Create an ArrayAdapter using the string array and a default spinner layout */
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.bend_types_array, android.R.layout.simple_spinner_item);
/* Specify the layout to use when the list of choices appears */
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
/* Apply the adapter to the spinner */
mSagBendTypesSpinner.setAdapter(adapter);
/* Referencing and calling all the EditText for the Activity */
mSagGpsShotEt = (EditText) findViewById(R.id.eTextGpsShotForSag);
mSagExistingGpsEt = (EditText) findViewById(R.id.eTextExistGradeForSag);
mSagCoverEt = (EditText) findViewById(R.id.eTextCoverForSag);
mSagDegreeEt = (EditText) findViewById(R.id.eTextDegreeForSag);
mSagDistanceFromEt = (EditText) findViewById(R.id.eTextDistanceFromForSag);
mSagNotesEt = (EditText) findViewById(R.id.eTextNotesForSagActivity);
mSagOccupyIdEt = (EditText) findViewById(R.id.eTextJointIdSagActivity);
mSagStationNumEt = (EditText) findViewById(R.id.eTextStationNumSagActivity);
} /*onCreate() ends here.*/
@Override
protected void onStart() {
super.onStart();
Log.i("SagActivity", "onStart: ");
/* Starting the location listener here (GoogleApiClient) */
if (mGPSLocationListener != null){
mGPSLocationListener.onStart();
}
}
@Override
protected void onStop() {
super.onStop();
Log.i("SagActivity", "onStop: ");
/* Stopping the location listener here (GoogleApiClient) */
if (mGPSLocationListener != null){
mGPSLocationListener.onStop();
}
}
@Override
public void onLocalVoiceInteractionStopped() {
super.onLocalVoiceInteractionStopped();
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
mBendTypeSpinnerVal = mSagBendTypesSpinner.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
@Override
public void exitBtnRespond() {
}
/**
* This overridden method comes from the Communicator Interface and is used globally in all
* Activities that implement it to Store (write) a transaction to the database.
* The utility class saveAndInsertBend() method is invoked here.
*/
@Override
public void storeBtnRespond() {
BendHelper.saveAndInsertBend(SagActivity.this, SAG_DIRECTION, mBendTypeSpinnerVal, mSagStationNumEt,
mSagOccupyIdEt, mSagDegreeEt, mSagDistanceFromEt, mSagGpsShotEt, mSagExistingGpsEt,
mSagCoverEt, mSagNotesEt);
}
@Override
public void mapItBtnRespond() {
Toast.makeText(this, "MapItBtn clicked in SagActivity",Toast.LENGTH_LONG).show();
mGPSLocationListener.getCurrentLocation();
Log.i("SagActivity", "mapItBtnRespond: " + String.valueOf(mGPSLocationListener.lat));
Log.i("SagActivity", "mapItBtnRespond: " + String.valueOf(mGPSLocationListener.lon));
}
@Override
public void onFragmentInteraction() {
}
}
</code></pre>
<p>What am I doing wrong here with all of this? Any help would be greatly appreciated as I am confused with the Permissions apparently. Thanks so much for any guidance. </p>
| 3 | 6,732 |
How can I pass configuration to Database class
|
<p>I have a database class in which i want to pass configuration. I have to keep the "framework" and the Application files separate.
here is my configuration class
</p>
<pre><code><?php namespace Fzaffa\System;
class Config {
private $items = [];
public function get($name)
{
list($file, $key) = $this->parseName($name);
$this->includeIfNotCached($file);
$item = $this->parseItemToReturn($key, $file);
return $item;
}
/**
* @param $file
*/
private function includeIfNotCached($file)
{
if ( ! array_key_exists($file, $this->items))
{
$arr = include __DIR__ . '/App/Config/' . $file . '.php';
$this->items[$file] = $arr;
}
}
/**
* @param $name
* @return array
*/
private function parseName($name)
{
if (strpos($name, '.'))
{
list($file, $key) = explode('.', $name);
return [$file, $key];
}
return [$name, null];
}
/**
* @param $key
* @param $file
* @return mixed
*/
private function parseItemToReturn($key, $file)
{
if ($key)
{
return $this->items[$file][$key];
}
else
{
return $this->items[$file];
}
}
}
</code></pre>
<p>and here is my Database class
</p>
<pre><code><?php namespace Fzaffa\System;
use PDO;
class Database {
private $host = 'localhost';
private $dbname = 'mycms';
private $user = 'homestead';
private $pass = 'secret';
private $dbh;
private $error;
private $statement;
public function __construct()
{
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ";charset=utf8";
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try
{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e)
{
$this->error = $e->getMessage();
}
}
</code></pre>
<p>I would like to be able to instantiate the configuration object in the index.php (where all bootstrapping and routing happens) like so
$config = new \Fzaffa\system\Config;
and then use the config variables inside classes like $class->get('database.username')</p>
<p>The config file being application specific need to stay separate and inside the /App/ folder.</p>
<p>Is there a way I can do it without an IoC container and without having to pass the config object through all the hierarchy to the model (Where I instantiate the \Fzaffa\Sysyem\Database object)?</p>
<p>Thank you in advance.</p>
| 3 | 1,248 |
Javascript: Extract correct json from php script using id
|
<p>The issue i am having is i am unable to figure out the correct code through which to extract the information i am looking for</p>
<p>Here firstly is the exhibitions.php</p>
<pre><code><?php
$exhibitionsarray = array(
array("exhibition_id" => "1", "exhibition_title" => "New York, New York", "exhibition_subject" => "New York", "ticket_price" => "10",
"exhibits" => array(
array("exhibit_id" => "3", "exhibit_title" => "Brooklyn Bridge from City Hall Park", "exhibit_description" => "New York, June 2005", "exhibit_image" => "brooklynbridge.jpg", "photographer" => "MLG"),
array("exhibit_id" => "6", "exhibit_title" => "Central Park, New York", "exhibit_description" => "New York, June 2005", "exhibit_image" => "centralpark.jpg", "photographer" => "MLG"),
array("exhibit_id" => "7", "exhibit_title" => "Chrysler Building at night, New York", "exhibit_description" => "New York, July 2001", "exhibit_image" => "chrysler_building.jpg", "photographer" => "MLG")
),
"locations" => array(
array("location_id" => "1", "location_name" => "Kelvingrove Art Gallery and Museum", "location_postcode" => "G3 8AG"),
array("location_id" => "3", "location_name" => "Walker Art Gallery", "location_postcode" => "L3 8EL"),
array("location_id" => "5", "location_name" => "Tate Modern", "location_postcode" => "SE1 9TG")
)
),
array("exhibition_id" => "2", "exhibition_title" => "Spanish Cities", "exhibition_subject" => "Spain", "ticket_price" => "15",
"exhibits" => array(
array("exhibit_id" => "9", "exhibit_title" => "Eiffel Bridge, Girona", "exhibit_description" => "Girona, March 2008", "exhibit_image" => "eiffel_bridge.jpg", "photographer" => "LPK"),
array("exhibit_id" => "13", "exhibit_title" => "Plaza Mayor, Madrid", "exhibit_description" => "Madrid, June 2010", "exhibit_image" => "plazamayor.jpg", "photographer" => "MLG"),
array("exhibit_id" => "14", "exhibit_title" => "Puppy (Day)", "exhibit_description" => "Bilbao, September 2006 - Puppy in daylight", "exhibit_image" => "puppy_day.jpg", "photographer" => "LPK"),
array("exhibit_id" => "15", "exhibit_title" => "Puppy (Night)", "exhibit_description" => "Bilbao, March 2011 - Puppy at night", "exhibit_image" => "puppy_night.jpg", "photographer" => "LPK")
),
"locations" => array(
array("location_id" => "2", "location_name" => "Scottish National Gallery", "location_postcode" => "EH2 2EL")
)
),
array("exhibition_id" => "3", "exhibition_title" => "A Glasgow Viewpoint", "exhibition_subject" => "Glasgow", "ticket_price" => "5",
"exhibits" => array(
array("exhibit_id" => "2", "exhibit_title" => "Bothwell Castle", "exhibit_description" => "Bothwell, April 2011", "exhibit_image" => "bothwell_castle.jpg", "photographer" => "LPK"),
array("exhibit_id" => "10", "exhibit_title" => "Hampden Park", "exhibit_description" => "Glasgow, June 2007 - SQA Event", "exhibit_image" => "hampden.jpg", "photographer" => "MLG"),
array("exhibit_id" => "11", "exhibit_title" => "Hogganfield Loch, Glasgow, Winter", "exhibit_description" => "Glasgow, January 2010", "exhibit_image" => "hogganfield_loch.jpg", "photographer" => "MLG"),
array("exhibit_id" => "16", "exhibit_title" => "Ramblas", "exhibit_description" => "Barcelona, July 1999 - Ramblas (Two Old Friends from Glasgow)", "exhibit_image" => "ramblas.jpg", "photographer" => "MLG"),
array("exhibit_id" => "17", "exhibit_title" => "River Clyde at Bothwell", "exhibit_description" => "Bothwell, April 2011 - River Clyde from Bothwell", "exhibit_image" => "river_clyde.jpg", "photographer" => "LPK"),
array("exhibit_id" => "18", "exhibit_title" => "River Kelvin", "exhibit_description" => "Glasgow, July 2011", "exhibit_image" => "river_kelvin.jpg", "photographer" => "MLG"),
array("exhibit_id" => "21", "exhibit_title" => "University Avenue", "exhibit_description" => "Glasgow, July 2011", "exhibit_image" => "university_avenue.jpg", "photographer" => "LPK")
),
"locations" => array(
array("location_id" => "1", "location_name" => "Kelvingrove Art Gallery and Museum", "location_postcode" => "G3 8AG"),
array("location_id" => "2", "location_name" => "Scottish National Gallery", "location_postcode" => "EH2 2EL"),
array("location_id" => "3", "location_name" => "Walker Art Gallery", "location_postcode" => "L3 8EL"),
array("location_id" => "4", "location_name" => "The Lowry", "location_postcode" => "M50 3AZ"),
array("location_id" => "5", "location_name" => "Tate Modern", "location_postcode" => "SE1 9TG")
)
),
array("exhibition_id" => "4", "exhibition_title" => "Some Churches", "exhibition_subject" => "Religious Architecture", "ticket_price" => "5",
"exhibits" => array(
array("exhibit_id" => "1", "exhibit_title" => "Big Ben", "exhibit_description" => "London, September 2011", "exhibit_image" => "big_ben.jpg", "photographer" => "LPK"),
array("exhibit_id" => "12", "exhibit_title" => "Louvre, Paris", "exhibit_description" => "Paris, June 1998", "exhibit_image" => "louvre.jpg", "photographer" => "LPK"),
array("exhibit_id" => "19", "exhibit_title" => "Sagrada Familia - Honeymoon", "exhibit_description" => "Barcelona, June 1997 - Honeymoon", "exhibit_image" => "sagrada.jpg", "photographer" => "MLG"),
array("exhibit_id" => "20", "exhibit_title" => "Mormon Temple", "exhibit_description" => "Salt Lake City, July 2005", "exhibit_image" => "salt_lake.jpg", "photographer" => "MLG")
),
"locations" => array(
array("location_id" => "1", "location_name" => "Kelvingrove Art Gallery and Museum", "location_postcode" => "G3 8AG"),
array("location_id" => "2", "location_name" => "Scottish National Gallery", "location_postcode" => "EH2 2EL")
)
),
array("exhibition_id" => "5", "exhibition_title" => "Barcelona Highlights", "exhibition_subject" => "Barcelona", "ticket_price" => "15",
"exhibits" => array(
array("exhibit_id" => "4", "exhibit_title" => "Martin at Camp Nou, Honeymoon", "exhibit_description" => "Barcelona, June 1997 - Honeymoon", "exhibit_image" => "campnou.jpg", "photographer" => "LPK"),
array("exhibit_id" => "5", "exhibit_title" => "Placa de Catalunya, Barcelona - Honeymoon", "exhibit_description" => "Barcelona, June 1997 - Honeymoon", "exhibit_image" => "catalunya.jpg", "photographer" => "MLG")
),
"locations" => array(
array("location_id" => "3", "location_name" => "Walker Art Gallery", "location_postcode" => "L3 8EL"),
array("location_id" => "4", "location_name" => "The Lowry", "location_postcode" => "M50 3AZ"),
array("location_id" => "5", "location_name" => "Tate Modern", "location_postcode" => "SE1 9TG")
)
),
array("exhibition_id" => "6", "exhibition_title" => "Martin’s Pictures", "exhibition_subject" => "Martin", "ticket_price" => "5",
"exhibits" => array(
array("exhibit_id" => "8", "exhibit_title" => "David Crosby at David Gilmour gig", "exhibit_description" => "Glasgow, May 2006", "exhibit_image" => "davidcrosby.jpg", "photographer" => "MLG"),
array("exhibit_id" => "22", "exhibit_title" => "Wolves", "exhibit_description" => "Yellowstone Park, October 2004", "exhibit_image" => "wolves.jpg", "photographer" => "MLG")
),
"locations" => array(
array("location_id" => "1", "location_name" => "Kelvingrove Art Gallery and Museum", "location_postcode" => "G3 8AG"),
array("location_id" => "3", "location_name" => "Walker Art Gallery", "location_postcode" => "L3 8EL"),
array("location_id" => "4", "location_name" => "The Lowry", "location_postcode" => "M50 3AZ"),
array("location_id" => "5", "location_name" => "Tate Modern", "location_postcode" => "SE1 9TG")
)
)
);
echo json_encode($exhibitionsarray);
?>
</code></pre>
<p>The information i wish depends on the specific exhibition id... and only use exhibits not location so for example when the id = 1 i wish this information...</p>
<pre><code>array("exhibition_id" => "1", "exhibition_title" => "New York, New York", "exhibition_subject" => "New York", "ticket_price" => "10",
"exhibits" => array(
array("exhibit_id" => "3", "exhibit_title" => "Brooklyn Bridge from City Hall Park", "exhibit_description" => "New York, June 2005", "exhibit_image" => "brooklynbridge.jpg", "photographer" => "MLG"),
array("exhibit_id" => "6", "exhibit_title" => "Central Park, New York", "exhibit_description" => "New York, June 2005", "exhibit_image" => "centralpark.jpg", "photographer" => "MLG"),
array("exhibit_id" => "7", "exhibit_title" => "Chrysler Building at night, New York", "exhibit_description" => "New York, July 2001", "exhibit_image" => "chrysler_building.jpg", "photographer" => "MLG")
),
</code></pre>
<p>Now here is the code i currently have to get all exhibit info</p>
<pre><code>function getExibitions()
{
console.log(json);
myExhibitionsView = document.getElementById('exhibitioncontent');
images = document.createElement('ul');
for (var i = 0; i < json.length; i++) {
for (var j = 0; j < json[i].exhibits.length; j++) {
listCheck = document.createElement('p');
listCheck.id = 'image';
listCheck.innerHTML = "<img src = " + "./images/" + json[i].exhibits[j].exhibit_image + " Photo Cover' height='200' width='200'>";
console.log(listCheck);
myExhibitionsView.appendChild(images);
images.appendChild(listCheck);
console.log(listCheck);
}
}
}
</code></pre>
<p>This code allows me to extract the json and then use the image urls... this is what i wish to do here as well but only if its of the specific id. Thank you very much for the assistance </p>
| 3 | 5,709 |
about concurrency with core data and relationship
|
<p>i want to insert data on secondary thread and then track changes in main thread.</p>
<p>I have two Entitys,and they was set Inverse.</p>
<pre><code>@interface Entity1 : NSManagedObject
@property (nonatomic, retain) NSString * data;
@property (nonatomic, retain) Entity2 * entity2;
@end
@interface Entity2 : NSManagedObject
@property (nonatomic, retain) Entity1 * entity1;
@end
</code></pre>
<p>I register context save notificaton in main thread.</p>
<pre><code> //this managedObjectContext run in main thread
-(NSManagedObjectContext *)managedObjectContext_mainThread {
......
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
return managedObjectContext_mainThread ;
}
//pass notification
- (void)contextDidSave:(NSNotification *)notification
{
......
[managedObjectContext_mainThread
mergeChangesFromContextDidSaveNotification:notification];
}
</code></pre>
<p>fetch from coredata,it will run in main thread</p>
<pre><code>-(NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil) {
NSManagedObjectContext *moc = [self managedObjectContext_mainThread];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity2"
inManagedObjectContext:moc];
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"entity1"
ascending:YES];
.....
}
return fetchedResultsController;
}
//NSFetchedResultsControllerDelegate, in this functions updata my UI
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
NSLog(@"controllerDidChangeContent start!");
}
</code></pre>
<p>this is the app start. </p>
<pre><code> -(void)loadView {
myQueue = dispatch_queue_create("myQueue", NULL);
// this context is managedObjectContext_mainThread and run in main thread
NSArray *results = [self fetchedResultsController];
//insert Data oparation in managedObjectContext_otherThread and myQueueu
dispatch_async(myQueue, ^{
......
Entity1 *entity1 =
[NSEntityDescription insertNewObjectForEntityForName:@"Entity1"
inManagedObjectContext:managedObjectContext_otherThread];
Entity2 *entity2 =
[NSEntityDescription
insertNewObjectForEntityForName:@"Entity2"
inManagedObjectContext:managedObjectContext_otherThread];
entity1.data = @"myData";
entity1.entity2 = entity2;
[[self managedObjectContext_otherThread] save:nil];
});
}
</code></pre>
<p>when i build i got an error</p>
<pre><code>-[Entity1 compare:]: unrecognized selector sent to instance 0x4d3ec90
</code></pre>
<p>and the error occur in NSFetchedResultsController handle context notification,this is the call stack:</p>
<pre><code>__exceptionPreprocess + 185
objc_exception_throw + 47
-[NSObject(NSObject) doesNotRecognizeSelector:] + 187
___forwarding___ + 966
CF_forwarding_prep_0 + 50
_NSCompareObject + 76
+[NSFetchedResultsController(PrivateMethods)
_insertIndexForObject:inArray:lowIdx:highIdx:sortDescriptors:] + 286
-[NSFetchedResultsController(PrivateMethods) _postprocessInsertedObjects:] + 402
-[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] + 1804
</code></pre>
<p>if i don't fetch the Entity2 but Entity1 in fetchedResultsController,my app run ok.but I want to fetch entity2,and then use entity2.entity1.data to access entity1.who can help me.</p>
| 3 | 1,570 |
Quick Sort using C#
|
<p>Hello I trying to do a QuickSort but didn't appear the result, For example the user input "cdabe" so the expected result is "abcde". May I know what is the cause why the result didn't display?
because There is no error in the code. I'm using MVC. My MergeSort is working properly but my QuickSort didn't.</p>
<p>Model :</p>
<pre><code>public string QuickSort()
{
string arrangedSort = "";
string Word= "cdabe";
List<string> ListLetters = new List<string>();
for (int i = 0; i < Word.Length; i++)
{
ListLetters.Add(Word.Substring(i, 1));
}
aQuicksort(Word, 0, ListLetters.Count - 1);
void aQuicksort(string Word, int left, int right)
{
int i = left;
int j = right;
var pivot = Word[(left + right) / 2];
while (i <= j)
{
while (char.Parse(ListLetters[i]) < pivot)
i++;
while (char.Parse(ListLetters[i]) > pivot)
j--;
if (i <= j)
{
var tmp = ListLetters[i];
ListLetters[i] = ListLetters[j];
ListLetters[j] = tmp;
i++;
j--;
}
}
if (left < j)
aQuicksort(Word, left, j);
if (i < right)
aQuicksort(Word, i, right);
foreach (var listLetter in ListLetters)
{
arrangedSort += listLetter;
}
}
return arrangedSort;
}
</code></pre>
| 3 | 1,368 |
AJAX Request in CodeIgniter Application Failing After Inactivity
|
<p>The application I am working on is built in CodeIgniter, and the content is always loaded via ajax into the main content div.</p>
<p>This works without fail normally, apart from after the user has been inactive for a short while.</p>
<p>We haven't completely narrowed down the inactivity time required for the request to fail, but it's around 40 minutes or more of inactivity.</p>
<p>I've tried logging details to the console in the error callback of the AJAX request, but nothing is logged.</p>
<p>I'm thinking that it's related to a session expiry but I can't be sure. I know when using CodeIgniter, there are two sessions which are created automatically (PHPSESSID, and ci_session) so my instinct is that it has something to do with these, or one of them, expiring?</p>
<p>When the request fails the headers, preview, response and cookies tab on chrome's developer tools show nothing.</p>
<p>If anyone has experienced this before, or has any ideas what may be causing the problem, I'd appreciate the input.</p>
<p><strong>Edit:</strong></p>
<p>Below is the AJAX request which is experiencing the above problem.</p>
<p>All links within my application use this loadPage function instead of a standard redirect.</p>
<pre><code>function loadPage(href, type, clickElem, changeHash) {
if(ajax_loading == true) { return false; }
ajax_loading = true;
$('#recording_area').slideUp('slow');
if(typeof queue_countdown !== 'undefined') { clearInterval(queue_countdown); }
if(type == 'sidenav') {
$('#sidenav_accordion .accordion-heading a').removeClass('on');
$('#sidenav_accordion .accordion-inner a').removeClass('on');
$(clickElem).parents('.accordion-group').find('.accordion-heading a').addClass('on');
$(clickElem).addClass('on');
} else {
page_requested = href.replace(/^\/([^\/]*).*$/, '$1');
if(!page_requested) { page_requested = 'dashboard'; }
nav_elem = $('.sidenav a[href="/' + page_requested + '"]');
if(nav_elem.html() != null) {
nav_elem_group = nav_elem.parents().eq(2).children().first().find('a');
if(!nav_elem_group.hasClass('on')) {
if(!nav_elem.parents().eq(2).children().first().next().hasClass('in')) { nav_elem_group.click(); }
$('.sidenav .on').removeClass('on');
nav_elem.addClass('on');
nav_elem_group.addClass('on');
}
}
}
current_ajax_request = $.ajax({
type: 'GET',
url: href,
dataType: 'html',
cache: true,
beforeSend: function() {
},
success: function(data){
$('#map-canvas').remove();
$('.content_wrapper script').each(function(){
$(this).remove();
});
$('#gbox_Customers').remove();
if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
$('.content_wrapper').hide().html(data).show();
$('#content_overlay').hide();
} else {
$('.content_wrapper').fadeOut().html(data).hide().fadeIn();
$('#content_overlay').fadeOut();
}
$('.queue_loading').hide();
console.log('success ended');
},
error: function(xhr,status,error) {
/*
* The below console logs do not fire when the problem is occuring.
*/
console.log('ERROR');
console.log('xhr: ' + xhr);
console.log('status: ' + status);
console.log('error: ' + error);
$('#map-canvas').remove();
$.get('inc.404.php', function(data) {
if($.browser.msie && parseInt($.browser.version, 10) === 7) {
$('.content_wrapper').hide().html(data).show();
} else {
$('.content_wrapper').fadeOut().html(data).hide().fadeIn();
}
});
if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
$('#content_overlay').hide();
} else {
$('#content_overlay').fadeOut();
}
$('.queue_loading').hide();
},
complete: function(data) {
console.log(data);
ajax_loading = false;
set_tooltips();
}
});
if(changeHash != false) {
window.location.hash = "!" + href;
}
}
</code></pre>
<p><strong>Edit 2:</strong></p>
<p>After putting several console log's through the function, to see at which point it breaks. The problem decided to disappear. For what reason would adding console logs to the function prevent this issue from occurring?</p>
<p>I'm currently waiting an hour or so to re-test it without the console logs to make sure it isn't a red herring.</p>
<p><strong>Edit 3:</strong></p>
<p>After putting in console logs in the error callback of the AJAX request, it seems that the error callback is not firing. Not quite sure where to look now - as if it was a success, it would surely return the content.</p>
| 3 | 2,178 |
How to have two different stroke type using Paint class?
|
<p>The image (white one) is actually how I want to build that blue container.</p>
<p>So, How can I get two different stroke type (bottom: Dash, other: solid).</p>
<p>Using paint like this</p>
<pre class="lang-dart prettyprint-override"><code>Paint paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 10.0
..strokeJoin = StrokeJoin.miter
..color = Colors.black;
</code></pre>
<p><strong>What I've got</strong></p>
<p><a href="https://i.stack.imgur.com/aKGSE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aKGSE.png" alt="What I got. " /></a></p>
<p><strong>What I want</strong></p>
<p><a href="https://i.stack.imgur.com/YHCe0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YHCe0.png" alt="What I want." /></a></p>
<p><strong>Full Code</strong></p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';
class UpperCustomClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
Path _path = Path();
double radius = 44.0, w = size.width, h = size.height;
_path.moveTo(radius, 0); // 1
_path.lineTo(w - radius, 0); // 2
_path.arcToPoint(Offset(w, radius), radius: Radius.circular(radius)); //3
_path.lineTo(w, h - radius); // 4
_path.arcToPoint(Offset(w - radius, h), // 5
radius: Radius.circular(radius),
clockwise: false);
_path.lineTo(radius, h); // 6
_path.arcToPoint(Offset(0, h - radius), //7
radius: Radius.circular(radius),
clockwise: false);
_path.lineTo(0, radius); // 8
_path.arcToPoint(Offset(radius, 0), radius: Radius.circular(radius)); // 9
_path.close();
return _path;
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
class UpperCustomPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Path _path = Path();
double radius = 44.0, w = size.width, h = size.height;
_path.moveTo(radius, 0); // 1
_path.lineTo(w - radius, 0); // 2
_path.arcToPoint(Offset(w, radius), radius: Radius.circular(radius)); //3
_path.lineTo(w, h - radius); // 4
_path.arcToPoint(Offset(w - radius, h), // 5
radius: Radius.circular(radius),
clockwise: false);
_path.lineTo(radius, h); // 6
_path.arcToPoint(Offset(0, h - radius), //7
radius: Radius.circular(radius),
clockwise: false);
_path.lineTo(0, radius); // 8
_path.arcToPoint(Offset(radius, 0), radius: Radius.circular(radius)); // 9
_path.close();
Paint paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 10.0
..strokeJoin = StrokeJoin.miter
..color = Colors.black;
canvas.drawPath(_path, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
</code></pre>
| 3 | 1,184 |
How to add the "Access-Control-Allow-Credentials" request header to a POST request in ASP.NET?
|
<p>So, I am trying to set the "Access-Control-Allow-Credentials", using the <code>HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true"); </code>, but it will only work for my GET requests, but not for my POST ones, and i don't know why.</p>
<p>I've also tried to set those in Startup.cs, as so:</p>
<pre><code> services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.WithOrigins("My_Web_App")
.AllowCredentials()
.AllowAnyMethod()
.AllowAnyHeader();
}));
</code></pre>
<p>And then use it in Configure with <code>app.UseCors("ApiCorsPolicy");</code></p>
<p>That's the code from my controller, so nothing fancy in here, I think:</p>
<pre><code> [ApiController]
[Route("[controller]")]
[EnableCors("ApiCorsPolicy")]
public class UserController : Controller
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[HttpPost("RegisterUser")]
public void GetTournaments([FromBody] UserDTO user)
{
HttpContext.Request.Headers.Add("Access-Control-Allow-Credentials", "true");
_userService.RegisterUser(user);
}
}
</code></pre>
<p>My question is, why I can't put the "Access-Control-Allow-Credentials" header using the <code>Headers.add</code> method( Which works for my GET requests ) ? If that is not the correct approach to it, then how to do it ?
Thanks!</p>
<p>Edit:
I've added all my Startup file, as requested:</p>
<pre><code> public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.WithOrigins("http://"MyIpAddressHere"/")
.AllowAnyMethod()
.AllowAnyHeader();
}));
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingGeneral());
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddSingleton<ITournamentService, TournamentService>();
services.AddSingleton<IUserService, UserService>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "my_app", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "my_app v1"));
}
app.UseRouting();
app.UseCors("ApiCorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
</code></pre>
| 3 | 1,835 |
Gitlab CICD sets wrong service url in the production environment
|
<p>After production deployment the application has not the endpoint of the environment.url from the <code>.gitlab-ci.yml</code>, but a combination of the groupname, projectname and basedomain:
<code><groupname>-<projectname>.basedomain</code>.</p>
<p>The Gitlab project belongs to a Gitlab group, which has an Kubernetes cluster. De group has a basedomain which is used in the <code>.gitlab-ci.yml</code>:</p>
<pre><code>//part of .gitlab-ci.yml
...
apply production secret configuration:
stage: prepare-deploy
extends: .auto-deploy
needs: ["build", "generate production configuration"]
dependencies:
- generate production configuration
script:
- auto-deploy check_kube_domain
- auto-deploy download_chart
- auto-deploy ensure_namespace
- kubectl create secret generic tasker-secrets-development --from-file=config.tar --dry-run -o yaml | kubectl apply -f -
environment:
name: production
url: http://app.$KUBE_INGRESS_BASE_DOMAIN
action: prepare
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
...
</code></pre>
<p>I expected <code>http://app.$KUBE_INGRESS_BASE_DOMAIN</code> as the endpoint for the application.</p>
<p>The Ingress (I removed the minio part):</p>
<pre><code>
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: {{ template "fullname" . }}
labels:
app: {{ template "appname" . }}
chart: "{{ .Chart.Name }}-{{ .Chart.Version| replace "+" "_" }}"
release: {{ .Release.Name }}
heritage: {{ .Release.Service }}
annotations:
cert-manager.io/cluster-issuer: {{ .Values.leIssuer }}
acme.cert-manager.io/http01-edit-in-place: "true"
{{- if .Values.ingress.annotations }}
{{ toYaml .Values.ingress.annotations | indent 4 }}
{{- end }}
{{- with .Values.ingress.modSecurity }}
{{- if .enabled }}
nginx.ingress.kubernetes.io/modsecurity-transaction-id: "$server_name-$request_id"
nginx.ingress.kubernetes.io/modsecurity-snippet: |
SecRuleEngine {{ .secRuleEngine | default "DetectionOnly" | title }}
{{- range $rule := .secRules }}
{{ (include "secrule" $rule) | indent 6 }}
{{- end }}
{{- end }}
{{- end }}
{{- if .Values.prometheus.metrics }}
nginx.ingress.kubernetes.io/server-snippet: |-
location /metrics {
deny all;
}
{{- end }}
spec:
{{- if .Values.ingress.tls.enabled }}
tls:
- hosts:
{{- if .Values.service.commonName }}
- {{ template "hostname" .Values.service.commonName }}
{{- end }}
- {{ template "hostname" .Values.service.url }} <<<<<<<<<<<<<<<<<<<
{{- if .Values.service.additionalHosts }}
{{- range $host := .Values.service.additionalHosts }}
- {{ $host }}
{{- end -}}
{{- end }}
secretName: {{ .Values.ingress.tls.secretName | default (printf "%s-cert" (include "fullname" .)) }}
{{- end }}
rules:
- host: {{ template "hostname" .Values.service.url }} <<<<<<<<<<<<<<<<<
http:
&httpRule
paths:
- path: /
backend:
serviceName: {{ template "fullname" . }}
servicePort: {{ .Values.service.externalPort }}
{{- if .Values.service.commonName }}
- host: {{ template "hostname" .Values.service.commonName }}
http:
<<: *httpRule
{{- end -}}
{{- if .Values.service.additionalHosts }}
{{- range $host := .Values.service.additionalHosts }}
- host: {{ $host }}
http:
<<: *httpRule
{{- end -}}
{{- end -}}
</code></pre>
<p>What I have done so far:</p>
<ul>
<li>removed deployment from cluster, cleared the Gitlab runners cache, cleared the Gitlab cluster cache. Deleted the environment (stop and delete). Created a new environment 'production' with the right URL 'Operations>Environments>production>Edit'. After push the url has been replaced with the wrong one.</li>
<li>hard coded the url in Ingress (at the arrows in the snippet), it worked</li>
<li>changed the value in gitlab-ci.yml without http://. No result.</li>
<li>check the use of 'apply production secret configuration' in the gitlab-ci.yml, by adding echo 'message!'. Conclusion: this part of the file is used for production</li>
<li>A CICD variable Settings>CICD: GITLAB_ENVIRONMENT_URL. No effect.</li>
</ul>
<p>UPDATE:
Maybe the <code>.Values.gitlab.app</code> is used for the URL.</p>
| 3 | 1,806 |
How to correct a mess java .class file set or generate a proper .jar archive from a mess .class set?
|
<h1>Background</h1>
<p>I have to contact different kind of Java project with various of build system. Sometimes the directory structure is different from the package hierarchy. So it is difficult to package.</p>
<p>Even if the build system like Maven and Gradle have its own function to pack .jar but it need a qualified internet connection and a giant size of local repository. Hence I usually build the library I need on the desktop in my office. However I spend more time on my laptop which doesn't have such good connection and storage.</p>
<h1>Question</h1>
<p>Is there a stable, compatible and secure way to make .jar package? Or move those .class file to appropriate directory? (An official and mature open source tool is better)</p>
<p>I am a beginner of Java Language, so any point may be helpful for me.</p>
<h2>In order to make it clearly, here I put some examples.</h2>
<h3>Case 1: If there is a tool which can moving (moving or copying) the .class file in correct directory it should behave as below:</h3>
<p>Before operation:</p>
<pre><code>from_root/
├── a.class
├── b.class
├── c.class
├── d.class
├── e.class
└── f.class
</code></pre>
<p>Note in each source file(.java) of .class file, there is package announcement(like <code>package org.hello.world;</code> or <code>package org.hello;</code>)</p>
<p>when typing <code>the_tool ./from_root ./to_root</code> in shell</p>
<p>it will become:</p>
<pre><code>to_root/
└── org
└── hello
├── a.class
├── b.class
└── world
├── c.class
├── d.class
├── e.class
└── f.class
</code></pre>
<h3>Case 2: If there is a tool which can packing correct .jar file from mess .class file directory it should behave as below:</h3>
<p>Before operation:</p>
<pre><code>from_root/
├── a.class
├── b.class
├── c.class
├── d.class
├── e.class
└── f.class
</code></pre>
<p>when typing <code>pack_tool ./from_root ./to_root/pack.jar</code> in shell</p>
<p>A <code>pack.jar</code> will be generate in <code>./to_root</code>.</p>
<p>When add it in Java Build Path of Eclipse, it should be imported and called properly, instead of wrong name-space hierarchy .</p>
<h1>What I have tried</h1>
<h2>For some famous 3rd part library (e.g. apache tika)</h2>
<p>It is build by maven, and I typed <code>cd /path/to/tika-1.18-src/tika-1.18/</code> then I typed <code>mvn package</code>.</p>
<p>Unfortunately, it was failed.</p>
<p>However when I typed <code>mvn compile</code>, everything went right.</p>
<p>Then in order to build .jar package, I typed <code>jar cvf ./build/tika-1.18.jar $(find ./ -name org | grep target)</code> in terminal.</p>
<p>However, the structure inside the .jar package was totally wrong. I couldn't use it in my project.</p>
<p>Then I tried <code>find ./ -name org | grep target | parallel cp {} ./build/ -R -f</code> then <code>cd ./build</code> and finally <code>jar cvf ./tika-1.18.jar org</code>.</p>
<p>It worked. However there is some disadvantage of this method.</p>
<h3>Shortcoming:</h3>
<ol>
<li><p>If the some source file(.java file)'s name include 'target', it will cause big trouble.</p>
</li>
<li><p>If different subproject contain same file it will cause conflict. For example here is the conflict information:
cp: cannot create directory './build/org/apache/tika/batch': File exists
cp: cannot create directory './build/org/apache/tika/language/translate': File exists</p>
</li>
<li><p>This method can only handle the situation which the path of those .class file is partly correct. If all the .class file are located in same directory flatly, it will failed to work.</p>
</li>
</ol>
<h3>Another attemption</h3>
<p>I tried to put the .class file in correct directory according to its binary content.</p>
<p>For example, <code>org.apache.tika.detect.AutoDetectReader</code></p>
<pre><code>$ hexdump -C /path/to/here/EncodingDetector.class
00000000 ca fe ba be 00 00 00 33 00 0e 07 00 0a 07 00 0b |.......3........|
00000010 07 00 0c 01 00 06 64 65 74 65 63 74 01 00 54 28 |......detect..T(|
00000020 4c 6a 61 76 61 2f 69 6f 2f 49 6e 70 75 74 53 74 |Ljava/io/InputSt|
00000030 72 65 61 6d 3b 4c 6f 72 67 2f 61 70 61 63 68 65 |ream;Lorg/apache|
00000040 2f 74 69 6b 61 2f 6d 65 74 61 64 61 74 61 2f 4d |/tika/metadata/M|
00000050 65 74 61 64 61 74 61 3b 29 4c 6a 61 76 61 2f 6e |etadata;)Ljava/n|
00000060 69 6f 2f 63 68 61 72 73 65 74 2f 43 68 61 72 73 |io/charset/Chars|
00000070 65 74 3b 01 00 0a 45 78 63 65 70 74 69 6f 6e 73 |et;...Exceptions|
00000080 07 00 0d 01 00 0a 53 6f 75 72 63 65 46 69 6c 65 |......SourceFile|
00000090 01 00 15 45 6e 63 6f 64 69 6e 67 44 65 74 65 63 |...EncodingDetec|
000000a0 74 6f 72 2e 6a 61 76 61 01 00 27 6f 72 67 2f 61 |tor.java..'org/a|
000000b0 70 61 63 68 65 2f 74 69 6b 61 2f 64 65 74 65 63 |pache/tika/detec|
000000c0 74 2f 45 6e 63 6f 64 69 6e 67 44 65 74 65 63 74 |t/EncodingDetect|
000000d0 6f 72 01 00 10 6a 61 76 61 2f 6c 61 6e 67 2f 4f |or...java/lang/O|
000000e0 62 6a 65 63 74 01 00 14 6a 61 76 61 2f 69 6f 2f |bject...java/io/|
000000f0 53 65 72 69 61 6c 69 7a 61 62 6c 65 01 00 13 6a |Serializable...j|
00000100 61 76 61 2f 69 6f 2f 49 4f 45 78 63 65 70 74 69 |ava/io/IOExcepti|
00000110 6f 6e 06 01 00 01 00 02 00 01 00 03 00 00 00 01 |on..............|
00000120 04 01 00 04 00 05 00 01 00 06 00 00 00 04 00 01 |................|
00000130 00 07 00 01 00 08 00 00 00 02 00 09 |............|
0000013c
</code></pre>
<p>In order to compare I used another .class file <code>org.apache.tika.embedder.Embedder</code></p>
<pre><code>$ hexdump -C ./Embedder.class
00000000 ca fe ba be 00 00 00 33 00 14 07 00 0f 07 00 10 |.......3........|
00000010 07 00 11 01 00 16 67 65 74 53 75 70 70 6f 72 74 |......getSupport|
00000020 65 64 45 6d 62 65 64 54 79 70 65 73 01 00 36 28 |edEmbedTypes..6(|
00000030 4c 6f 72 67 2f 61 70 61 63 68 65 2f 74 69 6b 61 |Lorg/apache/tika|
00000040 2f 70 61 72 73 65 72 2f 50 61 72 73 65 43 6f 6e |/parser/ParseCon|
00000050 74 65 78 74 3b 29 4c 6a 61 76 61 2f 75 74 69 6c |text;)Ljava/util|
00000060 2f 53 65 74 3b 01 00 09 53 69 67 6e 61 74 75 72 |/Set;...Signatur|
00000070 65 01 00 58 28 4c 6f 72 67 2f 61 70 61 63 68 65 |e..X(Lorg/apache|
00000080 2f 74 69 6b 61 2f 70 61 72 73 65 72 2f 50 61 72 |/tika/parser/Par|
00000090 73 65 43 6f 6e 74 65 78 74 3b 29 4c 6a 61 76 61 |seContext;)Ljava|
000000a0 2f 75 74 69 6c 2f 53 65 74 3c 4c 6f 72 67 2f 61 |/util/Set<Lorg/a|
000000b0 70 61 63 68 65 2f 74 69 6b 61 2f 6d 69 6d 65 2f |pache/tika/mime/|
000000c0 4d 65 64 69 61 54 79 70 65 3b 3e 3b 01 00 05 65 |MediaType;>;...e|
000000d0 6d 62 65 64 01 00 76 28 4c 6f 72 67 2f 61 70 61 |mbed..v(Lorg/apa|
000000e0 63 68 65 2f 74 69 6b 61 2f 6d 65 74 61 64 61 74 |che/tika/metadat|
000000f0 61 2f 4d 65 74 61 64 61 74 61 3b 4c 6a 61 76 61 |a/Metadata;Ljava|
00000100 2f 69 6f 2f 49 6e 70 75 74 53 74 72 65 61 6d 3b |/io/InputStream;|
00000110 4c 6a 61 76 61 2f 69 6f 2f 4f 75 74 70 75 74 53 |Ljava/io/OutputS|
00000120 74 72 65 61 6d 3b 4c 6f 72 67 2f 61 70 61 63 68 |tream;Lorg/apach|
00000130 65 2f 74 69 6b 61 2f 70 61 72 73 65 72 2f 50 61 |e/tika/parser/Pa|
00000140 72 73 65 43 6f 6e 74 65 78 74 3b 29 56 01 00 0a |rseContext;)V...|
00000150 45 78 63 65 70 74 69 6f 6e 73 07 00 12 07 00 13 |Exceptions......|
00000160 01 00 0a 53 6f 75 72 63 65 46 69 6c 65 01 00 0d |...SourceFile...|
00000170 45 6d 62 65 64 64 65 72 2e 6a 61 76 61 01 00 21 |Embedder.java..!|
00000180 6f 72 67 2f 61 70 61 63 68 65 2f 74 69 6b 61 2f |org/apache/tika/|
00000190 65 6d 62 65 64 64 65 72 2f 45 6d 62 65 64 64 65 |embedder/Embedde|
000001a0 72 01 00 10 6a 61 76 61 2f 6c 61 6e 67 2f 4f 62 |r...java/lang/Ob|
000001b0 6a 65 63 74 01 00 14 6a 61 76 61 2f 69 6f 2f 53 |ject...java/io/S|
000001c0 65 72 69 61 6c 69 7a 61 62 6c 65 01 00 13 6a 61 |erializable...ja|
000001d0 76 61 2f 69 6f 2f 49 4f 45 78 63 65 70 74 69 6f |va/io/IOExceptio|
000001e0 6e 01 00 27 6f 72 67 2f 61 70 61 63 68 65 2f 74 |n..'org/apache/t|
000001f0 69 6b 61 2f 65 78 63 65 70 74 69 6f 6e 2f 54 69 |ika/exception/Ti|
00000200 6b 61 45 78 63 65 70 74 69 6f 6e 06 01 00 01 00 |kaException.....|
00000210 02 00 01 00 03 00 00 00 02 04 01 00 04 00 05 00 |................|
00000220 01 00 06 00 00 00 02 00 07 04 01 00 08 00 09 00 |................|
00000230 01 00 0a 00 00 00 06 00 02 00 0b 00 0c 00 01 00 |................|
00000240 0d 00 00 00 02 00 0e |.......|
00000247
</code></pre>
<p><strong>What's amazing is the content after "...SourceFile..." is the package location of this class.</strong></p>
<p>It is possible to write a program which can scan every .class file and determine their location in the directory. However, there is Java 9, Java 10 and Java 11 will coming soon. different java version will cause the different binary content of .class files. And it might be different between JDK and OpenJDK. So it is not compatible enough. But on the other hand, it shows that it is possible to determine the package location of a certain .class file without other infomation.</p>
<p><strong>Hope someone can provide some ideas, thanks sincerely!</strong></p>
| 3 | 3,542 |
Undefined function 'fitrsvm' for input arguments of type 'double'
|
<p>I am using Matalb 2014 . on using which function it shows : </p>
<pre><code>which fitrsvm
'fitrsvm' not found.
</code></pre>
<p>fitrsvm is an inbuilt function so why matlab doesn't recognize it?
I want to use svm in regression is there any other way to do it ?</p>
<p>On tying "ver" it shows </p>
<pre><code>MATLAB Version: 8.4.0.150421 (R2014b)
MATLAB License Number: unknown
Operating System: Microsoft Windows 8.1 Pro Version 6.3 (Build 9600)
Java Version: Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
----------------------------------------------------------------------------------------------------
MATLAB Version 8.4 (R2014b)
Simulink Version 8.4 (R2014b)
Bioinformatics Toolbox Version 4.5 (R2014b)
Communications System Toolbox Version 5.7 (R2014b)
Computer Vision System Toolbox Version 6.1 (R2014b)
Control System Toolbox Version 9.8 (R2014b)
Curve Fitting Toolbox Version 3.5 (R2014b)
DSP System Toolbox Version 8.7 (R2014b)
Data Acquisition Toolbox Version 3.6 (R2014b)
Database Toolbox Version 5.2 (R2014b)
Econometrics Toolbox Version 3.1 (R2014b)
Financial Toolbox Version 5.4 (R2014b)
Fixed-Point Designer Version 4.3 (R2014b)
Fuzzy Logic Toolbox Version 2.2.20 (R2014b)
Global Optimization Toolbox Version 3.3 (R2014b)
Image Acquisition Toolbox Version 4.8 (R2014b)
Image Processing Toolbox Version 9.1 (R2014b)
Instrument Control Toolbox Version 3.6 (R2014b)
MATLAB Builder EX Version 2.5.1 (R2014b)
MATLAB Builder JA Version 2.3.2 (R2014b)
MATLAB Builder NE Version 4.2.2 (R2014b)
MATLAB Coder Version 2.7 (R2014b)
MATLAB Compiler Version 5.2 (R2014b)
MATLAB Report Generator Version 4.0 (R2014b)
Mapping Toolbox Version 4.0.2 (R2014b)
Neural Network Toolbox Version 8.2.1 (R2014b)
Optimization Toolbox Version 7.1 (R2014b)
Parallel Computing Toolbox Version 6.5 (R2014b)
Partial Differential Equation Toolbox Version 1.5 (R2014b)
Real-Time Windows Target Version 4.5 (R2014b)
Robust Control Toolbox Version 5.2 (R2014b)
Signal Processing Toolbox Version 6.22 (R2014b)
SimBiology Version 5.1 (R2014b)
SimHydraulics Version 1.15 (R2014b)
SimMechanics Version 4.5 (R2014b)
SimPowerSystems Version 6.2 (R2014b)
Simscape Version 3.12 (R2014b)
Simulink Coder Version 8.7 (R2014b)
Simulink Control Design Version 4.1 (R2014b)
Simulink Real-Time Version 6.1 (R2014b)
Spreadsheet Link EX Version 3.2.2 (R2014b)
Stateflow Version 8.4 (R2014b)
Statistics Toolbox Version 9.1 (R2014b)
Symbolic Math Toolbox Version 6.1 (R2014b)
System Identification Toolbox Version 9.1 (R2014b)
Wavelet Toolbox Version 4.14 (R2014b)
</code></pre>
<p>There is statistics toolbox but no statistics and machine learning toolbox.</p>
| 3 | 2,762 |
Accessing and Modifying AppDelegate OUTSIDE Itself
|
<p>In my <strong>viewController</strong>, there's an object of a custom <strong>PolyShape</strong> class. The main variable of it is the number of sides and this modifies everything else in the app.</p>
<p>I'm trying to use the <strong>AppDelegate</strong> and <strong>NSUserDefaults</strong> to store the number of sides on the <strong>NSUserDefault</strong>, but my problem is communicating between the <strong>AppDelegate</strong> and my <strong>viewController</strong>.</p>
<p>I saw that you can make a call to the <strong>AppDelegate</strong> with this line of code
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
which doesn't seem to work for me.</p>
<p>But supposing this DID work and I was able to call the value out of the AppDelegate, how would I write it back in the the app is about to close? Here's my code so far:</p>
<pre><code>@synthesize window = _window;
@synthesize polySides;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self setPolySides: [[NSUserDefaults standardUserDefaults] integerForKey:@"polysides"]];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
[[NSUserDefaults standardUserDefaults] setInteger: self.polySides forKey:@"polysides"];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
*/
[[NSUserDefaults standardUserDefaults] setInteger: self.polySides forKey:@"polysides"];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
*/
[self setPolySides: [[NSUserDefaults standardUserDefaults] integerForKey:@"polysides"]];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
Save data if appropriate.
See also applicationDidEnterBackground:.
*/
[[NSUserDefaults standardUserDefaults] setInteger:polygon.numberOfSides forKey:@"polysides"];
}
- (void)dealloc {
[_window release];
[super dealloc];
}
</code></pre>
<p><strong>EDIT:</strong> I guess I wasn't clear. What I want to be able to do is the following:</p>
<pre><code>[[NSUserDefaults standardUserDefaults] setInteger: polygon.numberOfSides forKey: @"polysides"];
</code></pre>
<p>where polygon is an object in my controller. Similarly I'd like to be able to do</p>
<pre><code>[polygon.setNumberOfSides: [[NSUserDefaults standardDefaults] integerForKey: @"polysides"];
</code></pre>
| 3 | 1,100 |
Get Mobile Number From Contacts and Block that number in android
|
<p>i want to get a number from user or select a number from contact list and block that number. I am able to get contacts from my contact list with check box, now i want when i click on number and press Block Number the number will be block. I have tried all these links </p>
<p>I am able to block a number define in the code. Now i want to select contact from my contact list and press block number the number will block</p>
<pre><code>public class BlockCallReceiver <MyAdapter> extends BroadcastReceiver{
Context context;
protected static final String TAG = null;
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
protected String toNumbers;
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
clear_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Selection Cleared", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
*//** When 'Done' Button Pushed: **//*
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("03234371984", null, "What's Up!!" , null, null);
String name = null;
String number = null;
long [] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
while(contact.moveToNext()){
name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//name+=name;
number = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//number+=number;
}
Toast.makeText(getApplicationContext(), "Name: " +name + "\n" + "Number: " + number , Toast.LENGTH_LONG).show();
}
}
});
}
private void ClearSelections() {
int count = this.myListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myListView.setItemChecked(i, false);
}
}
@SuppressWarnings("deprecation")
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
private Cursor managedQuery(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle myBundle = intent.getExtras();
if (myBundle != null)
{
System.out.println("--------Not null-----");
try
{
if (intent.getAction().equals("android.intent.action.PHONE_STATE"))
{
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
System.out.println("--------in state-----");
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
// Incoming call
String incomingNumber =intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
System.out.println("03335222339"+incomingNumber);
System.out.println("03234371984"+incomingNumber);
System.out.println("03244211843"+incomingNumber);
System.out.println("03006041071"+incomingNumber);
System.out.println("03056603902"+incomingNumber);
System.out.println("03224444774"+incomingNumber);
// this is main section of the code,. could also be use for particular number.
// Get the boring old TelephonyManager.
TelephonyManager telephonyManager =(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// Get the getITelephony() method
Class<?> classTelephony = Class.forName(telephonyManager.getClass().getName());
Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
// Ignore that the method is supposed to be private
methodGetITelephony.setAccessible(true);
// Invoke getITelephony() to get the ITelephony interface
Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);
// Get the endCall method from ITelephony
Class<?> telephonyInterfaceClass = Class.forName(telephonyInterface.getClass().getName());
Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");
// Invoke endCall()
methodEndCall.invoke(telephonyInterface);
}
}
}
catch (Exception ex)
{ // Many things can go wrong with reflection calls
ex.printStackTrace();
}
}
}
</code></pre>
<p>}</p>
<p><a href="http://androidsourcecode.blogspot.in/2010/10/blocking-incoming-call-android.html" rel="nofollow noreferrer">Block Calls programmatically</a> </p>
<p><a href="http://mfarhan133.wordpress.com/2010/10/15/manipulating-incoming-ougoing-calls-tutorial-for-android/" rel="nofollow noreferrer">Block Calls programmatically</a></p>
<p><img src="https://i.stack.imgur.com/S3SXD.png" alt="When user select a number and press Block button the number will be block"></p>
<p>When user select a number and press Block Number button the number will be block</p>
| 3 | 2,938 |
MySQL deleting records that only exist in child table/cakephp update?
|
<p>I have two Myisam tables, let's say Parent and Child. Parent is created in a perl script. Parent is where the child gets the information(Not for editing) that's all the same, while Child holds information unique to it. Following Cakephp naming conventions, they're connected through the Parent's id field and the child's parent_id. When the Parent table is updated through another application(A record being added via Perl) it shows up in Child but if a record is deleted, Child doesn't update. Is there a way following cakephp conventions to have the table update(Removing the record that was deleted in Parent)?
I do have 'dependent' => true in the parent table for the child? Does that need to be in the child table? Or does that not matter since the table is updated outside of the app?</p>
<p>If nothing else, I can maybe set up a cron job to check the tables periodically, but i'm not sure how to find/delete the records in the child table that no longer exist in the Parent table via <strong>MYSQL</strong>. A combination of joins and where such n such <>? So my question(s) are can i do it with cakephp if the table is updated outside of the app? Or how would I do it with mysql?</p>
<p>Code:</p>
<pre><code><?php
class Drug extends AppModel {
var $name = 'Drug';
var $order = "Drug.generic ASC";
var $useDbConfig = 'default';
var $actsAs = array('ExtendAssociations', 'Containable');
var $hasOne = array(
'FrenchTranslation' => array(
'className' => 'FrenchTranslation',
'dependent' => true
),
'GermanTranslation' => array(
'className' => 'GermanTranslation',
'dependent' => true
),
'SpanishTranslation' => array(
'className' => 'SpanishTranslation',
'dependent' => true
)
);
}
?>
<?php
class FrenchTranslation extends AppModel {
var $name = 'FrenchTranslation';
var $validate = array(
'drug_id'=>array(
'The drug_id must be unique.'=>array(
'rule'=>'isUnique',
'message'=>'The Drug ID must be unique.',
'on'=>'create'
),
'The drug_id must be numeric.'=>array(
'rule'=>array('numeric'),
'message'=>'The Drug ID must be numeric.'
)
),
'id'=>array(
'The id must be unique.'=>array(
'rule'=>'isUnique',
'message'=>'The ID must be unique.',
'on'=>'create'
),
'The id must be numeric.'=>array(
'rule'=>array('numeric'),
'message'=>'The ID must be numeric.'
)
)
);
var $belongsTo = array(
'Drug' => array(
'className' => 'Drug',
'foreignKey' => 'drug_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'User'=>array(
'className'=>'User',
'foreignKey'=>'user_id'
),
);
}
?>
</code></pre>
| 3 | 1,278 |
Grade checking program keeps auto exiting prematurely
|
<p>I am currently trying to learn C++ and I have written the following program. It does what it should successfully, however it keeps auto exiting. I have tried putting a <code>cin</code> at the end and when that didn't work I put a <code>getChar()</code> and it doesn't wait for any input. To be clear, I have had no formal education regarding C++ and this problem has had me stumped. I have tried googling it but all that comes up is it telling me to use either of the things I have already tried. I have commented out the <code>cin</code> breakpoints to show where I put them.</p>
<p>As I said earlier, the actual code for the program is below. Underneath that is the debug log.</p>
<p>For what it's worth, I used Visual Studio to make this.</p>
<p><strong>Edit</strong>: This isn't a duplicate question as I want to be able to go the actual executable, double click it and get it to wait for me to press a key until it exits. With this program even if I go to the actual executable, it still auto exits.</p>
<h2>Code</h2>
<p>Code for the program:</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
// Declare variables for intro
string intro = "Please enter your score.\n";
string prompt = ">>> ";
string nl = "\n";
// Declare grade calculation variables
int initial_grade = 0;
bool temp;
// Declare variables for perfection test
string perfect_score = "You scored perfectly, congratulations!\n";
void perfection_test() {
switch (initial_grade) {
case 100:
cout << perfect_score;
//cin;
}
//cin;
}
int main() {
cout << intro << prompt;
cin >> initial_grade;
cout << nl;
//cin;
perfection_test();
//cin;
}
</code></pre>
<p>Debug:</p>
<pre><code>'GradingProgram.exe' (Win32): Loaded 'C:\Users\student\Desktop\khush\GradingProgram\Debug\GradingProgram.exe'. Symbols loaded.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\vcruntime140d.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\advapi32.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcrt.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sechost.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rpcrt4.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sspicli.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptbase.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcryptprimitives.dll'. Cannot find or open the PDB file.
'GradingProgram.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel.appcore.dll'. Cannot find or open the PDB file.
The thread 0x134c has exited with code 0 (0x0).
The thread 0x2110 has exited with code 0 (0x0).
The thread 0x210c has exited with code 0 (0x0).
The program '[9092] GradingProgram.exe' has exited with code 0 (0x0).
</code></pre>
| 3 | 1,247 |
How to add parent network to existing vapp via REST api when fenceMode is isolated
|
<p>I have a vapp instantiated on vcd host via my template, vapp network config section xml looks like:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<NetworkConfigSection xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" type="application/vnd.vmware.vcloud.networkConfigSection+xml" href="https://mycloud.stratogen.com/api/vApp/vapp-0991d221-1b3e-47aa-ab69-2d8f300f454d/networkConfigSection/" ovf:required="false" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.dmtf.org/ovf/envelope/1 http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd http://www.vmware.com/vcloud/v1.5 http://mycloud.stratogen.com/api/v1.5/schema/master.xsd">
<ovf:Info>The configuration parameters for logical networks</ovf:Info>
<Link rel="edit" type="application/vnd.vmware.vcloud.networkConfigSection+xml" href="https://mycloud.stratogen.com/api/vApp/vapp-0991d221-1b3e-47aa-ab69-2d8f300f454d/networkConfigSection/"/>
<NetworkConfig networkName="VM Network">
<Link rel="repair" href="https://mycloud.stratogen.com/api/admin/network/86d21d4f-0b15-44e3-877e-5b5160ea9271/action/reset"/>
<Description>The VM Network network</Description>
<Configuration>
<IpScope>
<IsInherited>false</IsInherited>
<Gateway>192.168.254.1</Gateway>
<Netmask>255.255.255.0</Netmask>
<IpRanges>
<IpRange>
<StartAddress>192.168.254.100</StartAddress>
<EndAddress>192.168.254.199</EndAddress>
</IpRange>
</IpRanges>
</IpScope>
<FenceMode>isolated</FenceMode>
<RetainNetInfoAcrossDeployments>false</RetainNetInfoAcrossDeployments>
</Configuration>
<IsDeployed>false</IsDeployed>
</NetworkConfig>
</NetworkConfigSection>
</code></pre>
<p>So, I have read official vmware documentation about NetworkConfigSection and tried to add ParentNetwork and switch to natRouted fence mode exactly as it was in example:
<a href="https://pubs.vmware.com/vcd-51/index.jsp?topic=%2Fcom.vmware.vcloud.api.doc_51%2FGUID-92622A15-E588-4FA1-92DA-A22A4757F2A0.html" rel="nofollow">https://pubs.vmware.com/vcd-51/index.jsp?topic=%2Fcom.vmware.vcloud.api.doc_51%2FGUID-92622A15-E588-4FA1-92DA-A22A4757F2A0.html</a></p>
<p>So, now my XML looks like:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<NetworkConfigSection xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" type="application/vnd.vmware.vcloud.networkConfigSection+xml" href="https://mycloud.stratogen.com/api/vApp/vapp-0991d221-1b3e-47aa-ab69-2d8f300f454d/networkConfigSection/" ovf:required="false" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.dmtf.org/ovf/envelope/1 http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd http://www.vmware.com/vcloud/v1.5 http://mycloud.stratogen.com/api/v1.5/schema/master.xsd">
<ovf:Info>The configuration parameters for logical networks</ovf:Info>
<Link rel="edit" type="application/vnd.vmware.vcloud.networkConfigSection+xml" href="https://mycloud.stratogen.com/api/vApp/vapp-0991d221-1b3e-47aa-ab69-2d8f300f454d/networkConfigSection/"/>
<NetworkConfig networkName="VM Network">
<Link rel="repair" href="https://mycloud.stratogen.com/api/admin/network/86d21d4f-0b15-44e3-877e-5b5160ea9271/action/reset"/>
<Description>The VM Network network</Description>
<Configuration>
<IpScopes>
<IpScope>
<IsInherited>false</IsInherited>
<Gateway>192.168.254.1</Gateway>
<Netmask>255.255.255.0</Netmask>
<IpRanges>
<IpRange>
<StartAddress>192.168.254.100</StartAddress>
<EndAddress>192.168.254.199</EndAddress>
</IpRange>
</IpRanges>
</IpScope>
</IpScopes>
<FenceMode>natRouted</FenceMode>
<ParentNetwork
type="application/vnd.vmware.vcloud.network+xml"
name="Internet"
href="https://vcloud.example.com/api/network/54" />
<RetainNetInfoAcrossDeployments>false</RetainNetInfoAcrossDeployments>
</Configuration>
<IsDeployed>false</IsDeployed>
</NetworkConfig>
</NetworkConfigSection>
</code></pre>
<p>After that I submitted PUT request to edit URL and I got an error:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Error xmlns="http://www.vmware.com/vcloud/v1.5" minorErrorCode="BAD_REQUEST" message="Bad request
- Unexpected JAXB Exception
- cvc-complex-type.2.4.a: Invalid content was found starting with element \'ParentNetwork\'. One of \'{&quot;http://www.vmware.com/vcloud/v1.5&quot;:RetainNetInfoAcrossDeployments, &quot;http://www.vmware.com/vcloud/v1.5&quot;:Features, &quot;http://www.vmware.com/vcloud/v1.5&quot;:SyslogServerSettings, &quot;http://www.vmware.com/vcloud/v1.5&quot;:RouterInfo}\' is expected." majorErrorCode="400" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/vcloud/v1.5 http://mycloud.stratogen.com/api/v1.5/schema/master.xsd"></Error>
</code></pre>
<p>How could I add parent network to existing vApp using vCloudDirector rest api?</p>
<p>Thanks.</p>
| 3 | 2,890 |
compareTo with objects returns a false while it is true
|
<p>I am trying to check whether my levelorder of my Binary Search Tree is equal to the other one. To do this, I tried to make a compareTo method. I only give equal values to the method, but it keeps on saying the condition is false. When I place breakpoints, I see that the values are still equal. I am probably not understanding it correctly. Does anyone know how to solve this?</p>
<p>Here is what I did, as you can see below, the compareTo returns a 1 instead of a 0:</p>
<pre><code>import edu.princeton.cs.algs4.BST;
import java.util.*;
public class MyBST implements Comparable<MyBST>{
private Object e;
public MyBST(Object e){
this.e = e;
}
private Object getE(){
return e;
}
public static void main(String[] args) {
int size = 4;
Random r = new Random();
Set<Integer> tes = new LinkedHashSet<>(size);
Stack<Integer> stack = new Stack<>();
while (tes.size() < size) {
tes.add(r.nextInt(10));
}
System.out.println("possible combinations");
Set<Stack<Integer>> combos = combos(tes, stack, tes.size());
Object[] arr = combos.toArray();
List<String> d = new ArrayList<>();
for (Object s : arr) {
String b = s.toString();
b = b.replaceAll("\\[", "").replaceAll("\\]", "");
d.add(b);
}
int index = 0;
do {
BST<String, Integer> bst1 = new BST<String, Integer>();
BST<String, Integer> bst2 = new BST<String, Integer>();
String key1 = d.get(index);
String key2 = d.get(index);
key1 = key1.replaceAll(" ", "");
String[] m = key1.split(",");
key2 = key2.replaceAll(" ", "");
String[] n = key2.split(",");
System.out.println("1e order");
for (int j = 0; j < m.length; j++) {
System.out.println(m[j]);
bst1.put(m[j], 0);
}
System.out.println("2e order");
for (int j = 0; j < n.length; j++) {
System.out.println(n[j]);
bst2.put(n[j], 0);
}
System.out.println("levelorder 1e BST");
MyBST e = new MyBST(bst1.levelOrder());
MyBST y = new MyBST(bst2.levelOrder());
System.out.println(bst1.levelOrder());
System.out.println("levelorder 2e BST");
System.out.println(bst2.levelOrder());
System.out.println(e.compareTo(y) + "\n");
index++;
} while (index < arr.length - 1);
}
public static Set<Stack<Integer>> combos(Set<Integer> items, Stack<Integer> stack, int size) {
Set<Stack<Integer>> set = new HashSet<>();
if (stack.size() == size) {
set.add((Stack) stack.clone());
}
Integer[] itemz = items.toArray(new Integer[0]);
for (Integer i : itemz) {
stack.push(i);
items.remove(i);
set.addAll(combos(items, stack, size));
items.add(stack.pop());
}
return set;
}
@Override
public int compareTo(MyBST o) {
if (this.e == o.e) {
return 0;
}
else
return 1;
}
}
</code></pre>
<p>Here you can find the BST.java class: <a href="https://algs4.cs.princeton.edu/32bst/BST.java.html" rel="nofollow noreferrer">BST.java</a></p>
<p>And the output is something like:</p>
<p><a href="https://i.stack.imgur.com/irtKk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/irtKk.png" alt="enter image description here" /></a></p>
<p>The breakpoint at the compareTo method says:</p>
<p><a href="https://i.stack.imgur.com/17Y2G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/17Y2G.png" alt="enter image description here" /></a></p>
| 3 | 2,012 |
vector compiler error for different variable type
|
<p>The goal of this assignment for my class is to ask the user for how many students are in the class.
Using the Vector library create a vector of Strings to hold the students names.
Create a vector of type double to hold a students grade average.</p>
<p>I have a couple two compiler errors that are preventing my code from running. Line 73 & 83. The following errors I am given:</p>
<pre><code>main.cpp: In function ‘void add_student()’: main.cpp:73:11: error: request for member ‘push_back’ in ‘grade’, which is of non-class type ‘double’
73 | grade.push_back(grade);
| ^~~~~~~~~
main.cpp: In function ‘void remove_student()’: main.cpp:83:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<std::__cxx11::basic_string<char> >::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
83 | for (int i = 0; i < students.size(); i++)
| ~~^~~~~~~~~~~~~~~~~**
</code></pre>
<p>Any help would be much appreciated. Below is my entire code</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
vector<string> students;
vector<double> grade;
void add_student();
void remove_student();
void menu();
void print_summary();
int main()
{
int numStudent;
char menuSelection;
cout << "Welcome to the Student roaster!" << endl;
cout << "How many students are in your class?:" << endl;
cin >> numStudent;
for (int i = 0; i < numStudent; i++)
{
add_student();
}
cout << "Thank you for entering class information!" << endl;
//calls menu for the user
menu();
while (1)
{
cout << "selection:" << endl;
cin >> menuSelection;
if (menuSelection == 'a')
{
add_student();
}
else if (menuSelection == 'r')
{
remove_student();
}
else if (menuSelection == 'p')
{
print_summary();
}
else if (menuSelection == 'm')
{
menu();
}
else if (menuSelection == 'q')
break;
else
cout << "Not a valid selection" << endl;
}
return 0;
}
void add_student()
{
string firstName, lastName;
double grade;
//ask for student info
cout << "Please enter student (Fisrt Last Grade) info: " << endl;
cin >> firstName >> lastName >> grade;
firstName += " ";
firstName += lastName;
//inserts new student
students.push_back(firstName);
grade.push_back(grade);
}
void remove_student()
{
string first, last;
cout << "Enter the student (First Last) to remove :\n";
cin >> first >> last;
first += " ";
first += last;
int loc = 0;
for (int i = 0; i < students.size(); i++)
{
if (students[i] == first)
{ // finding the location to erase
loc = i;
break;
}
}
students.erase(students.begin() + loc); //removing using erase function
grade.erase(grade.begin() + loc);
}
void menu()
{
cout << "Please choose one of the following options:\n";
cout << "a: add a student\n";
cout << "r: remove a student\n";
cout << "p: print the class summary\n";
cout << "m: print menu\n";
cout << "q: quit program\n";
}
void print_summary()
{
cout << "class summary" << endl;
cout << "--------------------------------" << endl;
cout << "Name" << setw(20) << "Grade" << endl;
cout << "-------" << setw(20) << "--------" << endl;
int n = students.size();
double total = 0;
//cycles through each student
for (int i = 0; i < n; i++)
{
int temp = students[i].size();
int loc = 20 - temp;
cout << students[i] << setw(loc) << grade[i] << endl;
total += grade[i];
}
cout << "Number of students: " << endl;
cout << "------------------" <<endl;
cout << n << " " << endl;
total = (total) / n;
cout << "Average Grade: " << endl;
cout << "--------------" << endl;
//limits the deciaml places to 2
cout << fixed << setprecision(2) << total << " " << endl;
}
</code></pre>
| 3 | 2,191 |
Autolayout redraws when animating
|
<p>So I have a <strong>Parent</strong> (ViewController) and a <strong>SubView</strong> (Slider) in which the SubView has a datePicker and a button. </p>
<p>The Subview itself is a class that uses auto layout to put the datePicker and Button in place so when this view is called, the datePicker and button are in place universally with different screen size of iPhones.</p>
<p><strong>The Problem:</strong> When this subView (Slider) is called from the parent view, it seems that the components inside this view are drawn on runtime from left to right and it looks bad in my opinion.</p>
<p>Below is a bit of the code I have and **I have commented out several parts of the components to begin solving the button issue first ** with no success yet.</p>
<pre><code>import UIKit
class Slider: UIView {
var title : UILabel = UILabel()
var testPicker : UIDatePicker = UIDatePicker()
var txtfield : UITextField = UITextField()
var SVSetButton: UIButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
//self.title.frame = CGRect(x: 50, y: 30, width: 200, height: 40)
self.title.translatesAutoresizingMaskIntoConstraints = false
self.title.text = "Child Object"
self.title.textAlignment = .center
self.title.font = UIFont(name: "avenir", size: 26.0)
self.txtfield.frame = CGRect(x: 0, y: 20, width: self.self.bounds.width, height: 35)
self.txtfield.placeholder = "Text"
self.testPicker.translatesAutoresizingMaskIntoConstraints = false
self.testPicker.backgroundColor = UIColor.red
self.SVSetButton.translatesAutoresizingMaskIntoConstraints = false
self.SVSetButton.setTitle("Done", for: .normal)
self.SVSetButton.backgroundColor = UIColor.alizarinColor()
//self.SVSetButton.addTarget(self, action: #selector(DateView.SaveRemindingData), for: .touchUpInside)
//self.addSubview(testPicker)
self.addSubview(SVSetButton)
// self.addSubview(txtfield)
}
override func willMove(toSuperview newSuperview: UIView?) {
self.title.layoutIfNeeded()
self.SVSetButton.layoutIfNeeded()
}
override func layoutSubviews() {
super.layoutSubviews()
// let centerX = NSLayoutConstraint(item: self.title, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
//
//
// let centerBottom = NSLayoutConstraint(item: self.title, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: -10)
//
// let height = NSLayoutConstraint(item: self.title, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 60)
//
// let width = NSLayoutConstraint(item: self.title, attribute: NSLayoutAttribute.width, relatedBy: .equal, toItem: self.self, attribute: NSLayoutAttribute.width, multiplier: 1, constant: -15)
// MARK: - Date picker test
// let pcenterX = NSLayoutConstraint(item: self.testPicker, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
//
//
// let pcenterBottom = NSLayoutConstraint(item: self.testPicker, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.SVSetButton, attribute: NSLayoutAttribute.top, multiplier: 1, constant: -10)
//
// let pheight = NSLayoutConstraint(item: self.testPicker, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 160)
//
// let pwidth = NSLayoutConstraint(item: self.testPicker, attribute: NSLayoutAttribute.width, relatedBy: .equal, toItem: self.self, attribute: NSLayoutAttribute.width, multiplier: 1, constant: -15)
let buttonCenterX = NSLayoutConstraint(item: self.SVSetButton, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let buttonCenterBottom = NSLayoutConstraint(item: self.SVSetButton, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -10)
let buttonHeight = NSLayoutConstraint(item: self.SVSetButton, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
let buttonWidth = NSLayoutConstraint(item: self.SVSetButton, attribute: NSLayoutAttribute.width, relatedBy: .equal, toItem: self.self, attribute: NSLayoutAttribute.width, multiplier: 1, constant: -15)
self.addConstraints([/*pcenterX, pcenterBottom, pheight, pwidth,*/ buttonCenterX, buttonCenterBottom, buttonHeight, buttonWidth])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
</code></pre>
<p>And here is the snippet that invokes this slider in the parent view using auto layout.</p>
<p><strong>ViewController (Parent)</strong></p>
<pre><code> func invokeRemindForm(){
self.card.textpad.resignFirstResponder()
self.sliderBackground.addGestureRecognizer(dismissTap)
slideView = Slider(frame: CGRect(x: 0, y: UIScreen.main.bounds.height, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2))
slideView?.translatesAutoresizingMaskIntoConstraints = false
sliderOpen = true
if sliderOpen {
self.remindButton.isEnabled = false
}
if let slider = slideView {
// view.addSubview(slider)
view.addSubview(sliderBackground)
self.sliderBackground.addSubview(slider)
sliderBackground.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
// This value may not be working entirely
sliderBackground.alpha = 1.0
sliderBackground.backgroundColor = UIColor.black.withAlphaComponent(0.7)
// Autolayout
let leading = NSLayoutConstraint(item: self.slideView!, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0)
let trailing = NSLayoutConstraint(item: self.slideView!, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0)
let bottom = NSLayoutConstraint(item: self.slideView!, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0)
let height = NSLayoutConstraint(item: self.slideView!, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.height/2)
self.slideView?.layoutIfNeeded()
self.view.addConstraints([leading, trailing, bottom, height])
}
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {
self.view.layoutIfNeeded()
})
}
</code></pre>
<p>What am I doing wrong? I seem to think that auto layout in the slider should hold all the components in place and should not draw themselves when the view is called. Any suggestions? </p>
| 3 | 2,754 |
What is the easiest way to differentiate between function calls from three different jqxgrid calls?
|
<p>I have three jqxgrids that call the same function to create a new account (which is a jq ui dialogue). What is the easiest or best way to differentiate between which grid was called.</p>
<p>My code:</p>
<pre><code>$("#divNewAccountDetails").dialog({
autoOpen: F,
modal: T,
title: "New Account",
width: 600,
close: function () {
},
buttons: {
"Save & Close": function () {
$(this).dialog("close");
var _Object, indexes, _row1, _row2, _row3;
_Object = $("#jqxAccountDropdownGrid");
indexes = $(_Object).jqxGrid('selectedrowindexes');
for (var index in indexes) {
_row1 = $(_Object).jqxGrid('getrowdata', index);
if (typeof _row1["AccountName"] !== "undefind") {
if (_row1["AccountName"].toString().toLowerCase() === "new") {
alert("Account");
$(_Object).jqxGrid('clearselection');
break;
}
}
}
_Object = $("#jqxPurchaseAccountDropdownGrid");
indexes = $(_Object).jqxGrid('selectedrowindexes');
for (var index in indexes) {
_row2 = $(_Object).jqxGrid('getrowdata', index);
if (typeof _row2["AccountName"] !== "undefind") {
if (_row2["AccountName"].toString().toLowerCase() === "new") {
alert("Purchase Account");
$(_Object).jqxGrid('clearselection');
break;
}
}
}
_Object = $("#jqxSalesAccountDropdownGrid");
indexes = $(_Object).jqxGrid('selectedrowindexes');
for (var index in indexes) {
_row3 = $(_Object).jqxGrid('getrowdata', index);
if (typeof _row3["AccountName"] !== "undefind") {
if (_row3["AccountName"].toString().toLowerCase() === "new") {
alert("Sales Account");
$(_Object).jqxGrid('clearselection');
break;
}
}
}
},
Cancel: function () {
$(this).dialog("close");
}
}
});
</code></pre>
<p>So basically the Grids are bound to a column change and when that columns value is <code>"new"</code>, the script triggers the dialogue (code above). What is happening is that when I click the <code>Save & Close</code> button, I get <code>"Uncaught TypeError: Cannot read property 'toString' of undefined"</code>. What I do not understand is that I am using a logic test to check for undefined and it appears to be executing the if block anyway which it shouldn't.</p>
| 3 | 1,389 |
Value not available within a private class
|
<p>My php script has two sql statements. The second one (connection 2) is not executing. I believe its because the value for 'id' is not set since it's within a private class. I was wondering if anyone had a suggestion on how to fix this?</p>
<pre><code> <?php
//process pdf file upload
if (isset($_FILES["flyer"]["name"])); {
$allowedExtsf = array("pdf");
$tempf = explode(".", $_FILES["flyer"]["name"]);
$extensionf = end($tempf);
if (($_FILES["flyer"]["type"] == "application/pdf") && ($_FILES["flyer"]["size"] < 524288000) && in_array($extensionf, $allowedExtsf))
{
if (file_exists("../flyers/" . $_FILES["flyer"]["name"]))
{
//if file exists, delete the file on the server
unlink("../flyers/" . $_FILES["flyer"]["name"]);
}
//move currrent pdf to the flyers folder
move_uploaded_file($_FILES["flyer"]["tmp_name"],"../flyers/" . $_FILES["flyer"]["name"]);
//Make url of pdf file
$ad_link="http://www.website.com/flyers/" . $_FILES["flyer"]["name"];
//SQL statement 1, insert all form fields, file url and current date time
}
else {
$ad_link = NULL;
}
require('../dbcon2.php');
//Connection 1
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO listings (title, address, lot_size, zoning, build_size, sale_price, lease_price, comment, transaction, ad_link, date_added) VALUES (:title, :address, :lot_size, :zoning, :build_size, :sale_price, :lease_price, :comment, :transaction, :ad_link, now())");
//Bind
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':address', $_POST['address']);
$stmt->bindParam(':lot_size', $_POST['lot_size']);
$stmt->bindParam(':zoning', $_POST['zoning']);
$stmt->bindParam(':build_size', $_POST['build_size']);
$stmt->bindParam(':sale_price', $_POST['sale_price']);
$stmt->bindParam(':lease_price', $_POST['lease_price']);
$stmt->bindParam(':comment', $_POST['comment']);
$stmt->bindParam(':transaction', $_POST['transaction']);
$stmt->bindParam(':ad_link', $ad_link);
$stmt->execute();
$id = $conn->lastInsertId();
$title = $_POST['title'];
$address = $_POST['address'];
$lot_size = $_POST['lot_size'];
$zoning = $_POST['zoning'];
$build_size = $_POST['build_size'];
$sale_price = $_POST['sale_price'];
$lease_price = $_POST['lease_price'];
$comment = $_POST['comment'];
$transaction = $_POST['transaction'];
$conn = null;
}
//Create class
class CropAvatar {
private $src;
private $id;
private $title;
private $address;
private $lot_size;
private $zoning;
private $build_size;
private $sale_price;
private $lease_price;
private $comment;
private $transaction;
private $data;
private $file;
private $dst;
private $type;
private $extension;
//location to save original image
private $srcDir = '../0images/listimg/orig';
//location to save cropped image
private $dstDir = '../0images/listimg/mod';
private $msg;
//Add to consttruct
function __construct($src, $data, $file, $id, $title, $address, $lot_size, $zoning, $build_size, $sale_price, $lease_price, $comment, $transaction) {
$this -> setSrc($src);
$this -> setData($data);
$this -> setFile($file);
$this -> setId($id);
$this -> setTitle($title);
$this -> setAddress($address);
$this -> setLot_size($lot_size);
$this -> setZoning($zoning);
$this -> setBuild_size($build_size);
$this -> setSale_price($sale_price);
$this -> setLease_price($lease_price);
$this -> setComment($comment);
$this -> setTransaction($transaction);
$this -> crop($this -> src, $this -> dst, $this -> data, $this -> lastid, $this -> title, $this -> address, $this -> lot_size, $this -> zoning, $this -> build_size, $this -> sale_price, $this -> lease_price, $this -> comment, $this -> transaction);
}
public function setId($id) {
$this->id = $id;
}
public function setTitle($title) {
$this->title = $title;
}
public function setAddress($address) {
$this->address = $address;
}
public function setLot_size($lot_size) {
$this->lot_size = $lot_size;
}
public function setZoning($zoning) {
$this->zoning = $zoning;
}
public function setBuild_size($build_size) {
$this->build_size = $build_size;
}
public function setSale_price($sale_price) {
$this->sale_price = $sale_price;
}
public function setLease_price($lease_price) {
$this->lease_price = $lease_price;
}
public function setComment($comment) {
$this->comment = $comment;
}
public function setTransaction($transaction) {
$this->transaction = $transaction;
}
//NNEED TO SET THE VARIABLES
private function setSrc($src)
{
if (!empty($src))
{
$type = exif_imagetype($src);
if ($type)
{
$this -> src = $src;
$this -> type = $type;
$this -> extension = image_type_to_extension($type);
$this -> setDst();
}
}
}
private function setData($data)
{
if (!empty($data))
{
$this -> data = json_decode(stripslashes($data));
}
}
private function setFile($file)
{
$errorCode = $file['error'];
if ($errorCode === UPLOAD_ERR_OK)
{
$type = exif_imagetype($file['tmp_name']);
if ($type)
{
$dir = $this -> srcDir;
if (!file_exists($dir))
{
mkdir($dir, 0777);
}
$currdate=date('YmdHis');
$extension = image_type_to_extension($type);
$src = $dir . '/' . $currdate . $extension;
if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {
if (file_exists($src))
{
unlink($src);
}
$result = move_uploaded_file($file['tmp_name'], $src);
//Connection 2 - Update sql row according to row id with the url of cropped image
$listing_img="http://www.website.com/0images/listimg/mod/" . $currdate . $extension;
$GLOBALS[ 'listing_img' ];
require('../dbcon2.php');
$GLOBALS[ 'id' ];
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="UPDATE listings SET listing_img='$listing_img' WHERE id=$this->id";
$conn->exec($sql);
$conn = null;
//Error handling
if ($result) {
$this -> src = $src;
$this -> type = $type;
$this -> extension = $extension;
$this -> setDst();
} else {
$this -> msg = 'Failed to save image file';
}
} else {
$this -> msg = 'Please upload image with the following types only: JPG, PNG, GIF';
}
} else {
$this -> msg = 'Please upload image file';
}
} else {
$this -> msg = $this -> codeToMessage($errorCode);
}
}
private function setDst() {
$dir = $this -> dstDir;
if (!file_exists($dir)) {
mkdir($dir, 0777);
}
$this -> dst = $dir . '/' . date('YmdHis') . $this -> extension;
}
private function crop($src, $dst, $data) {
if (!empty($src) && !empty($dst) && !empty($data)) {
switch ($this -> type) {
case IMAGETYPE_GIF:
$src_img = imagecreatefromgif($src);
break;
case IMAGETYPE_JPEG:
$src_img = imagecreatefromjpeg($src);
break;
case IMAGETYPE_PNG:
$src_img = imagecreatefrompng($src);
break;
}
if (!$src_img) {
$this -> msg = "Failed to read the image file";
return;
}
$dst_img = imagecreatetruecolor(220, 220);
$result = imagecopyresampled($dst_img, $src_img, 0, 0, $data -> x, $data -> y, 220, 220, $data -> width, $data -> height);
if ($result) {
switch ($this -> type) {
case IMAGETYPE_GIF:
$result = imagegif($dst_img, $dst);
break;
case IMAGETYPE_JPEG:
$result = imagejpeg($dst_img, $dst);
break;
case IMAGETYPE_PNG:
$result = imagepng($dst_img, $dst);
break;
}
if (!$result) {
$this -> msg = "Failed to save the cropped image file";
}
} else {
$this -> msg = "Failed to crop the image file";
}
imagedestroy($src_img);
imagedestroy($dst_img);
}
}
private function codeToMessage($code) {
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'The uploaded file was only partially uploaded';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'No file was uploaded';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Missing a temporary folder';
break;
case UPLOAD_ERR_CANT_WRITE:
$message = 'Failed to write file to disk';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'File upload stopped by extension';
break;
default:
$message = 'Unknown upload error';
}
return $message;
}
public function getResult() {
return !empty($this -> data) ? $this -> dst : $this -> src;
}
public function getMsg() {
return $this -> msg;
}
public function getId() {
return $this -> id;
}
public function getTitle() {
return $this->title;
}
public function getAddress() {
return $this->address;
}
public function getLot_size() {
return $this->lot_size;
}
public function getZoning() {
return $this->zoning;
}
public function getBuild_size() {
return $this->build_size;
}
public function getSale_price() {
return $this->sale_price;
}
public function getLease_price() {
return $this->lease_price;
}
public function getComment() {
return $this->comment;
}
public function getTransaction() {
return $this->transaction;
}
}
$crop = new CropAvatar($_POST['avatar_src'], $_POST['avatar_data'], $_FILES['avatar_file'], $id, $title, $address, $lot_size, $zoning, $build_size, $sale_price, $lease_price, $comment, $transaction);
$response = array(
'state' => 200,
'message' => $crop -> getMsg(),
'result' => $crop -> getResult(),
'id' => $crop -> getId(),
'title' => $crop -> getTitle(),
'address' => $crop -> getAddress(),
'lot_size' => $crop -> getLot_size(),
'zoning' => $crop -> getZoning(),
'build_size' => $crop -> getBuild_size(),
'sale_price' => $crop -> getSale_price(),
'lease_price' => $crop -> getLease_price(),
'comment' => $crop -> getComment(),
'Transaction' => $crop -> getTransaction()
);
echo json_encode($response);
?>
</code></pre>
| 3 | 8,754 |
Not receiving any data from callback url. Where am I going wrong in Android?
|
<p>This is my URL post: </p>
<pre><code> String urlParameters = "&consumer_key="+AppSession.getPocketConsumerKey()+"&client_secret="+AppSession.getPocketRedirectUri();
String request = "https://getpocket.com/v3/oauth/request";
URL url;
try {
url = new URL(request);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("X-Accept","application/x-www-form-urlencoded");
connection.setUseCaches (false);
connection.connect();
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
Log.d("urlparmas",urlParameters);
wr.flush();
wr.close();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.d( "response",response.toString());
} catch (Exception e) {
e.printStackTrace();
}
</code></pre>
<p>My redirect Uri: MyApp://callback</p>
<pre><code><activity android:name="com.app.account.Register" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="MyApp" android:host="callback"/>
</intent-filter>
</activity>
</code></pre>
<p>So, I am just not getting any reply from the callback url. Wondering where I've gone wrong in the code. </p>
<p>Edit: </p>
<pre><code>InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.d( "response",response.toString());
</code></pre>
<p>This produces the error. </p>
| 3 | 1,162 |
Include php is throwing result in header
|
<p>I am trying to use the php code to display a comment box on a page:</p>
<pre><code>$object_id = 'article_12';
include('commentanything/php/loadComments.php');
</code></pre>
<p>For some reason the comment box is not appearing where i want it to appear,it keeps throwing the comment box to header, is there any way i can make it appear exactly where i want it to?, here is where i am trying to use it(not a complete code):</p>
<pre><code> <!--<h1 align="center" style="font-size:1.2em"><strong>'.$row['title'].'</strong></h1>-->
<div class="song-art"><a href="'.$this->url.'/mp3download/'.$row['id'].'/'.$this->genSlug($row['title']).'.html"><img src="'.$this->url.'/thumb.php?src='.$row['art'].'&t=m&w=112&h=112" id="song-art'.$row['id'].'" title="'.$row['title'].'" alt="'.$row['title'].'"/></a></div>
<div class="song-top">
<div class="song-timeago">
<a href="'.$this->url.'/mp3download/'.$row['id'].'/'.$this->genSlug($row['title']).'.html"><span id="time'.$row['id'].'">
<div class="timeago'.$b.'" title="'.$time.'">
'.$time.'
</div>
</span>
</a>
</div>
<div data-track-name="'.$row['name'].'" data-track-id="'.$row['id'].'" id="play'.$row['id'].'" class="track song-play-btn">
</div>
<div class="song-titles">
<div class="song-author"><a onmouseover="profileCard('.$row['idu'].', '.$row['id'].', 0, 0);" onmouseout="profileCard(0, 0, 0, 1);" onclick="profileCard(0, 0, 1, 1);" href="'.$this->url.'/index.php?a=profile&u='.$row['username'].'">'.realName($row['username'], $row['first_name'], $row['last_name']).'</a></div>
<div class="song-tag">
<a href="'.$this->url.'/index.php?a=explore&filter='.$tag.'">'.$tag.'</a>
</div>
<div class="song-title">
<div class="track-link"><h2 style="font-size:1.0em">
<!--<a href="'.$this->url.'/mp3download/'.$row['id'].'/'.$this->genSlug($row['title']).'.html" id="song-url'.$row['id'].'"><div id="song-name'.$row['id'].'">'.$row['title'].'</div></a>-->
</h2></div>
</div>
</div>
</div>
<div class="player-controls">
<div id="song-controls'.$row['id'].'">
<div id="jp_container_123" class="jp-audio">
<div class="jp-type-single">
<div class="jp-gui jp-interface">
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="track-actions-container">
</div>
'.$extra_links.'
'.$seo_links.'
'.$comment.'
'.$charts.'
</div>';
$object_id = 'article_12';
include('commentanything/php/loadComments.php');
$start = (isset($row['extra_id'])) ? $row['extra_id'] : $row['id'];
}
}
</code></pre>
<p>I am trying to display it right after '.$charts.' but it keeps showing up in header </p>
| 3 | 3,043 |
Spring JPA Data: Query ElementCollection
|
<p>I have an entity with an elementCollection:</p>
<pre><code>@Entity
class Customer {
@Column(name = "id")
int id;
String name;
@ElementCollection
@CollectionTable(
joinColumns = @JoinColumn(name = "customer_id")
Set<Address> addresses;
}
@Embeddable
class Address {
@Column(name = "address_id")
String id;
String data;
}
</code></pre>
<p>of course the matching data on the db:</p>
<pre><code>databaseChangeLog:
- changeSet:
id: 1
author: me
changes:
- createTable:
tableName: customer
columns:
- column:
name: id
type: bigint
autoIncrement: true
constraints:
primaryKey: true
nullable: false
- column:
name: name
type: varchar(255)
- createTable:
tableName: address
columns:
- column:
name: customer_id
type: bigint
constraints:
nullable: false
- column:
name: address_id
type: varchar(30)
- column:
name: data
type: varchar(255)
- addForeignKeyConstraint:
baseTableName: address
baseColumnNames: customer_id
referencedTableName: customer
referencedColumnNames: id
constraintName: fk_customer_id
- addUniqueConstraint:
tableName: address
name: unique_address_id
columnNames: address_id
</code></pre>
<p>Note: address id is really a String!</p>
<p>Inserting, and reading works. But my goal is to select <code>Customer</code> by <code>Address.id</code>.</p>
<p>My goal:</p>
<pre><code>interface CustomerJpaRepository extends JpaRepository<Customer, Long> {
XXXX // <-- insert solution here
}
</code></pre>
<p>My ideas for XXXX:</p>
<ol>
<li>Using spring data JPA:</li>
</ol>
<pre><code> Customer findByAddressWithId(String addressId);
</code></pre>
<p>Of course, this does not work, because the syntax is wrong. But I can't even find a description of the complete syntax for ElementCollections.</p>
<ol start="2">
<li>Using a custom query:</li>
</ol>
<pre><code> @Query(value = "select c from Customer c join Address a where a.id = '?1'")
Customer findByStreet(String addressId);
</code></pre>
<p>This one does not work because <code>a.id</code> can't be found.</p>
<p>Unfortunately, none of the above work.
Does anybody have any solution for <code>XXXX</code>?</p>
| 3 | 1,275 |
How can I put the label and the input on the same line please?
|
<p>How can I put the label and the input on the same line please? <strong>I would like to get please a spacing of 1,5cm between the label and input also.</strong></p>
<p>By searching <a href="https://stackoverflow.com/questions/39277144/how-to-put-label-and-input-box-on-the-same-line-using-bootstrap">here</a> I have to use <code>form-inline</code> but it doesn't work for put the label and input on the same line.</p>
<p><a href="https://i.stack.imgur.com/7MW2H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7MW2H.png" alt="enter image description here" /></a></p>
<p>Thank you so much for your tests.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>HTML CSS JS</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
<h1 id="welcome">HTML CSS JS</h1>
<div class="col-12 col-md-6 col-lg-3">
<div class="form-group ">
<label for="date">Start date</label>
<div class="input-group">
<input name="beginDate" id="beginDate" type="text" class="form-control"
style="background-color: white;"
(ngModelChange)="changedBeginDateInput($event)" [(ngModel)]="beginDate">
<input id="picker1" class="form-control" placeholder="dd/mm/yyyy" name="dp1"
ngbDatepicker #dp1="ngbDatepicker" [(ngModel)]="begin.validityDate"
(ngModelChange)="changedBeginDate($event)"
style="position: absolute; left: 0; visibility: hidden">
<div class="input-group-append" (click)="dp1.toggle()">
<span class="input-group-text" id="basic-addon2">
<i class="icon-regular i-Calendar-4"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-lg-3">
<div class="form-group form-inline">
<label for="date">End date</label>
<div class="input-group">
<input name="beginDate" id="beginDate" type="text" class="form-control"
style="background-color: white;"
(ngModelChange)="changedBeginDateInput($event)" [(ngModel)]="beginDate">
<input id="picker1" class="form-control" placeholder="dd/mm/yyyy" name="dp1"
ngbDatepicker #dp1="ngbDatepicker" [(ngModel)]="begin.validityDate"
(ngModelChange)="changedBeginDate($event)"
style="position: absolute; left: 0; visibility: hidden">
<div class="input-group-append" (click)="dp1.toggle()">
<span class="input-group-text" id="basic-addon2">
<i class="icon-regular i-Calendar-4"></i>
</span>
</div>
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| 3 | 1,641 |
Inheritance inconsistency
|
<p>Having some trouble working out an inheritance issue within Python. My code is:</p>
<pre><code>class Calendar(object):
def __init__(self):
self.norm_year = (365)
self.leap_year = (366)
def _input_validity(self, args_num, *args):
if len(args) != args_num:
return False
elif len(args) == 3:
args[0] = month
args[1] = day
args[2] = year
if type(month) != str or type(day) != int or type(year) != int:
return False
elif len(args) == 2:
args[0] = year
args[1] = doy
if type(year) != int or type(doy) != int:
return False
def _is_leap_year(self, year):
print(str(self))
if (type(year) != int) or (year <= 0):
return
if (year % 4 == 0):
if (year % 400 == 0) or (year % 100 != 0):
self.days_in_year = self.leap_year
self.months = self.months_leap
self.length = self.length_leap
return True
else:
self.days_in_year = self.norm_year
self.months = self.months_norm
self.length = self.length_norm
return False
else:
self.days_in_year = self.norm_year
self.months = self.months_norm
self.length = self.length_norm
return False
def date_to_day_of_year(self, *args):
pass
def day_of_year_to_date(self, *args):
args_num = 2
year = args[0]
doy = args[1]
self._is_leap_year(year)
if self._input_validity == False:
return
else:
month = 1
for i in self.length:
if doy > i:
month += 1
doy -= i
elif doy <= i:
day = doy
month = self.months[month]
return(str(month), day, year)
def date_to_day_of_week(self, *args):
# This can be called with three arguments such as
# obj.date_to_day_of_year("Messidor", 14, 1789)
# or with two arguments such as
# obj.date_to_day_of_year("Midyear"s Day", 1418)
# You need to determine which by looking at len(args).
pass
class Gregorian_Calendar(Calendar):
def __init__(self):
super().__init__()
self.months_norm = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}
self.months_leap = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}
self.length_norm = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
self.length_leap = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
self.weekdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri')
def day_of_year_to_day_of_week(self, year, doy):
pass
class Shire_Calendar(Calendar):
def __init__(self):
super().__init__()
self.months_norm = {1: "2 Yule", 2: "Afteryule", 3: "Solmath", 4: "Rethe", 5: "Astron", 6: "Thrimidge", 7: "Forelithe", 8: "1 Lithe", 9: "Midyear's Day", 10: "2 Lithe", 11: "Afterlithe", 12: "Wedmath", 13: "Halimath", 14: "Winterfilth", 15: "Blotmath", 16: "Foreyule", 17: "1 Yule"}
self.months_leap = {1: "2 Yule", 2: "Afteryule", 3: "Solmath", 4: "Rethe", 5: "Astron", 6: "Thrimidge", 7: "Forelithe", 8: "1 Lithe", 9: "Midyear's Day", 10: "Overlithe", 11: "2 Lithe", 12: "Afterlithe", 13: "Wedmath", 14: "Halimath", 15: "Winterfilth", 16: "Blotmath", 17: "Foreyule", 18: "1 Yule"}
self.length_norm = (1, 30, 30, 30, 30, 30, 30, 1, 1, 1, 1, 30, 30, 30, 30, 30, 30, 1)
self.length_leap = (1, 30, 30, 30, 30, 30, 30, 1, 1, 1, 30, 30, 30, 30, 30, 30, 1)
self.weekdays = ("Sterday", "Sunday", "Monday", "Trewsday", "Hensday", "Mersday", "Highday")
def _is_leap_year(self, year):
if (year % 4 == 0) and (year % 100 != 0):
self.days_in_year = self.leap_year
return True
else:
self.days_in_year = self.norm_year
return False
def day_of_year_to_day_of_week(self, year, doy):
pass
class Calendrier_Républicain(Calendar):
def __init__(self):
super().__init__()
self.months_norm = {"Vendémiaire": 1, "Brumaire": 2, "Frimaire": 3, "Nivôse": 4, "Pluviôse": 5, "Ventôse": 6, "Germinal": 7, "Floréal": 8, "Prairial": 9, "Messidor": 10, "Thermidor": 11, "Fructidor": 12, "Jour de la vertu": 13, "Jour du génie": 14, "Jour du travail": 15, "Jour de l'opinion": 16, "Jour des récompenses": 17}
self.months = {"Vendémiaire": 1, "Brumaire": 2, "Frimaire": 3, "Nivôse": 4, "Pluviôse": 5, "Ventôse": 6, "Germinal": 7, "Floréal": 8, "Prairial": 9, "Messidor": 10, "Thermidor": 11, "Fructidor": 12, "Jour de la vertu": 13, "Jour du génie": 14, "Jour du travail": 15, "Jour de l'opinion": 16, "Jour des récompenses": 17, "Jour de la Révolution": 18}
self.length_norm = (30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 1, 1, 1, 1, 1)
self.length_leap = (30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 1, 1, 1, 1, 1, 1)
self.weekdays = ("primidi", "duodi", "tridi", "quartidi", "quintidi", "sextidi", "septidi", "octidi", "nonidi", "décadi")
def day_of_year_to_day_of_week(self, year, doy):
pass
# Basic Testing
cal = Calendar()
gcal = Gregorian_Calendar()
scal = Shire_Calendar()
rcal = Calendrier_Républicain()
print(scal.day_of_year_to_date(1400, 2))
print(scal.day_of_year_to_date(1400, 184))
print(scal.day_of_year_to_date(1404, 184))
</code></pre>
<p>I'm trying to create a superclass that will be able to handle multiple different types of calendars and perform operations on them. The example I'm showing is a function within the superclass that converts the day of the year to the date by using information from the <code>Shire_Calendar</code> subclass.</p>
<p>In order to handle leap years, I want to assign two different variables for months and days in a month (<code>months_norm</code>, <code>months_leap</code>, <code>length_norm</code>, <code>length_leap</code>), that are specified within the calendar subclass, in this case <code>Shire_Calendar</code>, and then the <code>_is_leap_year</code> function within the superclass reads the year input, determines if it is a leap year, and assigns the appropriate month tuple and days in a month tuple to the general variables <code>months</code> and <code>length</code>. From there, the general variables are passed on to the function <code>day_of_year_to_date</code>.</p>
<p>The problem is that when I try to pass these variables, it spits out a name error that <code>Shire_Calendar</code> has no attribute <code>length</code>. It's as if within the <code>_is_leap_year</code> function, <code>months</code> and <code>length</code> are not being assigned, or being assigned to the wrong place.</p>
| 3 | 3,261 |
Receiving an Array to render in component
|
<p>I am trying to pass my state of thumbnail URLs that are saved to an array state. But when evaluating in my Netflix component videos is empty? When I console it, it returns <code>In tile {"videos":[]}</code></p>
<p><strong>Render</strong></p>
<pre><code>return (
<div className="explore">
<div className="row">
<NetflixTile videos={this.state.thumbnail} />
</div>
</div>
);
</code></pre>
<p><strong>Constructor</strong></p>
<pre><code> constructor(props) {
super(props);
this.props.getVideos();
this.state = {
thumbnail: []
};
}
</code></pre>
<p><strong>DidMount EDITED</strong></p>
<pre><code>componentDidUpdate() {
console.log("Component updated?");
let i = 0;
if (this.props.videos == null) {
console.log("It's null");
} else {
const videos = this.props.videos.video.map(video => {
<h5 key={video._id}>{video.thumbnail}</h5>;
this.state.thumbnail[i] = video.thumbnail;
console.log(this.state.thumbnail);
i++;
});
}
}
</code></pre>
<p><strong>Netflix component added into Render</strong></p>
<pre><code>const NetflixTile = videos => {
console.log("In tile " + JSON.stringify(videos.videos));
if (videos.length != null) {
for (let i = 0; videos > i; i++) {
return (
<div className="row__inner">
<div className="tile">
<div className="tile__media">
<img
className="tile__img"
id="thumbnail"
src={videos[i]}
alt=""
/>
</div>
</div>
</div>
);
}
} else {
return (
<div>
<h1>
You have not yet uploaded any STEM content. Go to your dashboard page
and click Upload to add to this library.
</h1>
</div>
);
}
};
export default NetflixTile;
</code></pre>
<p>**Console output of <code>this.state.thumbnail</code> **
<a href="https://i.stack.imgur.com/MktmR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MktmR.png" alt="enter image description here"></a></p>
| 3 | 1,066 |
Issue trying to get website to work - possible issue with my html code?
|
<p>SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...</p>
<p>But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.</p>
<p>Here is my fiddle:</p>
<p><a href="http://jsfiddle.net/sean1rose/sKadX/33/" rel="nofollow">jsfiddle</a></p>
<p>^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...</p>
<p>And here is the actual site:</p>
<p><a href="http://www.abveaspirations.com/index.html" rel="nofollow">http://www.abveaspirations.com/index.html</a></p>
<p>And here's my HTML code uploaded to the server via FTP:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- @@controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- @@controlbox -->
</div> <!-- 11main -->
</body>
</code></pre>
<p> </p>
<p>And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):</p>
<pre><code>$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
</code></pre>
<p>Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!</p>
| 3 | 2,935 |
Pytest core dump on Unbutu 22.04 LTS when using pyqt5 with mayavi and pyvirtualdisplay
|
<h2>Want I want to do:</h2>
<p>I want to have these requirements running on Ubuntu 22.04 LTS:</p>
<pre><code># Bug on Ub.22.04 but avoids AttributeError: 'Timer' object has no attribute 'start' on other OS
pyqt5==5.15.7
# These together work:
mayavi==4.7.4
PyVirtualDisplay==3.0
pytest==7.1.2
</code></pre>
<p>So I can run this test:</p>
<pre class="lang-py prettyprint-override"><code>import pytest
from pyvirtualdisplay import Display
import os
display = Display(visible=0, size=(1280, 1024))
display.start()
from mayavi import mlab
def foo(tmp_path):
assert 0 == 0;
</code></pre>
<h2>Problem</h2>
<p>Adding the PyQt5 to the list of dependencies seems to break the behavior of the program on Ubuntu 22.04 LTS (although it works on Ubuntu 20.04 LTS and MacOS for multiple version of Python 3.</p>
<p>The output error is the following:</p>
<pre><code>Run python3 -m pip install pytest
python3 -m pip install pytest
cd tests
python3 -m pytest
shell: /usr/bin/bash --noprofile --norc -e -o pipefail {0}
Defaulting to user installation because normal site-packages is not writeable
Collecting pytest
Downloading pytest-7.1.2-py3-none-any.whl (297 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 297.0/297.0 KB 8.8 MB/s eta 0:00:00
Collecting pluggy<2.0,>=0.12
Downloading pluggy-1.0.0-py2.py3-none-any.whl (13 kB)
Collecting iniconfig
Downloading iniconfig-1.1.1-py2.py3-none-any.whl (5.0 kB)
Requirement already satisfied: attrs>=19.2.0 in /usr/lib/python3/dist-packages (from pytest) (21.2.0)
Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (from pytest) (21.3)
Collecting py>=1.8.2
Downloading py-1.11.0-py2.py3-none-any.whl (98 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 98.7/98.7 KB 23.2 MB/s eta 0:00:00
Collecting tomli>=1.0.0
Downloading tomli-2.0.1-py3-none-any.whl (12 kB)
Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/lib/python3/dist-packages (from packaging->pytest) (2.4.7)
Installing collected packages: iniconfig, tomli, py, pluggy, pytest
Successfully installed iniconfig-1.1.1 pluggy-1.0.0 py-1.11.0 pytest-7.1.2 tomli-2.0.1
Fatal Python error: Aborted
Current thread 0x00007f99b32c8000 (most recent call first):
File "/home/runner/.local/lib/python3.10/site-packages/pyface/ui/qt4/init.py", line 36 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "<frozen importlib._bootstrap>", line 1050 in _gcd_import
File "/usr/lib/python3.10/importlib/__init__.py", line 126 in import_module
File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 171 in load
File "/home/runner/.local/lib/python3.10/site-packages/pyface/base_toolkit.py", line 218 in import_toolkit
File "/home/runner/.local/lib/python3.10/site-packages/pyface/base_toolkit.py", line 263 in find_toolkit
File "/home/runner/.local/lib/python3.10/site-packages/pyface/toolkit.py", line 23 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/qt4/toolkit.py", line 33 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1078 in _handle_fromlist
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/qt4/__init__.py", line 35 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "<frozen importlib._bootstrap>", line 1050 in _gcd_import
File "/usr/lib/python3.10/importlib/__init__.py", line 126 in import_module
File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 171 in load
File "/home/runner/.local/lib/python3.10/site-packages/pyface/base_toolkit.py", line 282 in find_toolkit
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/toolkit.py", line 110 in toolkit
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/toolkit_traits.py", line 43 in ColorTrait
File "/home/runner/.local/lib/python3.10/site-packages/traits/trait_factory.py", line 40 in __call__
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/editors/code_editor.py", line 32 in CodeEditor
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/editors/code_editor.py", line 21 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/editors/api.py", line 96 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/editors/__init__.py", line 16 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 992 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/traitsui/api.py", line 257 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/mayavi/preferences/preference_manager.py", line 29 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/mayavi/preferences/api.py", line 4 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/mayavi/tools/engine_manager.py", line 12 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/mayavi/tools/camera.py", line 24 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "/home/runner/.local/lib/python3.10/site-packages/mayavi/mlab.py", line 16 in <module>
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap_external>", line 883 in exec_module
File "<frozen importlib._bootstrap>", line 688 in _load_unlocked
File "<frozen importlib._bootstrap>", line 1006 in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1027 in _find_and_load
File "<frozen importlib._bootstrap>", line 241 in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1078 in _handle_fromlist
File "/home/runner/work/pyvirtualdisplay-bug/pyvirtualdisplay-bug/tests/test_animate.py", line 8 in <module>
File "/home/runner/.local/lib/python3.10/site-packages/_pytest/assertion/rewrite.py", line 168 in exec_module
...
Extension modules: numpy.core._multiarray_umath, numpy.core._multiarray_tests, numpy.linalg.lapack_lite, numpy.linalg._umath_linalg, numpy.fft._pocketfft_internal, numpy.random._common, numpy.random.bit_generator, numpy.random._bounded_integers, numpy.random._mt19937, numpy.random.mtrand, numpy.random._philox, numpy.random._pcg64, numpy.random._sfc64, numpy.random._generator, traits.ctraits, PyQt5.QtCore, PyQt5.QtGui, PyQt5.QtWidgets, PyQt5.QtPrintSupport, PyQt5.QtNetwork, PyQt5.QtQml, PyQt5.QtBluetooth, PyQt5.QtDBus, PyQt5.QtDesigner, PyQt5.QtHelp, PyQt5.QtNfc, PyQt5.QtOpenGL, PyQt5.QtPositioning, PyQt5.QtLocation, PyQt5.QtQuick, PyQt5.QtQuick3D, PyQt5.QtQuickWidgets, PyQt5.QtRemoteObjects, PyQt5.QtSensors, PyQt5.QtSerialPort, PyQt5.QtSql, PyQt5.QtSvg, PyQt5.QtTest, PyQt5.QtTextToSpeech, PyQt5.QtWebChannel, PyQt5.QtWebSockets, PyQt5.QtX11Extras, PyQt5.QtXml, PyQt5.QtXmlPatterns (total: 44)
/home/runner/work/_temp/0585cdff-a041-431e-b28d-a33e621d22b2.sh: line 3: 6351 Aborted (core dumped) python3 -m pytest
</code></pre>
<h3>Bug reproduction</h3>
<p>I created <a href="https://github.com/Becheler/pyvirtualdisplay-bug" rel="nofollow noreferrer">a small repo</a> to reproduce the issue. I created a bunch of branches where I cut some python dependencies off until I could isolate pyqt5 as the one breaking the working state: the changes are documented in the README. I know using external repos is not ideal, but since in that case it is a Github Action problem (it works on my local Ubuntu 22.04), maybe it makes sense?</p>
| 3 | 5,464 |
Ckeditor5 connection
|
<p>I use ElFinder as my image editor and ckeditor5 as my editor.</p>
<p>When I call the CKEditor script, it doesn't work :</p>
<pre><code>Uncaught (in promise) TypeError: $(...).dialogelfinder is not a function
</code></pre>
<p>The problem comes from the connector URL :</p>
<pre><code>/var/www/......./Sites/Admin/CkEditor5.php:101: string(80) "http://localhost/domain/external/elFinder-master/php/connector.minimal.php"
</code></pre>
<p>Both, the link and the hash are correct. When I click on the image icon it creates this error.</p>
<p>The script inside a function</p>
<pre><code> $connector = static::getElFinderConnector(); // connector URL (see above for example)
$field .= "<script>
// elfinder folder hash of the destination folder to be uploaded in this CKeditor 5
const uploadTargetHashImage = 'l2_Q0stRmlsZXM_' . $name;
// elFinder connector URL
//const connectorUrl = 'php/connector.minimal.php';
const connectorUrlImage = '{$connector}'; ================> here the problem
// To create CKEditor 5 classic editor
CKEDITOR.ClassicEditor
.create(document.getElementById('{$name}'), {
toolbar: {
items: [
'ckfinder', '|',
'sourceEditing'
],
shouldNotGroupWhenFull: true
},
removePlugins: [
// These two are commercial, but you can try them out without registering to a trial.
// 'ExportPdf',
// 'ExportWord',
'CKBox',
//'CKFinder',
'EasyImage',
// This sample uses the Base64UploadAdapter to handle image uploads as it requires no configuration.
// https://ckeditor.com/docs/ckeditor5/latest/features/images/image-upload/base64-upload-adapter.html
// Storing images as Base64 is usually a very bad idea.
// Replace it on production website with other solutions:
// https://ckeditor.com/docs/ckeditor5/latest/features/images/image-upload/image-upload.html
// 'Base64UploadAdapter',
'RealTimeCollaborativeComments',
'RealTimeCollaborativeTrackChanges',
'RealTimeCollaborativeRevisionHistory',
'PresenceList',
'Comments',
'TrackChanges',
'TrackChangesData',
'RevisionHistory',
'Pagination',
'WProofreader',
// Careful, with the Mathtype plugin CKEditor will not load when loading this sample
// from a local file system (file://) - load this site via HTTP server if you enable MathType
'MathType'
]
} )
.then(editor => {
const ckf = editor.commands.get('ckfinder'),
fileRepo = editor.plugins.get('FileRepository'),
ntf = editor.plugins.get('Notification'),
i18 = editor.locale.t,
// Insert images to editor window
insertImages = urls => {
const imgCmd = editor.commands.get('imageUpload');
if (!imgCmd.isEnabled) {
ntf.showWarning(i18('Could not insert image at the current position.'), {
title: i18('Inserting image failed'),
namespace: 'ckfinder'
});
return;
}
editor.execute('imageInsert', { source: urls });
},
// To get elFinder instance
getfm = open => {
return new Promise((resolve, reject) => {
// Execute when the elFinder instance is created
const done = () => {
if (open) {
// request to open folder specify
if (!Object.keys(_fm.files()).length) {
// when initial request
_fm.one('open', () => {
_fm.file(open)? resolve(_fm) : reject(_fm, 'errFolderNotFound');
});
} else {
// elFinder has already been initialized
new Promise((res, rej) => {
if (_fm.file(open)) {
res();
} else {
// To acquire target folder information
_fm.request({cmd: 'parents', target: open}).done(e =>{
_fm.file(open)? res() : rej();
}).fail(() => {
rej();
});
}
}).then(() => {
// Open folder after folder information is acquired
_fm.exec('open', open).done(() => {
resolve(_fm);
}).fail(err => {
reject(_fm, err? err : 'errFolderNotFound');
});
}).catch((err) => {
reject(_fm, err? err : 'errFolderNotFound');
});
}
} else {
// show elFinder manager only
resolve(_fm);
}
};
// Check elFinder instance
if (_fm) {
// elFinder instance has already been created
done();
} else {
// To create elFinder instance
_fm = $('<div/>').dialogelfinder({
// dialog title
title : 'File Manager',
// connector URL
url : connectorUrlImage,
// start folder setting
startPathHash : open? open : void(0),
// Set to do not use browser history to un-use location.hash
useBrowserHistory : false,
// Disable auto open
autoOpen : false,
// elFinder dialog width
width : '80%',
// set getfile command options
commandsOptions : {
getfile: {
oncomplete : 'close',
multiple : true
}
},
// Insert in CKEditor when choosing files
getFileCallback : (files, fm) => {
let imgs = [];
fm.getUI('cwd').trigger('unselectall');
$.each(files, function(i, f) {
if (f && f.mime.match(/^image\//i)) {
imgs.push(fm.convAbsUrl(f.url));
} else {
editor.execute('link', fm.convAbsUrl(f.url));
}
});
if (imgs.length) {
insertImages(imgs);
}
}
}).elfinder('instance');
done();
}
});
};
// elFinder instance
let _fm;
if (ckf) {
// Take over ckfinder execute()
ckf.execute = () => {
getfm().then(fm => {
fm.getUI().dialogelfinder('open');
});
};
}
// Make uploader
const uploder = function(loader) {
let upload = function(file, resolve, reject) {
getfm(uploadTargetHashImage).then(fm => {
let fmNode = fm.getUI();
fmNode.dialogelfinder('open');
fm.exec('upload', {files: [file], target: uploadTargetHashImage}, void(0), uploadTargetHashImage)
.done(data => {
if (data.added && data.added.length) {
fm.url(data.added[0].hash, { async: true }).done(function(url) {
resolve({
'default': fm.convAbsUrl(url)
});
fmNode.dialogelfinder('close');
}).fail(function() {
reject('errFileNotFound');
});
} else {
reject(fm.i18n(data.error? data.error : 'errUpload'));
fmNode.dialogelfinder('close');
}
})
.fail(err => {
const error = fm.parseError(err);
reject(fm.i18n(error? (error === 'userabort'? 'errAbort' : error) : 'errUploadNoFiles'));
});
}).catch((fm, err) => {
const error = fm.parseError(err);
reject(fm.i18n(error? (error === 'userabort'? 'errAbort' : error) : 'errUploadNoFiles'));
});
};
this.upload = function() {
return new Promise(function(resolve, reject) {
if (loader.file instanceof Promise || (loader.file && typeof loader.file.then === 'function')) {
loader.file.then(function(file) {
upload(file, resolve, reject);
});
} else {
upload(loader.file, resolve, reject);
}
});
};
this.abort = function() {
_fm && _fm.getUI().trigger('uploadabort');
};
};
// Set up image uploader
fileRepo.createUploadAdapter = loader => {
return new uploder(loader);
};
})
.catch(error => {
console.error( error );
});
</script>";
</code></pre>
| 3 | 4,817 |
How do I open a bitmap from a URI that is the result of taking a camera picture?
|
<p>I'm pretty bewildered here and have tried numerous suggestions I've seen on SO. I was following the Xamarin recipe for accessing the camera on Android and taking a picture. There were some things missing/out of date, but regardless I got to the point where I need to call <code>BitmapFactory.DecodeFile</code> so I can open the image the user just took and resize it to display in my view. The problem I ran into is that I can't use file paths, I have to use URIs. So I followed the instructions <a href="https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed">in this SO thread</a></p>
<p>and set up my file provider stuff. I have this file in my resources/xml directory: provider_paths.xml (MyApp being renamed from my actual app details)</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="MyApp" path="."/>
</paths>
</code></pre>
<p>Then in the manifest I added this inside the section:</p>
<pre><code><provider android:name="android.support.v4.content.FileProvider" android:authorities="com.myapp.provider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
</code></pre>
<p>I ensure the directory exists by doing:</p>
<pre><code>var file = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), "MyApp");
Directory = file.AbsolutePath;
if (!file.Exists())
file.Mkdirs();
</code></pre>
<p>(Directory being a string variable).</p>
<p>I create the intent and file name like so:</p>
<pre><code>Intent intent = new Intent(MediaStore.ActionImageCapture);
var file = new File(Directory, $"myPhoto_{Guid.NewGuid()}.jpg");
BaseFilename = file.Name;
_uri = FileProvider.GetUriForFile(MainActivity.Instance, "com.myapp.provider", file);
intent.PutExtra(MediaStore.ExtraOutput, _uri);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
</code></pre>
<p>(BaseFilename being a string variable in this class)</p>
<p>At first I thought maybe I should somehow convert the URI to a file path so that I can call BitmapFactory.DecodeFile. I followed several SO threads and none of them worked. I got various exceptions when they all started doing ContentResolver.Query or cursor operations. </p>
<p>So I figured, well, there's a BitmapFactory.DecodeStream method, why not use that instead? I tried getting a stream from the URI like so:</p>
<pre><code>var stream = MainActivity.Instance.ContentResolver.OpenInputStream(_uri)
</code></pre>
<p>But when I do this I get an exception: <code>Java.Lang.Exception: open failed: ENOENT (No such file or directory)</code></p>
<p>An example of what the URI looks like when I try this:</p>
<pre><code>content://com.myapp.provider/MyApp/Pictures/MyApp/myPhoto_2d13056f-6d23-461a-ad4b-532e10d9cb75.jpg
</code></pre>
<p>I'm so confused at this point about what's even the problem, and having a hard time with a lot of outdated Xamarin samples that I don't know where to look or what even is the real underlying problem here. Any insight would be greatly appreciated. BTW in case it matters, I at least go the permission stuff right. I already prompted for camera and storage access (I already dealt with errors regarding not having permission for camera/read/write external storage so at least that's over with).</p>
| 3 | 1,120 |
error message instead of NaN output and negative 'Nett Payment' output
|
<pre><code>var vDiscountPercent;
var vGrossPayment;
var vTicketType;
vTicketType = prompt(" What type of Tickets is required?");
document.write("The Ticket Type is: " + vTicketType);
var vTicketQty;
vTicketQty = prompt("How many Tickets are required?");
document.write("<br/>");
document.write("The Ticket Qty is: " + vTicketQty + "<br/>");
var vTicketQty = parseInt(vTicketQty);
if (isNaN(parseInt(vTicketQty))) {
vTicketQty = 0;
}
if (vTicketQty <= 0) {
document.write("Invalid Qty" + "<br/>");
} else {
vTicketPrice = calcPrice(vTicketType);
if (vTicketPrice == -1) {
document.write("Invalid Ticket Type" + "<br/>");
} else {
document.write("Ticket Price is: " + vTicketPrice + "<br/>");
}
var vTotalPayment = calcTotal(vTicketPrice, vTicketQty);
if (vTotalPayment > 0) {
document.write("Total payment required is: $" + vTotalPayment + "<br/>");
} else {
document.write("Invalid data supplied" + "<br/>");
}
}
function calcTotal(vTicketPrice, vTicketQty) {
return vTicketPrice * vTicketQty;
}
function calcPrice(vTicketType) {
var vTicketPrice;
if (vTicketType.toLowerCase() == "a") {
vTicketPrice = 100;
} else if (vTicketType.toLowerCase() == "b") {
vTicketPrice = 75;
} else if (vTicketType.toLowerCase() == "c") {
vTicketPrice = 50;
} else {
vTicketPrice = -1;
}
return vTicketPrice;
}
vGrossPayment = vTotalPayment;
var vGrossPayment = calcDiscountPercent(vGrossPayment);
function calcDiscountPercent(vGrossPayment) {
if (vGrossPayment < 200) {
document.write("Discount Percent: 0%");
vDiscountPercent = 0;
} else if (vGrossPayment < 400) {
document.write("Discount Percent: 5%");
vDiscountPercent = 0.05;
} else if (vGrossPayment < 600) {
document.write("Discount Percent: 7.5%");
vDiscountPercent = 0.075;
} else if (vGrossPayment > 600) {
document.write("Discount Percent: 10%");
vDiscountPercent = 0.10;
} else {
document.write("No discount");
}
return vDiscountPercent;
}
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent);
function applyDiscount(vTotalPayment, vDiscountPercent) {
return vTotalPayment * (vDiscountPercent * 100) / 100;
}
document.write("<br/>" + "Discount Amount: $" + applyDiscount);
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount);
function calcDiscountAmount(vGrossPayment, vDiscountPercent) {
return vTotalPayment - applyDiscount;
}
document.write("<br/>" + "Nett Payment: $" + vNettPayment);
</code></pre>
<p>At the moment when I enter a value that isn't between 1 to 100 in 'vTicketQty' the output is 'NaN' for 'Nett Payment' and 'Discount Amount', how do I get the output value to show an error message instead of NaN?
Also when I don't enter 'a' , 'b' or 'c' for 'vTicketType' the output for 'Nett Payment" is negative, again how do I get the output to show an error message instead?</p>
| 3 | 1,216 |
connect to hs100 with c++ sockets
|
<p>I'm new to the c++ world. But I want to make a script that turns on / off my tp-link switch. I have found a <a href="https://github.com/ggeorgovassilis/linuxscripts/blob/master/tp-link-hs100-smartplug/hs100.sh" rel="nofollow noreferrer">bash</a>, <a href="https://github.com/plasticrake/hs100-api" rel="nofollow noreferrer">javascript</a> and <a href="https://github.com/natefox/tplink-hs100/blob/master/turn_on.py" rel="nofollow noreferrer">python</a> script to do this but I want to make it in c++. </p>
<p>After a few days trying, reading webpages and coping code I have this that sends a request but there is something wrong with it. But I can't figure out what the problem is. </p>
<p>I can see in the Wireshark overview that the requested are send to the device. </p>
<h2>update 22-4-2017:</h2>
<p>I have updated the c++ with a hex decoder from the internet. </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
using namespace std;
string decode(string hex);
int tcp_send();
int main(int argc, char *argv[]) {
tcp_send();
}
string decode(string hex) {
unsigned long len = hex.length();
string newString;
for (int i = 0; i < len; i += 2) {
string byte = hex.substr(i, 2);
char chr = (char) (int) strtol(byte.c_str(), nullptr, 16);
newString.push_back(chr);
}
return newString;
}
int tcp_send() {
int sd, rc;
struct sockaddr_in servAddr;
string message;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(9999);
inet_pton(AF_INET, "192.168.2.4", &(servAddr.sin_addr));
/* create socket */
sd = socket(AF_INET, SOCK_STREAM, 0);
rc = connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr));
if (rc < 0) {
puts("error by send");
} else {
puts("connected");
}
message = decode("0000002ad0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedfa2dfa2");
rc = send(sd, (void *)(&message), sizeof(message), 0);
if (rc < 0) {
puts("error bij send 1");
close(sd);
exit(1);
} else puts("did send it");
sleep(1);
message = decode("AAAAKtDygfiL/5r31e+UtsWg1Iv5nPCR6LfEsNGlwOLYo4HyhueT9tTu36Lfog==");
rc = send(sd, (void *)(&message), sizeof(message), 0);
if (rc < 0) {
puts("error bij send 2");
close(sd);
exit(1);
} else puts("dit send it the second time");
return 0;
}
</code></pre>
<h2>update 21-4-2017:</h2>
<p>These are the commands that I can send (hex encoded) </p>
<pre><code>commands = {'info' : '{"system":{"get_sysinfo":{}}}',
'on' : '{"system":{"set_relay_state":{"state":1}}}',
'off' : '{"system":{"set_relay_state":{"state":0}}}',
'cloudinfo': '{"cnCloud":{"get_info":{}}}',
'wlanscan' : '{"netif":{"get_scaninfo":{"refresh":0}}}',
'time' : '{"time":{"get_time":{}}}',
'schedule' : '{"schedule":{"get_rules":{}}}',
'countdown': '{"count_down":{"get_rules":{}}}',
'antitheft': '{"anti_theft":{"get_rules":{}}}',
'reboot' : '{"system":{"reboot":{"delay":1}}}',
'reset' : '{"system":{"reset":{"delay":1}}}'
}
</code></pre>
<h2>c++ code</h2>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int tcp_send();
int main(int argc, char *argv[]) {
tcp_send();
}
int tcp_send() {
int sd, rc;
struct sockaddr_in servAddr;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(9999);
inet_pton(AF_INET, "192.168.2.4", &(servAddr.sin_addr));
/* create socket */
sd = socket(AF_INET, SOCK_STREAM, 0);
rc = connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr));
if (rc < 0) {
puts("error bij send");
} else {
puts("connected");
}
rc = send(sd, "0000002ad0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedfa2dfa2", strlen("0000002ad0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedfa2dfa2"), 0);
if (rc < 0) {
puts("error bij send 1");
close(sd);
exit(1);
} else puts("did send it");
sleep(1);
rc = send(sd, "AAAAKtDygfiL/5r31e+UtsWg1Iv5nPCR6LfEsNGlwOLYo4HyhueT9tTu36Lfog==", strlen("AAAAKtDygfiL/5r31e+UtsWg1Iv5nPCR6LfEsNGlwOLYo4HyhueT9tTu36Lfog=="), 0);
if (rc < 0) {
puts("error bij send 2");
close(sd);
exit(1);
} else puts("dit send it the second time");
return 0;
}
</code></pre>
<h2>wireshark calls:</h2>
<pre><code>No. Time Source Destination Protocol Length Info
214 8.443523 192.168.2.9 192.168.2.4 TCP 78 56667 → 9999 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=32 TSval=973574968 TSecr=0 SACK_PERM=1
Frame 214: 78 bytes on wire (624 bits), 78 bytes captured (624 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56667, Dst Port: 9999, Seq: 0, Len: 0
No. Time Source Destination Protocol Length Info
217 8.446444 192.168.2.9 192.168.2.4 TCP 66 56667 → 9999 [ACK] Seq=1 Ack=1 Win=131744 Len=0 TSval=973574971 TSecr=18699694
Frame 217: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56667, Dst Port: 9999, Seq: 1, Ack: 1, Len: 0
No. Time Source Destination Protocol Length Info
218 8.455485 192.168.2.9 192.168.2.4 TCP 112 56667 → 9999 [PSH, ACK] Seq=1 Ack=1 Win=131744 Len=46 TSval=973574980 TSecr=18699694
Frame 218: 112 bytes on wire (896 bits), 112 bytes captured (896 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56667, Dst Port: 9999, Seq: 1, Ack: 1, Len: 46
Data (46 bytes)
0000 00 00 00 2a d0 f2 81 f8 8b ff 9a f7 d5 ef 94 b6 ...*............
0010 c5 a0 d4 8b f9 9c f0 91 e8 b7 c4 b0 d1 a5 c0 e2 ................
0020 d8 a3 81 f2 86 e7 93 f6 d4 ee df a2 df a2 ..............
No. Time Source Destination Protocol Length Info
219 8.455538 192.168.2.9 192.168.2.4 TCP 66 56667 → 9999 [FIN, ACK] Seq=47 Ack=1 Win=131744 Len=0 TSval=973574980 TSecr=18699694
Frame 219: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56667, Dst Port: 9999, Seq: 47, Ack: 1, Len: 0
No. Time Source Destination Protocol Length Info
222 8.459966 192.168.2.9 192.168.2.4 TCP 66 56667 → 9999 [ACK] Seq=48 Ack=50 Win=131712 Len=0 TSval=973574984 TSecr=18699696
Frame 222: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56667, Dst Port: 9999, Seq: 48, Ack: 50, Len: 0
No. Time Source Destination Protocol Length Info
224 8.460343 192.168.2.9 192.168.2.4 TCP 66 56667 → 9999 [ACK] Seq=48 Ack=51 Win=131712 Len=0 TSval=973574984 TSecr=18699696
Frame 224: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56667, Dst Port: 9999, Seq: 48, Ack: 51, Len: 0
No. Time Source Destination Protocol Length Info
1397 68.198574 192.168.2.9 192.168.2.4 TCP 78 56704 → 9999 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=32 TSval=973634481 TSecr=0 SACK_PERM=1
Frame 1397: 78 bytes on wire (624 bits), 78 bytes captured (624 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56704, Dst Port: 9999, Seq: 0, Len: 0
No. Time Source Destination Protocol Length Info
1399 68.202027 192.168.2.9 192.168.2.4 TCP 66 56704 → 9999 [ACK] Seq=1 Ack=1 Win=131744 Len=0 TSval=973634484 TSecr=18712532
Frame 1399: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56704, Dst Port: 9999, Seq: 1, Ack: 1, Len: 0
No. Time Source Destination Protocol Length Info
1400 68.202117 192.168.2.9 192.168.2.4 TCP 158 56704 → 9999 [PSH, ACK] Seq=1 Ack=1 Win=131744 Len=92 TSval=973634484 TSecr=18712532
Frame 1400: 158 bytes on wire (1264 bits), 158 bytes captured (1264 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56704, Dst Port: 9999, Seq: 1, Ack: 1, Len: 92
Data (92 bytes)
0000 30 30 30 30 30 30 32 61 64 30 66 32 38 31 66 38 0000002ad0f281f8
0010 38 62 66 66 39 61 66 37 64 35 65 66 39 34 62 36 8bff9af7d5ef94b6
0020 63 35 61 30 64 34 38 62 66 39 39 63 66 30 39 31 c5a0d48bf99cf091
0030 65 38 62 37 63 34 62 30 64 31 61 35 63 30 65 32 e8b7c4b0d1a5c0e2
0040 64 38 61 33 38 31 66 32 38 36 65 37 39 33 66 36 d8a381f286e793f6
0050 64 34 65 65 64 66 61 32 64 66 61 32 d4eedfa2dfa2
No. Time Source Destination Protocol Length Info
1403 69.205674 192.168.2.9 192.168.2.4 TCP 130 56704 → 9999 [PSH, ACK] Seq=93 Ack=1 Win=131744 Len=64 TSval=973635485 TSecr=18712532
Frame 1403: 130 bytes on wire (1040 bits), 130 bytes captured (1040 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56704, Dst Port: 9999, Seq: 93, Ack: 1, Len: 64
Data (64 bytes)
0000 41 41 41 41 4b 74 44 79 67 66 69 4c 2f 35 72 33 AAAAKtDygfiL/5r3
0010 31 65 2b 55 74 73 57 67 31 49 76 35 6e 50 43 52 1e+UtsWg1Iv5nPCR
0020 36 4c 66 45 73 4e 47 6c 77 4f 4c 59 6f 34 48 79 6LfEsNGlwOLYo4Hy
0030 68 75 65 54 39 74 54 75 33 36 4c 66 6f 67 3d 3d hueT9tTu36Lfog==
No. Time Source Destination Protocol Length Info
1404 69.206651 192.168.2.9 192.168.2.4 TCP 66 56704 → 9999 [FIN, ACK] Seq=157 Ack=1 Win=131744 Len=0 TSval=973635485 TSecr=18712532
Frame 1404: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56704, Dst Port: 9999, Seq: 157, Ack: 1, Len: 0
No. Time Source Destination Protocol Length Info
1407 69.209081 192.168.2.9 192.168.2.4 TCP 66 56704 → 9999 [ACK] Seq=158 Ack=2 Win=131744 Len=0 TSval=973635487 TSecr=18712748
Frame 1407: 66 bytes on wire (528 bits), 66 bytes captured (528 bits) on interface 0
Ethernet II, Src: Apple_55:12:a7 (78:4f:43:55:12:a7), Dst: Tp-LinkT_01:4a:a9 (50:c7:bf:01:4a:a9)
Internet Protocol Version 4, Src: 192.168.2.9, Dst: 192.168.2.4
Transmission Control Protocol, Src Port: 56704, Dst Port: 9999, Seq: 158, Ack: 2, Len: 0
</code></pre>
| 3 | 6,385 |
Error analysing the csv database with javascript
|
<p>I'm a doing a project for school using IBM's bluemix and I'm having trouble finding out where is my error. I have a database in CSV that has some parameters (neighbourhood, number of rooms, area in square meters, etc). I also have a JADE file that contains a form that the user have to fill in. In this form, the user will choose how many rooms he wants and everything else. Then, my app in JAVASCRIPT should be able to run the database based on the choices of the user. However, for some reason, the results are not appearing in the webpage as they should.</p>
<p>Here is my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
var fs = require('fs');
var parse = require('csv-parse');
// create a new express server
var app = express();
function seleciona_dados(dados, parametros){
var resultado = {Bairro: [], quartos: [], area: [], valor: [], endereco: [], img: []};
for (var i = 1; i < dados.Bairro.length; i++){
if (dados.Bairro[i] == parametros.bairro && dados.quartos[i] == parametros.quartos && dados.area[i] >= Number(parametros.area) && dados.valor[i] <= Number(parametros.valor)){
resultado.bairro.push(dados.bairro[i]);
resultado.quartos.push(dados.quartos[i]);
resultado.area.push(dados.area[i]);
resultado.valor.push(dados.valor[i]);
resultado.endereco.push(dados.endereco[i]);
resultado.img.push(dados.img[i]);
}
}
return resultado;
}
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function(req, res){
res.render('cadastro.jade', { pageTitle: 'Cadastro Usuário'});
});
app.post('/resumo', function(req, res){
// var furfles = req.body;
var parser = parse({delimiter: ';'}, function(err, data){
var dados = {bairro: [], quartos: [], area: [], valor: [], endereco: [], img: []};
for (var i = 1; i < data.length; i++){
dados.bairro.push(data[i][0]);
dados.quartos.push(data[i][1]);
dados.area.push(Number(data[i][2]));
dados.valor.push(Number(data[i][3]));
dados.endereco.push(data[i][4]);
dados.img.push(data[i][5]);
}
dados = seleciona_dados(dados, req.body);
res.render('resumo.jade', {pageData:{ pageTitle: 'Resumo do Pedido do Usuário'}, formData: req.body, imoveis: dados});
});
fs.createReadStream(__dirname+'/static/BD.csv').pipe(parser);
});</code></pre>
</div>
</div>
</p>
<p>The list of apartments selected in the database should appear below the last sentence of this image.<a href="http://i.stack.imgur.com/zvTRz.png" rel="nofollow">Page</a></p>
| 3 | 1,461 |
How can this Java tree be 1000 x faster?
|
<p>I am programming an AI for a chess-like game, based on two types of pieces on a 8 x 8 grid.</p>
<p>I want to build a kind of minmax tree, which represents each possible move in a game, played by white players in first, and by black players in second.</p>
<p>I have this generate() method which is call recursively. I need to be able to display about 8 levels of possible moves. Without optimization, this three has 8^8 leafs.</p>
<p>I implemented a simple system which determinate if a grid has actually ever been calculated and if its the case, system just points a child to the ever-calculated child reference.</p>
<p>I don't know if my explanations are clear, I will join a part of code that you should be able to understand.</p>
<p>The problem is that actually, I am able to generate about 3 or 4 levels of all possibilities. I am far of 8.</p>
<p>I would like to be able to calculate it in less than 5 seconds..</p>
<p>So guys, do you see a solution for optimize my algorithm ?</p>
<p>This is the generate function:
leftDiagonalMove(), rightDiagonalMove() and frontMove() return false if a move is illegal or move the piece in the grid and return true, if the move is legal.</p>
<p>clone() creates a new instance with the same properties of it's "parent" and backMove() just step back to last Move.</p>
<pre><code>public void generate(Node root, boolean white, int index) {
Grid grid = root.getGrid();
Stack<Piece> whitePieces = grid.getPiecesByColor(WHITE);
Stack<Piece> blackPieces = grid.getPiecesByColor(BLACK);
Node node;
String serial = "";
// white loop
for (int i = 0; i < whitePieces.size() && white; i++) {
Piece wPiece = whitePieces.get(i);
if (grid.leftDiagonalMove(wPiece)) {
serial = grid.getSerial();
if(!allGrids.containsKey(serial)){
node = new Node(grid.clone());
node.setMove(grid.getLastMove());
root.addChild(node); // add modified grid
allGrids.put(serial, node);
//actualGrid.display();
if (index < 5 && grid.getPosition(wPiece).x > 0)
generate(node, !white, index + 1);
actualGrid.backMove(); // back step to initial grid
}
else{
root.addChild(allGrids.get(serial));
}
}
if (grid.frontMove(wPiece)) {
// same code as leftMove
}
if (grid.rightDiagonalMove(wPiece)) {
// same code as leftMove
}
}
// black loop
for (int i = 0; i < blackPieces.size() && !white; i++) {
Piece bPiece = blackPieces.get(i);
if (grid.leftDiagonalMove(bPiece)) {
// same code as white loop and replacing wPiece by bPiece
}
if (grid.frontMove(bPiece)) {
// same code as white loop and replacing wPiece by bPiece
}
if (grid.rightDiagonalMove(bPiece)) {
// same code as white loop and replacing wPiece by bPiece
}
}
}
</code></pre>
| 3 | 1,253 |
option on select with icon and text when opened and just icon when collapsed
|
<p>I want to create a select-option input on my local web with an icon and text when opened or clicked, and return to just being an icon when collapsed. It doesn't matter if I have to use js, css, or some small plugin. Is that possible? Please tell me how</p>
<pre><code><div class="form-group mb-3">
<div class="input-group">
<select class="select2" id="pilihan" name="medsos" style="width: 73px;" onchange="chg_kontak()">
<option selected disabled value="medsos"></option>
<option value="email">Email</option><!-- this is the main problem, I want text with uppercase (Signal, WhatsApp, etc) hidden when select collapsed -->
<option value="signal">Signal</option>
<option value="telegram">Telegram</option>
<option value="twitter">Twitter</option>
<option value="whatsapp">WhatsApp</option>
</select>
<input type="text" class="form-control" id="oth_contact" name="oth_contact" placeholder="kontak lain" required disabled onfocus>
</div>
</div>
<script>
//Initialize Select2 Elements
$('.select2').select2()
$(document).on('select2:open', () => {
document.querySelector('.select2-search__field').focus();
});
function chg_kontak() {
var x = document.getElementById("pilihan").value;
var y = document.getElementById("oth_contact");
if (x == "telegram" | x == "twitter") {
y.type = "text";
y.placeholder = "@username_anda";
y.onfocus = function(){
y.value = '@';
}
}else if (x == "whatsapp" | x == "signal"){
y.type = "tel";
// y.maxlength = "14";
y.placeholder = "nomor "+x;
y.value = '';
y.onfocus = function(){
y.value = '';
}
}else if (x == "email"){
y.type = x;
y.placeholder = "alamat email";
y.value = '';
y.onfocus = function(){
y.value = '';
}
}
y.removeAttribute("disabled");
}
$("#pilihan").select2({
templateResult: function (idioma) {
var $span = $("<span><img src='"+window.location.origin+"/jala/aset/mycustom/img/icons/"+idioma.id+".svg' style='width: 27px; padding-bottom: 2px;' /> " + idioma.text + "</span>");
return $span;
},
templateSelection: function (idioma) {
var $span = $("<span><img src='"+window.location.origin+"/jala/aset/mycustom/img/icons/"+idioma.id+".svg' style='width: 27px; padding-bottom: 2px;' /> " + idioma.text + "</span>");
return $span;
},
minimumResultsForSearch: Infinity
// placeholder: "<span><img src='"+window.location.origin+"/jala/aset/mycustom/img/email.png' height='27' /> dsafsak </span>" and I can't use my icon as placeholder too, but it's not a big problem
});
</script>
</code></pre>
| 3 | 1,448 |
Extract only first occurrence of character and all the numbers before and after hyphen
|
<p>I got into this situation to write a generic function which can extract only first occurrence of the character and all the number from a string.</p>
<p>Input String (Say): ABC123-45DEF-GH67IJ9<br>
Output String: A123-45D-G679</p>
<p>I have finalized an approach but the complexity of the program is high. There are two bad situations for me here:</p>
<ol>
<li>I am getting incorrect output from my program.<br>
<strong>Output:</strong> A123-45D-G679- (This extra hyphen is the issue in the below code).</li>
<li>I need a better approach to get this done in a less complex way.</li>
</ol>
<p><strong>Here is my code snippet:</strong></p>
<pre><code>package Test;
import java.util.LinkedList;
public class FirstLetterAndNumerics {
static void firstLetterAndNumber(String string) {
StringBuffer sb = new StringBuffer();
LinkedList<String> ll = new LinkedList<String>();
String[] str = string.split("-");
boolean flag = true;
for (int i = 0; i < str.length; i++) {
ll.add(str[i]);
}
for (int j = 0; j < ll.size(); j++) {
if (Character.isAlphabetic(ll.get(j).charAt(0))) {
if (flag == false) {
sb.append("-");
}
sb.append(ll.get(j).charAt(0));
for (int k = 1; k < ll.get(j).length(); k++) {
if (Character.isAlphabetic(ll.get(j).charAt(k))) {
flag = false;
} else if (Character.isDigit(ll.get(j).charAt(k))) {
sb.append(ll.get(j).charAt(k));
}
}
sb.append("-");
flag = true;
} else if (Character.isDigit(ll.get(j).charAt(0))) {
sb.append(ll.get(j).charAt(0));
for (int l = 1; l < ll.get(j).length(); l++) {
if (Character.isDigit(ll.get(j).charAt(l))) {
sb.append(ll.get(j).charAt(l));
} else if (Character.isAlphabetic(ll.get(j).charAt(l)) && flag == true) {
sb.append(ll.get(j).charAt(l));
flag = false;
}
}
}
}
System.out.println(sb);
}
public static void main(String[] args) {
firstLetterAndNumber("ABC123-45DEF-GH67IJ9");
}
}
</code></pre>
| 3 | 1,261 |
Angularjs – Warn on unsaved changes in Master Detail Scenario
|
<p>I need a solution to warning about unsaved changes in a Master- Detail scenario. I was able to implement a solution by Sam that he created in September 2015 (<a href="http://www.samjhill.com/blog/?p=525#comment-28558" rel="nofollow noreferrer">http://www.samjhill.com/blog/?p=525#comment-28558</a>). This was in response to a stackoverflow question and answer at the link, <a href="https://stackoverflow.com/questions/14852802/detect-unsaved-changes-and-alert-user-using-angularjs">Detect Unsaved changes and alert user using angularjs</a>.</p>
<p>The solution provided by Sam works great with a single form in the html file but I am having problems in a situation I have where I have multiple forms in a header section and detail section where both can change. In the detail section I am using xeditable table. I have tried adding the "confirm-on-exit" attribute to both forms. In the top section the confirmation box comes up as expected but continues to come up even after I submit for update. In the xeditable section the confirmation box never comes up. I have included my html below. Can you offer any suggests I can make so that the warning comes up if a change is made to any form on the page?</p>
<pre><code>.container.col-md-12.col-sm-12.col-xs-12-center
.well
form.form-horizontal(name="createQuestionAnswer" confirm-on-exit)
fieldset
legend Question Definition
.form-group
label.col-md-2.control-label(for="statement") Question
.col-md-10
input.form-control(name="statement", type="text", placeholder="Statement", ng-model="statement", ng-change = "changeStatement()",required)
.form-group
label.col-md-2.control-label(for="sequenceNo") SequenceNo
.col-md-4
input.form-control(name="sequenceNo", type="text", placeholder="SequenceNo", ng-model="sequenceNo", ng-change = "changeSequenceNo()",required)
label.col-md-2.control-label(for="componentType") Type
.col-md-4
input.form-control(name="componentType", type="text", placeholder="ComponentType", ng-model="componentType", ng-change = "changeComponentType()",required)
.form-group
label.col-md-2.control-label(for="weight") Weight
.col-md-2
input.form-control(name="weight", type="text", placeholder="Weight", ng-model="weight", ng-change = "changeWeight()")
label.col-md-2.control-label(for="imageURL") Image
.col-md-6
input.form-control(name="imageURL", type="text", placeholder="Image", ng-model="imageURL", ng-change = "changeImageURL()", required)
div(ng-app='app')
table.table.table-bordered.table-hover.table-condensed(style='width: 100%')
tr(style='font-weight: bold')
td(style='width:70%') Answer
td(style='width:10%') Correct
td(style='width:10%') Rank
td(style='width:10%') Position
tr(ng-repeat='answer in answers')
td
// editable answer (text with validation)
span(editable-text='answer.answer', e-name='answer', e-form='rowform', onbeforesave='checkAnswer($data)',onaftersave='saveAnswers($data)', e-required='') {{ answer.answer || &apos;empty&apos;}}
td
// editable (select-local)
span(editable-text='answer.correct', e-name='correct', e-form='rowform') {{ answer.correct }}
td
// editable
span(editable-text='answer.rank', e-name='rank', e-form='rowform' ) {{ answer.rank }}
td
// editable
span(editable-text='answer.position', e-name='position', e-form='rowform') {{ answer.position }}
td(style='white-space: nowrap')
// form
form.form-buttons.form-inline(editable-form='', name='rowform' onbeforesave='changeAnswers()', ng-show='rowform.$visible', shown='inserted == answer')
button.btn.btn-primary(type='submit', ng-disabled='rowform.$waiting') save
button.btn.btn-default(type='button', ng-disabled='rowform.$waiting', ng-click='rowform.$cancel()') cancel
.buttons(ng-show='!rowform.$visible')
button.btn.btn-primary(ng-click='rowform.$show()' ) edit
button.btn.btn-danger(ng-click='removeAnswer($index)') del
button.btn.btn-default(ng-click='addAnswer()') Add row
form.form-horizontal(name="buttonQuestionAnswer")
fieldset
.form-group
.col-md-10.col-md-offset-2
.pull-right
button.btn.btn-primary(ng-controller="flQuestionCrudCtrl", ng-show="questionMode=='Create'", ng-click="createQuestion()") Save New
| &nbsp;
button.btn.btn-primary(ng-controller="flQuestionCrudCtrl", ng-show="questionMode=='Update'", ng-click="updateQuestion()") Update
| &nbsp;
button.btn.btn-primary(ng-controller="flQuestionCrudCtrl", ng-show="questionMode=='Update'", ng-click="deleteQuestion()") Delete
| &nbsp;
a.btn.btn-default(ui-sref="home") Cancel
</code></pre>
| 3 | 2,582 |
Cells Format and subtotals with VBA
|
<p>I have created a VBA macro to give the format to Sheet in excel and create some subtotals. </p>
<p>It works, but has a lot of room for improvement. </p>
<p>Right now it takes very long. </p>
<p>I know that using Matrix the processing time could be reduced to milliseconds.</p>
<pre><code>Sub justsubttotals()
Sheets("Produktionsplan").Select
'Delete previous format
Range("A4:I1000").Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlHairline
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlHairline
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlHairline
End With
'I define 3 start variables with the first row of the matrix (per default it always starts in row 4).
primero = 4
fin = 4
contar = 4
'Identify how many rows are in the file
Finalrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
For j = 4 To Finalrow
If Cells(j, 1) = 0 And contar <= Finalrow Then
Cells(j, 1).Select
Selection.EntireRow.Select
Selection.Delete Shift:=xlUp
j = j - 1
contar = contar + 1
Else
contar = contar + 1
End If
Next
inicio = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
'Este inicio lo guardo para la parte de los subtotales
inicio2 = inicio
'Este inicio si es para los formatos
inicio = inicio + 1
For i = 4 To inicio
For j = primero To inicio
If Cells(primero, 4) = Cells(fin + 1, 4) Then
fin = fin + 1
Else
j = inicio
End If
Next
'Based on the description of column 2, I know which colour to assign
If Cells(primero, 2) = "B. Rück RH" Or Cells(primero, 2) = "B. 7 OB RH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.699981688894314
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "B. Rück LH" Or Cells(primero, 2) = "B. 7 OB LH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.499981688894314
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "B. 7 SAMS Center " Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 8771461
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "B. 7 SAMS LH " Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 8771461
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "B. 7 SAMS RH " Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 8771461
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "B. 634 RH/LH " Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6723891
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "B. Vor RH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent5
.TintAndShade = 0.699981688894314
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "B. Vor LH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.699981688894314
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "Porsche RH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent5
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "Porsche LH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.399993896298105
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "Audi RH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.ThemeColor = xlThemeColorDark2
.TintAndShade = -9.99786370433668E-02
.TintAndShade = 0.699981688894314
.PatternTintAndShade = 0
End With
ElseIf Cells(primero, 2) = "Audi LH" Then
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3
.TintAndShade = 0.599993896298105
.PatternTintAndShade = 0
End With
Else
Range("A" & primero & ":I" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Range("A" & primero & ":I" & fin).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlHairline
End With
primero = fin + 1
Next
'************************************************
'I create the subtotals
'************************************************
primero = 4
fin = 4
inicio = inicio2
For i = 4 To inicio
For j = primero To inicio
If Cells(primero, 4) = Cells(fin + 1, 4) Then
fin = fin + 1
Else
j = inicio
End If
Next
If fin > primero Then
Rows(fin + 1 & ":" & fin + 1).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
inicio = inicio + 1
Range("H" & fin + 1).Select
Cells(fin + 1, 8).Value = "=Sum(H" & primero & ":H" & fin & ")"
Range("H" & fin + 1).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Selection.Font.Bold = True
Else
Range("H" & fin).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Selection.Font.Bold = True
End If
primero = fin + 1
Next
'************************************************
'I use the formula of another sheet
'************************************************
Sheets("RuestenMatrix").Select
Range("J1").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Produktionsplan").Select
Range("J4:J810").Select
ActiveSheet.Paste
'************************************************
'Once again I use the formula of another sheet
'************************************************
Sheets("Pause Zeit").Select
Range("K4:K5").Select
Selection.Copy
Sheets("Produktionsplan").Select
Range("K4").Select
ActiveSheet.Paste
Range("K5").Select
Application.CutCopyMode = False
Selection.AutoFill Destination:=Range("K5:K810")
Range("K5:K810").Select
'************************************************
'One more time I use the formula of another sheet
'************************************************
Cells(4, 13).Select
Sheets("Pause Zeit").Select
Range("M4:P5").Select
Selection.Copy
Sheets("Produktionsplan").Select
ActiveSheet.Paste
Range("M5:P5").Select
Application.CutCopyMode = False
Selection.AutoFill Destination:=Range("M5:P872")
Range("M5:P872").Select
Range("M4").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.Font.Bold = True
End Sub
</code></pre>
| 3 | 4,117 |
Output text file is not giving me underscore symbol
|
<p>I am reading a text file and making some alignment changes, also removing the space in 3rd column of text file and replacing it with underscore (_) symbol. <strong>But unfortunately.. when my output generated i can see the underscore symbol is not coming for no reason</strong>. Can ANYONE help me please, why its happening like that??</p>
<p>code snippet:</p>
<pre><code> public void just_create_text()
{
//Here we are exporting header
string[] strLines = System.IO.File.ReadAllLines(textBox1.Text);
string CarouselName = enter.Text;
int[] cols = new int[] { 15, 15, 25, 15, 15 };
StringBuilder sb = new StringBuilder();
string line = RemoveWhiteSpace(strLines[0]).Trim();
string[] cells = line.Replace("\"", "").Split('\t');
for (int c = 0; c < cells.Length; c++)
sb.Append(cells[c].Replace(" ", "_").PadRight(cols[c]));
// here i am replacing the space with underscore...
sb.Append("Location".PadRight(15));
sb.Append("\r\n");
int tmpCarousel = 0;
int carouselNumber = 0;
Dictionary<string, int> namesForCarousels = new Dictionary<string, int>();
for (int i = 0; i < textfile.Count; i++)
{
for (int c = 0; c < cells.Length; c++)
sb.Append(textfile[i].Cells[c].PadRight(cols[c]));
string name = textfile[i].Cells[1];
if (namesForCarousels.TryGetValue(name, out tmpCarousel) == false)
{
carouselNumber++;
namesForCarousels[name] = carouselNumber;
}
var strCorousel = lstMX.Find(x => x.MAX_PN.Equals(name)).Carousel;
strCorousel = (String.IsNullOrEmpty(strCorousel)) ? CarouselName : strCorousel;
sb.Append(String.Format("{0}:{1}", strCorousel, carouselNumber).PadRight(15));
sb.Append("\r\n");
}
System.IO.File.WriteAllText(@"D:\output.TXT", sb.ToString());
}
private string RemoveWhiteSpace(string str)
{
str = str.Replace(" ", " ");
if (str.Contains(" "))
str = RemoveWhiteSpace(str);
return str;
}
</code></pre>
<p>Input text file:</p>
<pre><code>Designator MAX PN Footprint Center-X(mm) Center-Y(mm)
"AC1" "100-0177" "CAPC1608N" "7.239" "82.677"
"AC2" "100-0177" "CAPC1608N" "4.445" "85.471"
"C1" "100-0211" "0805M - CAPACITOR" "14.745" "45.72"
"C2" "100-0230" "CAPC3225N" "83.388" "58.42"
"C3" "100-0145" "CAPC1608N" "101.543" "73.025"
"C10" "100-0145" "CAPC1608N" "109.163" "73.025"
</code></pre>
<p>In output text file i need like below if we take the case for C1:</p>
<pre><code> C1 100-0211 0805M_-_CAPACITOR 14.745 45.72 Location:3
//here only problem is i am not getting the underscore in 0805M - CAPACITOR.
//i am getting as same.. like 0805M - CAPACITOR
</code></pre>
| 3 | 1,354 |
grid view button asp.net c#
|
<p>we want to accept only one record in gridview through accept button but in our code all requests are accepted if we are on last record.kindly let me know the problem in my code also provide the solution</p>
<p>protected void ChangeStatus(object sender, EventArgs e)
{
var context = new healthCareContext();</p>
<pre><code> Button btn = (Button)sender;
string str = btn.CommandName;
var pemail = str;
//////int row = GridView1.Rows.Count;
////GridView1.SelectedIndex =GridView1.Rows.Count;
////string mypemail = GridView1.SelectedRow.Cells[2].Text;
String status="Accepted";
if (btn.Text == "Accepted")
btn.Visible = false;
string newStatus = "";
if (btn.Text == "Accept")
{
newStatus = "Accepted";
Response.Write("appointment has been Accepted and added in the database table 'appointments'.");
}
using (context)
{
var results = (from a in context.appointments where a.pemail == pemail select a);
foreach (var b in results)
{
b.astatus = newStatus;
//string signupName = b.name;
}
//int row = GridView1.Rows.Count;
//GridView1.Selected
// string mypemail = GridView1.SelectedRow.Cells[2].Text;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["healthCareContext"].ConnectionString);
conn.Open();
Console.WriteLine(conn);
SqlCommand com = new SqlCommand("INSERT into appointments (astatus) values (@p1) where pemail==" + pemail + "), conn");
com.Parameters.AddWithValue("@p1", status);
com.ExecuteNonQuery();
conn.Close();
context.SaveChanges();
}
Response.AppendHeader("Refresh", "0");
}
</code></pre>
<p>the html markup</p>
' onClick="ChangeStatus">
" SelectCommand="SELECT * FROM [appointments]">
| 3 | 1,166 |
How to make a list of PrimaryRowId and Matching RowIds
|
<p>In my previous question (<a href="https://stackoverflow.com/questions/14629325/select-a-distinct-rowid-based-on-series-of-trainnumbers">Select a distinct RowId based on series of trainnumbers</a>) I got a nice list of RowIds.</p>
<p>Now I'd like to make that list complete and totally awesome! :)</p>
<p>My raw data(Excel 2010) looks like this:</p>
<pre><code>Time Wagons Delete DayType Plate trainnumber RowId
05.28 1 1 0901-046 2 38676
08.20 2 1 0901-003 2 18676
05.25 2 x 1 0901-046 2 28676
15.28 2 1 0901-046 2 3676
23.20 3 1 0601-001 2 3867
05.08 3 1 0901-046 2 3876
00.28 L x 1 0901-046 2 8676
00.00 1 0901-046 2 367
</code></pre>
<p>I need a list that groups the Primary RowIds(the list from the previous question) with the RowIds that match it by the following criteria:</p>
<ul>
<li>on the Primary and Matching rows the following must be the SAME:
<ul>
<li>trainnumber</li>
<li>DayType</li>
<li>Time</li>
</ul></li>
<li>on the Primary and Matching rows the Plate must be DIFFERENT</li>
<li>Wagons must be MORE THAN 1 (The column contains rows with numbers, letters and nothing)</li>
<li>Delete must be empty</li>
</ul>
<p>When matches are found, I need the RowId of the match.</p>
<p>Ideally a dataset like this:</p>
<pre><code>PrimaryRowId Match#1 Match#2 Match#3 Match#4
15674 5465 456 5456 45656
5564 231 132 1321 7862
</code></pre>
<p>It's possible that there's more matches per Primary RowId, but that's ok.</p>
<p>My SQL skills is somewhat limited, so that's why I'm asking you guys. :)</p>
<p>I <em>think</em> it might be something like this:</p>
<pre><code>SELECT RowId
FROM Conversion
WHERE trainnumber=trainnumber and daytype=daytype and
time=time and plate<>plate and Wagons>1 and delete=""
GROUP BY RowId
</code></pre>
<p>But it would only give me one(1) RowId at a time. :-/</p>
| 3 | 1,116 |
fancybox use divs instead of a href
|
<p>How can I use FancyBox or JQuery to create multiple pop-up DIVs that all use the same class (no IDs) on one page? For example, I have 50 products on a single page that all have the same class names.</p>
<pre><code><div class="popup_box"> <!-- OUR PopupBox DIV-->
<h1>This IS A Cool PopUp 1</h1>
<div class="closePopup">Close</div>
</div>
<div class="overlay_box"></div>
<div class="menu_item_container"> <!-- Main Page -->
<h1 class="container_header">Sample 1</h1>
</div>
<div class="popup_box"> <!-- OUR PopupBox DIV-->
<h1>This IS A Cool PopUp 2</h1>
<div class="closePopup">Close</div>
</div>
<div class="overlay_box"></div>
<div class="menu_item_container"> <!-- Main Page -->
<h1 class="container_header">Sample 2</h1>
</div>
<div class="popup_box"> <!-- OUR PopupBox DIV-->
<h1>This IS A Cool PopUp 3</h1>
<div class="closePopup">Close</div>
</div>
<div class="overlay_box"></div>
<div class="menu_item_container"> <!-- Main Page -->
<h1 class="container_header">Sample 3</h1>
</div>
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function() {
// When site loaded, load the Popupbox First
$('.container_header').click( function() {
loadPopupBox();
});
$('.closePopup').click( function(){
unloadPop()
});
});
function loadPopupBox() { // To Load the Popupbox
$('.popup_box').fadeIn("slow");
$('.overlay_box ').fadeIn("slow");
}
function unloadPop(){
$('.popup_box').fadeOut("slow");
$('.overlay_box ').fadeOut("slow");
}
</script>
</code></pre>
<p>THE CSS</p>
<pre><code><style type="text/css">
/* popup_box DIV-Styles*/
.overlay_box{
display:none;
position:fixed;
_position:absolute; /* hack for internet explorer 6*/
height:100%;
width:100%;
top:0;
left:0;
background:#000000;
border:1px solid #cecece;
z-index:1;
}
.popup_box {
display:none; /* Hide the DIV */
position:fixed;
_position:absolute; /* hack for internet explorer 6 */
height:300px;
width:600px;
background:#FFFFFF;
left: 300px;
top: 150px;
z-index:100; /* Layering ( on-top of others), if you have lots of layers: I just maximized, you can change it yourself */
margin-left: 15px;
/* additional features, can be omitted */
border:2px solid #ff0000;
padding:15px;
font-size:15px;
-moz-box-shadow: 0 0 5px #ff0000;
-webkit-box-shadow: 0 0 5px #ff0000;
box-shadow: 0 0 5px #ff0000;
}
.menu_item_container{
background: #d2d2d2; /*Sample*/
width:100%;
height:100%;
}
h1.container_header{
cursor: pointer;
}
/* This is for the positioning of the Close Link */
.closePopup {
font-size:20px;
line-height:15px;
right:5px;
top:5px;
position:absolute;
color:#6fa5e2;
font-weight:500;
}
</style>
</code></pre>
<p>It should work like this example (please click on the product to test pop-up):</p>
<p><a href="http://www.grubhub.com/order.jsp?custId=263838&cityId=5&orderId=18429055&searchable=true&deliverable=true&verified=false&poiSearchTerm=null" rel="nofollow">http://www.grubhub.com/order.jsp?custId=263838&cityId=5&orderId=18429055&searchable=true&deliverable=true&verified=false&poiSearchTerm=null</a></p>
| 3 | 1,788 |
how to update a table with livewire after deleting a row
|
<p>I have a livewire component that shows a table of client contacts, each row of the table has a delete button which calls a confirm box which uses LivewireUI Modal (<a href="https://github.com/wire-elements/modal" rel="nofollow noreferrer">https://github.com/wire-elements/modal</a>). Upon confirming to delete this component deletes the row from the database but it doesn't refresh the table and remove this deleted element.</p>
<p>In the parent component (the table) I have set a listener <code>protected $listeners =['refreshTable' => '$refresh'];</code> and in the child (confirm popup form) I use <code>$this->emitUp( 'refreshTable' );</code> but it doesn't refresh. I have also used <code>$this->emit( 'refreshTable' );</code> but this didn't work either.</p>
<p>Here are the files:
DeleteContact.php</p>
<pre><code><?php
namespace App\Http\Livewire;
use App\Models\ClientContact;
use LivewireUI\Modal\ModalComponent;
class DeleteContact extends ModalComponent
{
public int $contact_id = 0;
public function render()
{
return view('livewire.delete-contact');
}
public function delete()
{
$contact = ClientContact::find( $this->contact_id );
if ( is_null( $contact->title ) || $contact->title === '' ) {
$contact->forceDelete();
} else {
$contact->delete();
}
$this->closeModal();
$this->emitUp( 'refreshTable' );
}
public static function closeModalOnEscape(): bool
{
return false;
}
public static function destroyOnClose(): bool
{
return true;
}
}
</code></pre>
<p>it's blade file (delete-contact.blade.php)</p>
<pre><code><x-modal formAction="delete">
<x-slot name="title">
Delete Contact
</x-slot>
<x-slot name="content">
<input type="hidden" name="contact_id" value="{{ $contact_id }}"/>
Are you sure you wish to delete this contact?
</x-slot>
<x-slot name="buttons">
<x-jet-button class="mx-2" type="submit">
{{ __('Yes') }}
</x-jet-button>
<x-jet-button type="button" class="mx-2" wire:click="$emit('closeModal', ['contact_id' => $contact_id])">
{{ __('No') }}
</x-jet-button>
</x-slot>
</x-modal>
</code></pre>
<p>The component to render the table:
ContactsTable.php</p>
<pre><code><?php
namespace App\Http\Livewire;
use App\Models\Client;
use App\Models\ClientContact;
use Livewire\Component;
class ContactsTable extends Component
{
protected $listeners =['refreshTable' => '$refresh'];
public Client $client;
public $clientContacts;
public function mount( Client $client )
{
$this->clientContacts = ClientContact::where( 'client_id', $client->id )->get();
}
public function render()
{
return view('livewire.contacts-table');
}
public function addNewContact()
{
$client_id = $this->client->id;
$new = ClientContact::make();
$new->client_id = $client_id;
$new->save();
$this->clientContacts = ClientContact::where( 'client_id', $client_id )->get();
}
}
</code></pre>
<p>And its blade file (contacts-table.blade.php)</p>
<pre><code><div class="col-span-6 sm:col-span-4">
<a
class="inline-flex items-center px-4 py-2 bg-gray-800 dark:bg-gray-100 dark:text-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring focus:ring-gray-300 disabled:opacity-25 transition"
wire:click="addNewContact"
>
{{ __('Add') }}
</a>
<p>&nbsp;</p>
<table id="contacts" class="table table-striped table-bordered table-hover">
<thead>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td style="width: 20px;"></td>
</thead>
<tbody>
@foreach( $clientContacts as $contact )
<tr id="{{ $contact->id }}">
<td>
<input name="contact_{{ $contact->id }}_title" class="w-full" type="text" value="{{ $contact->title }}"/>
</td>
<td>
<input name="contact_{{ $contact->id }}_email" class="w-full" type="text" value="{{ $contact->email }}"/>
</td>
<td>
<input name="contact_{{ $contact->id }}_phone_number" class="w-full" type="text" value="{{ $contact->phone_number }}"/>
</td>
<td class="width-8">
<a
class="cursor-pointer"
wire:click="$emit( 'openModal', 'delete-contact',{{ json_encode(['contact_id' => $contact->id]) }} )"
>
DELETE
</a>
</td>
</tr>
@endforeach
</tbody>
</table>
<p class="mt-1 text-sm text-gray-600">
Edit the cells above, click the bin to delete or the + to add a new row to populate with a new contact.
</p>
</div>
</code></pre>
<p>Additionally if it's useful when I click the Add button above the table the new row is added (but this is inside the same component as doesn't have the confirm box)</p>
<p>thanks</p>
| 3 | 2,884 |
Owl Carousel just show 1 item
|
<p>i have problem to show a owl carousel and its just show 1 item,
i want to show 2 or more item
this is my code</p>
<pre><code>`function showNowPlay(data)
{
nowplay.innerHTML = '<div class="home__carousel owl-carousel active" id="flixtv-hero">';
data.forEach(movie => {
data.splice(8);
const {backdrop_path,title,release_date} = movie;
const movieE3 = document.createElement('div');
movieE3.classList.add('home__card');
movieE3.innerHTML= 'my html'
nowplay.appendChild(movieE3).owlCarousel({
});
});
}`
</code></pre>
<p>and html is</p>
<pre><code><div class="home__carousel owl-carousel" id="flixtv-hero">
<div class="home__card">
<a href="details.html">
<img src="img/home/1.jpg" alt="">
</a>
<div>
<h2>Money Plane</h2>
<ul>
<li>Free</li>
<li>Action</li>
<li>2021</li>
</ul>
</div>
<button class="home__add" type="button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M16,2H8A3,3,0,0,0,5,5V21a1,1,0,0,0,.5.87,1,1,0,0,0,1,0L12,18.69l5.5,3.18A1,1,0,0,0,18,22a1,1,0,0,0,.5-.13A1,1,0,0,0,19,21V5A3,3,0,0,0,16,2Zm1,17.27-4.5-2.6a1,1,0,0,0-1,0L7,19.27V5A1,1,0,0,1,8,4h8a1,1,0,0,1,1,1Z"/></svg></button>
<span class="home__rating"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M22,9.67A1,1,0,0,0,21.14,9l-5.69-.83L12.9,3a1,1,0,0,0-1.8,0L8.55,8.16,2.86,9a1,1,0,0,0-.81.68,1,1,0,0,0,.25,1l4.13,4-1,5.68A1,1,0,0,0,6.9,21.44L12,18.77l5.1,2.67a.93.93,0,0,0,.46.12,1,1,0,0,0,.59-.19,1,1,0,0,0,.4-1l-1-5.68,4.13-4A1,1,0,0,0,22,9.67Zm-6.15,4a1,1,0,0,0-.29.88l.72,4.2-3.76-2a1.06,1.06,0,0,0-.94,0l-3.76,2,.72-4.2a1,1,0,0,0-.29-.88l-3-3,4.21-.61a1,1,0,0,0,.76-.55L12,5.7l1.88,3.82a1,1,0,0,0,.76.55l4.21.61Z"/></svg> 9.1</span>
</div>
</code></pre>
<p>it just show 1 item,
how can i show 2-8 item ?
thanks</p>
| 3 | 1,485 |
How can I replace the below while loops with something working on ISE?
|
<p>I'm working on my school project and after I finished it I realized that the code doesn't work on ISE. I can't imagine how should I change the algorithm in order to get what I need => multiple subtractions. </p>
<p>I tried it on Active-HDL too, there's all fine right there. It successfully compiles and works. </p>
<pre><code>process(clk)
variable provi, bac_10, bac_20, bac_50, bac_5, bac_2, bac_1: integer:=0;
begin
if enable='1' and clk='1' and clk'event then
if int_suma_introdusa<int_suma_necesara then
succes<='0';
elsif int_suma_introdusa=int_suma_necesara then
succes<='1';
else
provi:=int_suma_introdusa-int_suma_necesara;
bac_50:=rez_50;
bac_20:=rez_20;
bac_10:=rez_10;
bac_5:=rez_5;
bac_2:=rez_2;
bac_1:=rez_1;
while provi>49 and bac_50>0 loop
provi:= provi-50;
bac_50:= bac_50-1;
end loop;
while provi>19 and bac_20>0 loop
provi:= provi-20;
bac_20:= bac_20-1;
end loop;
while provi>9 and bac_10>0 loop
provi:= provi-10;
bac_10:= bac_10-1;
end loop;
while provi>4 and bac_5>0 loop
provi:= provi-5;
bac_5:= bac_5-1;
end loop;
while provi>1 and bac_2>0 loop
provi:= provi-2;
bac_2:= bac_2-1;
end loop;
while provi>0 and bac_1>0 loop
provi:= provi-1;
bac_1:= bac_1-1;
end loop;
if provi=0 then
succes<='1';
else succes<='0';
end if;
end if;
end if;
end process;
</code></pre>
<p>So could you pleas egive me an idea?</p>
| 3 | 1,166 |
How to Update data and Add new rows
|
<p>I have the <code>Invoice form</code> so sometime I want to update the data of the same Invoice number and add now rows.</p>
<p>I want to update the data and new rows on the same <code>Invoice No</code>, on my code below is update and add <code>one row</code> instead of add more than one rows which i have selected.</p>
<p>supposed the invoice has one row and i want to update by add 10 rows on that Invoice number, so the code below is works but it update one row and add 1 new row instead of 10(news rows).</p>
<p>My controller of update</p>
<pre><code>public function update(Request $request, $inv_no)
{
$data = $request->all();
$date = date ("Y-m-d", strtotime($request->Indate));
$stocks = Stock::where('inv_no', $inv_no)->get();
$i = 0;
foreach ($stocks as $stock) {
Stock::where('inv_no', $inv_no)
->where('id', $stock->id)
->update([
'pid' => $request->pid[$i],
'qty' => $request->qty[$i],
'user_id' => Auth::user()->id,
'Indate'=>$date ,
'supplierName' => $request->supplierName,
'receiptNumber' => $request->receiptNumber,
'truckNumber' => $request->truckNumber[$i],
'driverName' => $request->driverName,
'remark' => $request->remark,
]);
$i++;
}
$totalPid = count($data['pid']);
$totalQty = count($data['qty']);
$totalTruckNumber = count($data['truckNumber']);
// dd($stocks);
if (count($stocks) < $totalPid) {
Stock::create([
'pid' => $request->pid[$totalPid-1],
'qty' => $request->qty[$totalQty-1],
'inv_no' => $request->inv_no,
'user_id' => Auth::user()->id,
'Indate'=>$date,
'supplierName' => $request->supplierName,
'receiptNumber' => $request->receiptNumber,
'truckNumber' => $request->truckNumber[$totalTruckNumber-1],
'driverName' => $request->driverName,
'remark' => $request->remark,
]);
}
return $this->show($inv_no)->with('success', 'GRN Edited Successfully ');
</code></pre>
<p>}</p>
<p>below is the Invoice form which i want to Update and Add new rows.
<a href="https://i.stack.imgur.com/T74is.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T74is.png" alt="enter image description here"></a></p>
<p>So I need the help what can i Add there to update and able to add more rows.</p>
| 3 | 1,205 |
Django template won't let my datetime field pop up or open
|
<p>I've been experiencing a weird error when using django for loop template, whenever I use my "{% for groups in groups %}" for loop, my datetime field won't open, however when I try to use other context for my loop, it just works. I also just simply copy pasted this modal from my other html page since it has the same function. Already checked if there are any conflicts with id and other loops. Also tried inspecting element on the modal's button, and it shows the correct group id. I have been using the same loop for other functions in this html page and it seems to be working fine as well. Any idea on how to debug this issue?</p>
<p><strong>admin.html</strong> </p>
<pre><code>{% for groups in groups %}
<!--start ALLOCATE MODAL -->
<div id="allocateModal-{{groups.id}}" class="modal fade" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="form-horizontal form-label-left">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h3 class="modal-title" id="myModalLabel">Allocate Device</h3>
</div>
<div class="modal-body">
<h2>Device List</h2>
<table class="table-width table table-striped jambo_table">
<thead>
<tr>
<th style="width: 10%"></th>
<th style="width: 30%">Device</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td class="a-center ">
<input type="checkbox" id="routerBox" onchange="enableRQty(this)">
</td>
<td>Router</td>
<td>
<div class="col-md-4">
<input type="text" id="routerQty" class="form-control" data-inputmask="'mask': '9'" placeholder="0" disabled>
</div>
</td>
</tr>
<tr>
<td class="a-center ">
<input type="checkbox" id="switchBox" value="sw" onchange="enableSWQty(this)">
</td>
<td>Switch</td>
<td>
<div class="col-md-4">
<input type="text" id="switchQty" placeholder="0" disabled class="form-control" data-inputmask="'mask': '9'">
</div>
</td>
</tr>
<tr>
<td class="a-center ">
<input type="checkbox" id="terminalBox" value="host" onclick="enableTQty(this)">
</td>
<td>Terminal</td>
<td>
<div class="col-md-4">
<input type="text" id="terminalQty" placeholder="0" disabled class="form-control" data-inputmask="'mask': '9'">
</div>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12" style="padding-right: 0">
<label class="control-label col-md-3" style="width: 17%" for="datetimepicker6">Date</label>
<div class='input-group date' id='datetimepicker6'>
<span class="input-group-addon">
<span class="fa fa-calendar-o"></span>
</span>
<input type='text' class="form-control" />
<!-- <span class="input-group-addon">to</span> -->
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-12" style="padding-left: 0">
<label class="control-label col-md-3" style="width: 12%" for="datetimepicker7">to</label>
<div class='input-group date' id='datetimepicker7'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="fa fa-calendar-o"></span>
</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Allocate</button>
</div>
</div>
</div>
</div>
</div>
<!-- end ALLOCATE MODAL -->
{% endfor %}
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>def adminPage(request):
currentUser = request.user
if currentUser.profile.usertype != 'admin':
return HttpResponseRedirect("/user/")
signupForm = SignUpForm()
newgroupForm = CreateGroupForm()
users = User.objects.all()
groups = Group.objects.all()
grouptodevice = GroupToDevice.objects.all()
devices = Device.objects.all()
context = {
'groups':groups,
'users':users,
'current_user': currentUser,
'newgroupForm': newgroupForm,
'signupForm' : signupForm,
'grouptodevice' : grouptodevice,
'devices':devices,
}
return render(request, 'admin.html', context)
</code></pre>
| 3 | 2,991 |
ComboBox Error: Collection was modified, enumeration operation may not execute
|
<p>I have a combo box that holds a list of values followed by a static "Add New" item. When I select that item, it loads an image and adds the image's file name to the list of values. When I do this, however, the WPF underlying code throws the "collection modified" exception.</p>
<p><strong>XAML:</strong></p>
<pre><code><StackPanel Orientation="Vertical">
<ComboBox x:Name="selector">
<ComboBoxItem IsEnabled="False" Content="---" />
<ComboBoxItem FontStyle="Italic" Content="Add New" Selected="New_Selected" />
</ComboBox>
</StackPanel>
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>public partial class MainWindow : Window
{
List<string> files = new List<string>();
public MainWindow()
{
InitializeComponent();
}
private void RepopulateResourceSelector()
{
// Remove all but the bottom 2 items
while (selector.Items.Count > 2)
{
selector.Items.RemoveAt(0);
}
int index = 0;
// Add all strings in the list to combo box
foreach (var file in files)
{
selector.Items.Insert(index, file);
index++;
}
}
private void New_Selected(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Filter = "Image Files (.bmp, .jpg, .gif, .png, .tiff)|*.bmp;*.jpg;*.gif;*.png;*.tiff";
if (dlg.ShowDialog(this) == true)
{
// Add selected file to the list
string name = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);
files.Add(name);
RepopulateResourceSelector();
}
// Deselect `Add New` item
selector.SelectedIndex = -1;
}
}
</code></pre>
<p><strong>Stack Trace:</strong></p>
<pre><code>System.InvalidOperationException occurred
HResult=0x80131509
Message=Collection was modified; enumeration operation may not execute.
Source=<Cannot evaluate the exception source>
StackTrace:
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.CreateDeltaSelectionChange(List`1 unselectedItems, List`1 selectedItems)
at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(ItemInfo info, Boolean assumeInItemsCollection)
at System.Windows.Controls.ComboBox.NotifyComboBoxItemMouseUp(ComboBoxItem comboBoxItem)
at System.Windows.Controls.ComboBoxItem.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at WpfApp1.App.Main()
</code></pre>
| 3 | 2,120 |
How to pass a button array into a function
|
<p>I'm trying to create a function that will send a serial string to a com port and change colors every time a button is pressed. </p>
<p>I have figured out how to do this with one button, but now I want to make an array of 140 buttons that can all be passed through this function. </p>
<p>My problem is that all 140 buttons perform the function of the first button, not what their individual function should be, which is send a different serial command and turn blue when it is on. </p>
<p>Here is my code:</p>
<pre><code>public partial class Form1 : Form
{
bool[] buttonStatus = new bool[140];
Button[] buttonArray = new Button[140];
private SerialPort LB;//"LB for left bottom module
public Form1()
{
InitializeComponent();
Initializing();
CreatingNewButtons();
}
/// <summary>
/// Initializes Serial ports to be used
/// </summary>
private void Initializing()
{
try
{
LB = new SerialPort();
LB.BaudRate = 57600;
LB.PortName = "COM9";
LB.Open();
}
catch(Exception)
{
MessageBox.Show("error connecting");
}
}
/// <summary>
/// Creates all 140 buttons at startup
/// </summary>
private void CreatingNewButtons()
{
int horizotal = 80;
int vertical = 30;
for (int i = 0; i < buttonArray.Length; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(25, 25);
buttonArray[i].Location = new Point(horizotal, vertical);
if ((i == 10) || (i == 20) || (i == 30) || (i == 40) || (i == 50) ||
(i == 60) || (i == 70) || (i == 80) || (i == 90) || (i == 100) ||
(i == 110) || (i == 120) || (i == 130))
{
vertical = 30;
horizotal = horizotal + 30;
}
else
vertical = vertical + 30;
this.Controls.Add(buttonArray[i]);
// Add a Button Click Event handler
buttonArray[i].Click += new EventHandler(buttonArray_Click);
}
}
void sendStringToAllModules (string stringToSend)
{
LB.WriteLine(stringToSend);//write string text to arduino
}
private void sendStringBtn_Click(object sender, EventArgs e)
{
LB.WriteLine(stringTextBox.Text);//write string text to arduino
}
private void receiveStringBtn_Click(object sender, EventArgs e)
{
receiveStringTextBox.Text = LB.ReadExisting();
}
#region pushbuttonCode
/// <summary>
/// send function index and sends either on or off to leds of modules
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void toggleLEDs(int i)
{
if (!buttonStatus[i])
{
sendStringToAllModules("1;" + i + ";");
buttonArray[i].BackColor = Color.CornflowerBlue;
buttonStatus[i] = !buttonStatus[i];
}
else
{
sendStringToAllModules("2;" + i + ";");
buttonArray[i].BackColor = Color.Gainsboro;
buttonStatus[i] = !buttonStatus[i];
}
}
private void buttonArray_Click(object sender, EventArgs e)//this button works
{
toggleLEDs(0);
}
private void buttonArray1_Click(object sender, EventArgs e)//this one doesn't
{
toggleLEDs(0);
}
#endregion
}
</code></pre>
<p>Any help is greatly appreciated! </p>
| 3 | 1,599 |
Modify class so that ButtonField is unselectable (never has focus)
|
<p>How can I modify below class so that the button field is unselectable (never has focus), and therefore never highlighted ? </p>
<p>Thanks</p>
<pre><code>import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.component.ButtonField;
/**
* Button field with a bitmap as its label.
*/
public class BitmapField extends ButtonField {
private Bitmap bitmap;
private Bitmap bitmapHighlight;
private boolean highlighted = false;
private int width;
private String label;
private Font font;
/**
* Instantiates a new bitmap button field.
*
* @param bitmap the bitmap to use as a label
*/
public BitmapField(Bitmap bitmap, Bitmap bitmapHighlight, String label, int width, Font font) {
this(bitmap, bitmapHighlight, ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER|ButtonField.FIELD_VCENTER
, label, width, font);
}
protected void onFocus(int direction) {
this.setHighlight(true);
super.onFocus(direction);
}
protected void onUnfocus() {
this.setHighlight(false);
super.onUnfocus();
}
public BitmapField(Bitmap bitmap, Bitmap bitmapHighlight, long style,
String label, int width, Font font) {
super(style);
this.bitmap = bitmap;
this.bitmapHighlight = bitmapHighlight;
this.width = width;
this.label = label;
this.font = font;
}
/* (non-Javadoc)
* @see net.rim.device.api.ui.component.ButtonField#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(getPreferredWidth(), getPreferredHeight());
}
/* (non-Javadoc)
* @see net.rim.device.api.ui.component.ButtonField#getPreferredWidth()
*/
public int getPreferredWidth() {
return bitmap.getWidth()+this.width;
}
/* (non-Javadoc)
* @see net.rim.device.api.ui.component.ButtonField#getPreferredHeight()
*/
public int getPreferredHeight() {
return bitmap.getHeight()+20;
}
/* (non-Javadoc)
* @see net.rim.device.api.ui.component.ButtonField#paint(net.rim.device.api.ui.Graphics)
*/
protected void paint(Graphics graphics) {
super.paint(graphics);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap b = bitmap;
if (highlighted)
b = bitmapHighlight;
//graphics.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
graphics.drawBitmap(0, 0, width, height, b, 0, 0);
graphics.setFont(font);
graphics.drawText(label, 0, bitmap.getHeight());
}
public void setHighlight(boolean highlight)
{
this.highlighted = highlight;
}
}
</code></pre>
| 3 | 1,545 |
Socket.IO Transport Close Trouble
|
<p>I'm having a lot of trouble with socket.io. I am coding this to be able to create a room, join it, and then use socket.io to play a game between the people. This is really just a coding challenge to see if I can code something using socket.io from scratch. The problem is that when one client disconnects, all of the other clients disconnect. Here is the code:</p>
<pre><code><script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js" integrity="sha512-MgkNs0gNdrnOM7k+0L+wgiRc5aLgl74sJQKbIWegVIMvVGPc1+gc1L2oK9Wf/D9pq58eqIJAxOonYPVE5UwUFA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
var code;
var codes;
var socket = io();
var log;
var variable = false;
var nick = null;
var me = {};
socket.on("com", function(type, arg1) {
switch (type) {
case "joined":
document.getElementById("getKey").innerHTML = ""
break;
case "dataSendCodes":
codes = arg1;
break;
case "dataSendLogs":
log = arg1;
break;
}
});
socket.on('connect', function() {
console.log("socket connected");
socket.on("disconnect", function(reason) {
console.log("disconnected - " + reason);
console.log(socket.id);
});
});
socket.on('connect_error', function(error) {
console.log(error);
});
function fetchcodes() {
socket.emit("comm","getData");
console.log("Data fetch request sent");
if (log != undefined & codes != undefined) {
return true;
} else {
return false;
}
}
function createRoom() {
fetchcodes();
setTimeout(function() {
createcode();
}, 2500);
}
function createcode() {
for (code = Math.floor(Math.random() * 99999999) + 1; codes[code] != undefined; code = Math.floor(Math.random() * 99999999) + 1) {
console.log("NOPE!");
}
socket.emit("comm", 'createcode', code);
document.getElementById("codeBox").innerHTML = "<p class='JoinText'>Code: " + code + "</p>"
socket.emit("comm", "join", code, nick, true);
me.nick = nick;
me.id = socket.id;
me.room = code;
me.admin = true;
console.log(me.room);
}
</script>
</code></pre>
<p>And server side:</p>
<pre><code>// server.js
// where your node app starts
// we've started you off with Express (https://expressjs.com/)
// but feel free to use whatever libraries or frameworks you'd like
through `package.json`.
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
// make all the files in 'public' available
// https://expressjs.com/en/starter/static-files.html
app.use(express.static("public"));
// https://expressjs.com/en/starter/basic-routing.html
app.get("/", (request, response) => {
response.sendFile(__dirname + "/join.html");
});
app.get("/admin", (request, response) => {
response.sendFile(__dirname + "/twotruthsandalieadmin.html");
});
var Codes = {};
var Log = {};
io.on("connection", function (socket) {
socket.on("disconnect", function() {
var check = io.sockets.clients(Log[socket.id].room);
if (check == 0) {
delete Codes[Log[socket.id].room];
}
delete Log[socket.id];
});
socket.on("comm", function(type, arg1, arg2, arg3) {
console.log("comm");
switch (type) {
case "getData":
console.log("get data");
io.to(socket.id).emit("com","dataSendCodes",Codes);
io.to(socket.id).emit("com","dataSendLogs",Log);
console.log("emitted");
break;
case "join":
socket.join(arg1, function () {
console.log("joined " + socket.id + "to a room");
io.to(arg1).emit("com","joined");
});
Log[socket.id] = {nick: arg2,id: socket.id,room: arg1,admin: arg3};
break;
case "createcode":
Codes[arg1] = arg1;
break;
}
});
});
function reset() {
Log = {};
Codes = {};
}
server.listen(process.env.PORT);
</code></pre>
<p>If it helps here are the dependencies:</p>
<pre><code>{
"//1": "describes your app and its dependencies",
"//2": "https://docs.npmjs.com/files/package.json",
"//3": "updating this file will download and update your packages",
"name": "hello-express",
"version": "0.0.1",
"description": "A simple Node app built on Express, instantly up and running.",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.17.1",
"socket.io": "^4.4.1"
},
"engines": {
"node": "12.x"
},
"repository": {
"url": "https://glitch.com/edit/#!/hello-express"
},
"license": "MIT",
"keywords": [
"node",
"glitch",
"express"
]
}
</code></pre>
<p>This is done on glitch, I don't know if that makes a difference. The disconnect reason is transport close, meaning it lost connection but it only happens when another client is disconnected. There isn't any code that should be closing the connection server side as far as I can see.</p>
<p>Any help is appreciated!</p>
| 3 | 2,635 |
React Redux this.props always return undefined
|
<p>I'm now at React and I'm doing some apps to study, learn more about. Aand right now I'm trying to add the logged user info to redux state, but when I try to check the value of <code>this.props.user</code> my app always returns <code>undefined</code>.</p>
<p>My reducer.js</p>
<pre><code>import { LOG_USER } from '../actions/actions';
let initialState = {
user: {
userName: '',
imageUrl: ''
}
}
const userInfo = (state = initialState, action) => {
switch (action.type) {
case LOG_USER:
return {
...state,
user: action.user
};
default:
return state;
}
}
const reducers = userInfo;
export default reducers;
</code></pre>
<hr>
<p>My actions.js</p>
<pre><code>export const LOG_USER = 'LOG_USER';
</code></pre>
<hr>
<p>My SignupGoogle.js component:</p>
<pre><code>import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import firebase from '../../config/firebase';
import { connect } from 'react-redux'
import { LOG_USER } from '../../actions/actions';
import './SignupGoogle.css'
class SignupGoogle extends Component {
constructor(props) {
super(props);
}
signup() {
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
console.log('---------------------- USER before login')
console.log(this.props.user)
let user = {
userName: result.user.providerData[0].displayName,
imageUrl: result.user.providerData[0].photoURL
}
console.log(user)
this.props.logUser(user)
console.log('---------------------- USER after login')
console.log(this.props.user)
}).catch((error) => {
console.log(error.code)
console.log(error.message)
console.log(error.email)
})
}
render() {
return (
<Button onClick={this.signup} variant="contained" className="btn-google">
Sign Up with Google
<img className='imgGoogle' alt={"google-logo"} src={require("../../assets/img/search.png")} />
</Button>
);
}
}
const mapStateToProps = state => {
return {
user: state.user
};
}
const mapDispatchToProps = dispatch => {
return {
logUser: (user) => dispatch({type: LOG_USER, user: user})
};
}
export default connect(mapStateToProps, mapDispatchToProps)(SignupGoogle);
</code></pre>
<hr>
<p>And my index.js</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux'
import { createStore } from 'redux';
import reducers from './reducers/reducers';
const store = createStore(reducers)
ReactDOM.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
</code></pre>
<p>This is what I can get at my browser log after login with Google firebase:</p>
<p><a href="https://i.stack.imgur.com/MRw35.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MRw35.png" alt="console.log after login with Google firebase"></a></p>
| 3 | 1,283 |
Why update fails because of unique index while there isn't duplicate value?
|
<p>I guess this image explains everything:</p>
<p><a href="https://i.stack.imgur.com/VVbrB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VVbrB.png" alt="enter image description here"></a></p>
<p>See? I'm setting the value of <code>2</code>, but it says <code>0</code> is duplicate. Why? Where that <code>0</code> comes from?</p>
<hr>
<p>Here is the table structure:</p>
<pre><code>-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 04, 2018 at 04:18 PM
-- Server version: 10.1.26-MariaDB
-- PHP Version: 7.1.8
SET
SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET
AUTOCOMMIT = 0;
START TRANSACTION;
SET
time_zone = " + 00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */
;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */
;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */
;
/*!40101 SET NAMES utf8mb4 */
;
--
-- Database: `spy`
--
-- --------------------------------------------------------
--
-- Table structure for table `support_us`
--
CREATE TABLE `support_us` ( `id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL COMMENT 'null means have not logged in', `full_name` varchar(100) CHARACTER
SET
utf8 COLLATE utf8_unicode_ci NOT NULL, `publish_name` tinyint(1) NOT NULL COMMENT '1 means show the name and 0 means don''t', `user_amount` varchar(20) NOT NULL, `final_amount` varchar(20) DEFAULT NULL, `cell_phone` varchar(20) NOT NULL, `trans_id` varchar(20) DEFAULT NULL COMMENT 'null means it''s just a intention (trans_id hasn''t issued yet by pay.ir)', `status_started` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 means the user is getting redirect to bank page and 0 means it couldn''t connect to bank port', `send_error_code` varchar(10) DEFAULT NULL COMMENT 'go to function.php fine, send() function', `status_finished` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 means finished successfully and 0 means failed', `verify_error_code` varchar(10) DEFAULT NULL COMMENT 'go to function.php fine, verify() function', `card_number` varchar(20) DEFAULT NULL, `message` varchar(200) DEFAULT NULL, `date_time` int(10) UNSIGNED NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET = latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `support_us`
--
ALTER TABLE `support_us` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `trans_id` (`trans_id`), ADD KEY `publish_name` (`publish_name`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `support_us`
--
ALTER TABLE `support_us` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 41;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */
;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */
;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */
;
</code></pre>
| 3 | 1,066 |
Strange white rectangle boxes that appear and disappear on website
|
<p>There are strange white rectangle boxes that appear and disappear in a chatroom that I created. They randomly appear at the bottom and right side of the chatroom behind the scroll bars, and I am unsure of the cause. Possibly incorrect CSS of HTML? Inspecting the page does me no justice because the boxes do not show up in my code however they randomly appear whenever they want to.</p>
<p>My site is currently running locally. And perhaps this is a localhost/glitch phenomenon, and possibly the bug will simply go away when I launch the site. However I don't want to risk that, so can someone shed some light on this issue? I need to know whats causing this. Here is what it looks like:</p>
<p><a href="https://i.stack.imgur.com/lCJra.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lCJra.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/bI32q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bI32q.png" alt="enter image description here" /></a></p>
<p>Usually, the scroll bar on the right is black/almost translucent. At the bottom, there is absolutely no need to scroll right or left. However like I said the rectangle just appears.</p>
<p>Should I just change the scroll bar background color? Here is what my HTML looks like:</p>
<pre><code> <div id="chatArea" class="chatroom">
<div id=box class="lemoncakeleft">
<div class="chat" id="chat"></div>
</div>
<form id="messageForm">
<div class="form-group">
<input type="text" required="required" placeholder="Enter your message here" class="enter-message" id="message"/>
</div>
<input class="chatbutton" type="submit" value="Send"/>
</form>
</div>
</code></pre>
<p>I doubt the issue has to do with the input, where I type and send a message. So here is the css for the div <code>id="box"</code></p>
<pre><code>#box {
height: 556px;
width: 313px;
color: #E8E8E8;
text-shadow: 1px 1px 1px rgba(0,0,0,0.3);
word-wrap: break-word;
overflow: scroll;
overflow-y: auto;
}
</code></pre>
<p>I think it has to do with the <code>overflow</code> properties. Which is disappointing because i need those properties for the chat to function appropriately. Also, when viewing the site on my tablet and cell phone, the rectangles are not there. So what exactly is the issue?</p>
<p>Any suggestions or advice is appreciated. Thank you in advance.</p>
<p>-JJ</p>
| 3 | 1,122 |
Unable to get login to work using scala with Play Framework
|
<p>I am trying to create login functionality for a website built in the play framework. When credentials of an existing user is entered into the html view, and the submit (login) button is clicked the login page doesn't do anything.</p>
<p>LoginController:</p>
<pre><code> class LoginController @Inject() extends Controller {
def login(Email:String, password:String): Boolean = {
val user = CustomerLogin.findCustomer(Email).get
var status:Boolean = false
if(user.password == password) {
//log the user in
status = true
} else {
status = false
}
status
}
def index = Action {
implicit request =>
Ok(views.html.loginOurs(LoginForm))
}
private val LoginForm: Form[CustomerLogin] = Form(mapping(
"Email" -> nonEmptyText,
"password" -> nonEmptyText)(CustomerLogin.apply)(CustomerLogin.unapply))
def save = Action {
implicit request =>
val newLoginForm = LoginForm.bindFromRequest()
newLoginForm.fold(hasErrors = {
form =>
Redirect(routes.LoginController.index()).flashing(Flash(form.data) +
("error" -> Messages("validation.errors")))
}, success = {
newLogin =>
Redirect(routes.HomeController.home()).flashing("success" -> Messages("customers.new.success", newLogin.Email))}
)
}
def newLogin = Action {
implicit request =>
val form = if(request2flash.get("error").isDefined)
LoginForm.bind(request2flash.data)
else
LoginForm
Ok(views.html.loginOurs(form))
}
}
</code></pre>
<p>loginOurs.scala.html (some)</p>
<pre><code><div id="content">
@main(Messages("login.form")) {
<h2>@Messages("login form")</h2>
@helper.form(action = routes.LoginController.save) {
<fieldset>
<legend>
@Messages("customer.details", Messages("customer.new"))
</legend>
@helper.inputText(LoginForm("Email"))
@helper.inputText(LoginForm("Password"))
</fieldset>
<p>
<input type="submit" class="btn-primary" value='@Messages("submit")'>
</p>
}
}
</div>
</code></pre>
<p>Routes (Login stuff only)</p>
<pre><code>GET /login controllers.LoginController.newLogin
POST /login controllers.LoginController.save
GET /login/:Email controllers.LoginController.login3(Email:String)
GET /login controllers.HomeController.confirm(Email:String)
</code></pre>
<p>Any help given would be greatly appreciated.</p>
<p>Many thanks
Jackie</p>
| 3 | 1,140 |
Onsen UI - Toolbar is not fixed to top on Cordova WP Universal App
|
<p>I am developing a cordova application with onsen ui.</p>
<p>I already found some problems that occur only on windows phone (i assume that this is the case because wp is not supported for such a long time)
. But there is 1 problem that i really need to fix.It seems that the ons-toolbar element is not fixed to the top in windows phone. If i scroll down, the toolbar also moves with the content. This doesn't happen on android.</p>
<p>Thats how i build up my page (the following code is inside an ons-sliding-menu):</p>
<pre><code><ons-page ng-controller="findUsersController">
<ons-toolbar fixed-style>
<div class="left">
<ons-toolbar-button ng-click="menu.toggleMenu()">
<ons-icon icon="fa-bars">
</ons-toolbar-button>
</div>
<!--<div class="left"><ons-back-button ons-if-platform="ios">Back</ons-back-button></div>-->
<div class="center"><h3 style="display:inline;">Connect<span style="color:cornflowerblue;">Us</span></h3></div>
</ons-toolbar>
<ons-pull-hook ng-action="findUsers($done)" var="loader">
<span ng-switch="loader.getCurrentState()">
<span ng-switch-when="initial"><ons-icon size="35px" icon="ion-arrow-down-a"></ons-icon> Pull down to refresh</span>
<span ng-switch-when="preaction"><ons-icon size="35px" icon="ion-arrow-up-a"></ons-icon> Release to refresh</span>
<span ng-switch-when="action"><ons-icon size="35px" spin="true" icon="ion-load-d"></ons-icon> Loading data...</span>
</span>
</ons-pull-hook>
<ons-list>
<ons-list-item ng-show="users.length === 0">
<div class="info">
Pull down to refresh
</div>
</ons-list-item>
<ons-list-item class="item" ng-repeat="user in users">
<ons-row>
<ons-col width="80px">
<img ng-src="http://lorempixel.com/60/60/?{{user.rand}}" class="item-thum" />
</ons-col>
<ons-col>
<p class="item-desc">{{ user.username }}</p>
</ons-col>
</ons-row>
</ons-list-item>
</ons-list>
</ons-page>
</code></pre>
<p>Initially everything shows up correct, but when i pull down to refresh, the toolbar moves down as well and the ons-pull-hook doesn't react. How can this be? i mean the toolbar is in no scrollable element.</p>
<p>Is there anyone who has an idea how to fix this problem?</p>
| 3 | 1,203 |
Get and store all changed values in data
|
<p>I am trying to create an "activity log" type thing on my server. I am using Angular and Mongoose on a node server. What I am trying to achieve is compare the request body with data stored in the DB by doing a deep diff.</p>
<p>So, whenever an API is hit, I am running this function:</p>
<pre><code>createActivityInformation(currentObject, updatedObject) {
let information = [];
function getChangedItem(currentItem, updatedItem, key, prop){
if(!currentItem || !updatedItem) return
// IF OBJECTS
if(typeof(updatedItem) === "object" && !Array.isArray(updatedItem)){
for(let prop in updatedItem){
getChangedItem(currentItem[prop], updatedItem[prop], key, prop)
}
}
else if(Array.isArray(updatedItem)){
}
else{
if(key != 'updatedAt' && (currentItem && updatedItem) && (currentItem.toString() !== updatedItem.toString())){
// CHECK FOR DATE - THIS IS ADDED BECAUSE DATES ARE COMPARED DIFFERENT THAN TO STRINGS
if(currentItem instanceof Date && !isNaN(currentItem)){
if(new Date(currentItem).getTime() != new Date(updatedItem).getTime()){
information.push({
'changeFrom': { key: key, value: currentItem, prop: prop},
'changeTo': { key: key, value: updatedItem, prop: prop}
})
}
} else {
information.push({
'changeFrom': { key: key, value: currentItem, prop: prop},
'changeTo': { key: key, value: updatedItem, prop: prop}
})
}
}
}
}
for(let key in updatedObject){
getChangedItem(currentObject[key], updatedObject[key], key)
}
return information;
}
</code></pre>
<p>Essentially what I am trying to do is store the original data, and the changed data. But I cannot seem to get it to work perfectly. The method is supposed to do a deep diff to compare everything, but also exclude some fields, like for instance <code>updatedAt</code>, or <code>_id</code>.</p>
<p>I took a look at the npm package <code>deep-diff</code>, but that did not work. That even compares the mongoose wrappers, but also compares for instance strings with booleans which then gets returned. But I also want to save the current data as well as the updated data.</p>
<p>Is there maybe something else I can look at that might solve my problem?</p>
<p><strong>EDIT</strong>
Normal objects, strings, and numbers are fine. But nested objects, arrays and booleans seem to be giving me a hard time.</p>
<p>here is a fiddle:
<a href="https://jsfiddle.net/xgpcm0h3/" rel="nofollow noreferrer">https://jsfiddle.net/xgpcm0h3/</a></p>
| 3 | 1,380 |
how can i render an array using different styling according to a specific property in this case message.senderEmail
|
<pre><code> function AlignFeature(){
const [allMessages, setAllMessages] = useState([]);
useEffect(()=>{
MessageService.getAllMessages().then(res=>{
setAllMessages(res.data);
});
}, []);
return (
<Container>
<Row>
<Col md={{ span: 6, offset: 0}}>
<div>
<div><Button color='warning'
onclick={MessageService.deleteChat}>
delete chat</Button></div>
<div className='chat'>
<div className='sentMes'>{
allMessages.map(message =>
<div key = {message.id}
className='sentMessages'>
<p
> {message.message} </p>
</div>
)}
</div>
</div>
<div style={{position:'static'}}>
<MessageForm />
</div>
</div>
</Col>
<Col md={{ span: 3, offset: 0}}> <UploadFiles /></Col>
</Row>
</Container>
);
}
export default AlignFeature;
</code></pre>
<p>properties of message are(id, message, receiverEmail, senderEmail)
after the map function i want to render message.message either left or right by checking if message.receiverEmail compares to an email stored in localStorage. if message.receiverEmail == localStorage.getItem('email') display right else display left</p>
| 3 | 1,317 |
how to extract particular data using pig script from web crawled data (nutch)
|
<p>This sample crawl data using nutch 2.3.1 where i need to take title and urls internal links and external links attached with website any suggestion most welcome.</p>
<p>I used this command to import data from hbase to pig</p>
<pre><code>`data9 = load 'hbase://htest15_webpage' using org.apache.pig.backend.hadoop.hbase.HBaseStorage('f:cnt', '-loadKey true');
</code></pre>
<p>`</p>
<pre><code>column=f:cnt, timestamp=1487743991250, value=<!DOCTYPE htm
l>\x0D\x0A<!--[if IE 7]>\x0D\x0A<html class="ie ie7" lang=
"en-US" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns
/fb#">\x0D\x0A<![endif]-->\x0D\x0A<!--[if IE 8]>\x0D\x0A<h
tml class="ie ie8" lang="en-US" prefix="og: http://ogp.me/
ns# fb: http://ogp.me/ns/fb#">\x0D\x0A<![endif]-->\x0D\x0A
<!--[if !(IE 7) | !(IE 8) ]><!-->\x0D\x0A<html lang="en-U
S" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#"
>\x0D\x0A<!--<![endif]-->\x0D\x0A<head>\x0D\x0A <meta cha
rset="UTF-8" /> \x0D\x0A <meta name="viewport" content="w
idth=device-width" /> \x0D\x0A \x0D\x0A<title>www.hardhe
ro.com</title>\x0A\x0A<!-- SEO Ultimate (http://www.seodes
ignsolutions.com/wordpress-seo/) -->\x0A\x09<meta name="de
scription" content="hardhero.com blog that provides intere
sting articles on general topics and ideas." />\x0A\x09<me
ta name="keywords" content="Internet Blog,SEO Blog,Interne
t Marketing Guide" />\x0A\x09<meta property="og:type" cont
ent="blog" />\x0A\x09<meta property="og:title" content="ww
w.hardhero.com" />\x0A\x09<meta property="og:url" content=
"http://hardhero.com/" />\x0A\x09<meta property="og:site_n
ame" content="www.hardhero.com" />\x0A\x09<meta name="twit
ter:card" content="summary" />\x0A<!-- /SEO Ultimate -->\x
0A\x0A<link rel="alternate" type="application/rss+xml" tit
le="www.hardhero.com &raquo; Feed" href="http://hardhero.c
om/feed/" />\x0A<link rel="alternate" type="application/rs
s+xml" title="www.hardhero.com &raquo; Comments Feed" href
="http://hardhero.com/comments/feed/" />\x0A\x09\x09<scrip
t type="text/javascript">\x0A\x09\x09\x09window._wpemojiSe
ttings = {"baseUrl":"http:\x5C/\x5C/s.w.org\x5C/images\x5C
/core\x5C/emoji\x5C/72x72\x5C/","ext":".png","source":{"co
ncatemoji":"http:\x5C/\x5C/hardhero.com\x5C/wp-includes\x5
C/js\x5C/wp-emoji-release.min.js?ver=4.2.11"}};\x0A\x09\x0
9\x09!function(a,b,c){function d(a){var c=b.createElement(
"canvas"),d=c.getContext&&c.getContext("2d");return d&&d.f
illText?(d.textBaseline="top",d.font="600 32px Arial","fla
g"===a?(d.fillText(String.fromCharCode(55356,56812,55356,5
6807),0,0),c.toDataURL().length>3e3):(d.fillText(String.fr
omCharCode(55357,56835),0,0),0!==d.getImageData(16,16,1,1)
.data[0])):!1}function e(a){var c=b.createElement("script"
);c.src=a,c.type="text/javascript",b.getElementsByTagName(
"head")[0].appendChild(c)}var f,g;c.supports={simple:d("si
mple"),flag:d("flag")},c.DOMReady=!1,c.readyCallback=funct
ion(){c.DOMReady=!0},c.supports.simple&&c.supports.flag||(
g=function(){c.readyCallback()},b.addEventListener?(b.addE
ventListener("DOMContentLoaded",g,!1),a.addEventListener("
load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onr
eadystatechange",function(){"complete"===b.readyState&&c.r
eadyCallback()})),f=c.source||{},f.concatemoji?e(f.concate
moji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(
window,document,window._wpemojiSettings);\x0A\x09\x09</scr
ipt>\x0A\x09\x09<style type="text/css">\x0Aimg.wp-smiley,\
x0Aimg.emoji {\x0A\x09display: inline !important;\x0A\x09b
order: none !important;\x0A\x09box-shadow: none !important
;\x0A\x09height: 1em !important;\x0A\x09width: 1em !import
ant;\x0A\x09margin: 0 .07em !important;\x0A\x09vertical-al
ign: -0.1em !important;\x0A\x09background: none !important
;\x0A\x09padding: 0 !important;\x0A}\x0A</style>\x0A<link
rel='stylesheet' id='es-widget-css-css' href='http://hard
hero.com/wp-content/plugins/email-subscribers/widget/es-wi
dget.css?ver=4.2.11' type='text/css' media='all' />\x0A<li
nk rel='stylesheet' id='shootingstar-style-css' href='htt
p://hardhero.com/wp-content/themes/shootingstar/style.css?
ver=4.2.11' type='text/css' media='all' />\x0A<link rel='s
tylesheet' id='shootingstar-elegantfont-css' href='http:/
/hardhero.com/wp-content/themes/shootingstar/css/elegantfo
</code></pre>
<p>></p>
| 3 | 3,232 |
React Native how to mock PixelRatio on 1 specific test
|
<p>I am having trouble testing my snapshot in react-native, to be more specific it's the PixelRatio I am having troubles with.</p>
<p>Code speaks more than words - I've simplified the code and removed all the noise:</p>
<p><strong>The component:</strong></p>
<pre><code>const Slide = (props) => (
<Image
source={props.source}
style={PixelRatio.get() === 2 ?
{ backgroundColor: 'red' } :
{ backgroundCoor: 'green' }}
/>
);
</code></pre>
<p><strong>The Snapshot test</strong>:</p>
<pre><code>import { Platform } from 'react-native';
describe('When loading the Slide component', () => {
it('should render correctly on ios', () => {
Platform.OS = 'ios';
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
describe('on devices with a pixelRatio of 2', () => {
it('it should render correctly', () => {
jest.mock('PixelRatio', () => ({
get: () => 2,
roundToNearestPixel: jest.fn(),
}));
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
});
});
</code></pre>
<p>But this doesn't work and after some digging I found a <a href="https://github.com/facebook/jest/issues/2582" rel="nofollow noreferrer">bug on github</a> that was already resolved - apparently you need to use <a href="https://github.com/facebook/jest/issues/2582#issuecomment-284514827" rel="nofollow noreferrer">beforeEach</a>. But that seems also not to be working or I am doing it wrong?</p>
<p><strong>The Snapshot test with the suggested solution of github</strong>:</p>
<pre><code>import { Platform } from 'react-native';
describe('When loading the Slide component', () => {
it('should render correctly on ios', () => {
Platform.OS = 'ios';
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
describe('on devices with a pixelRatio of 2', () => {
it('it should render correctly', () => {
beforeEach(() => {
jest.mock(pxlr, () => ({
get: () => 2,
roundToNearestPixel: jest.fn(),
}));
const pxlr = require('react-native').PixelRatio;
}
const tree = renderer.create(
<Provider store={store}>
<Slide />
</Provider>,
).toJSON();
expect(tree).toMatchSnapshot();
});
});
});
</code></pre>
| 3 | 1,131 |
Inserting new record from AngularJS using Web API
|
<p>Hi I'm a newbie in web development and I'm having some trouble in inserting new data in my database.</p>
<p>First, there's an error in dbcontext.Tbl_Articles.Add(adto);
It says, cannot convert WebAPI.Models.Articles to WebAPI.DataLayer.Tbl_Articles</p>
<p>Another thing is, whenever I run my Web API, it says something like this - {"Message":"The requested resource does not support http method 'GET'."}
script file:</p>
<pre><code>$scope.AddArticle = function ()
{
var data =
{
Category: $scope.Category,
IsCarousel: $scope.IsCarousel,
IsImportant: $scope.IsImportant,
HeaderImage: $scope.HeaderImage,
Title: $scope.Title,
ByLine: $scope.ByLine,
Content: $scope.Content,
Author: $scope.Author,
PublishStartDate: $scope.PublishStartDate_date + " " + $scope.PublishStartDate_time + $scope.PublishStartDate_time_ext,
PublishEndDate: $scope.PublishEndDate_date + " " + $scope.PublishEndDate_time + $scope.PublishEndDate_time_ext
};
$http(
{
method: 'POST',
url: 'http://project-aphrodite-uat-service.azurewebsites.net/api/articles/createarticle',
data: JSON.stringify(data)
})
.then(function successCallback(response)
{
console.log(response);
},
function errorCallback(response)
{
console.log("error" + response);
});
};
</code></pre>
<p>ArticlesController.cs:</p>
<pre><code> [HttpPost]
[Route("api/articles/createarticle")]
public Articles CreateArticle(Articles obj)
{
DataLayer.DataLayer dl = new DataLayer.DataLayer();
dl.CreateArticle(obj);
return obj;
}
</code></pre>
<p>DataLayer.cs:</p>
<pre><code> public string CreateArticle(Articles obj)
{
var adto = new Articles();
adto.Category = obj.Category;
adto.IsCarousel = obj.IsCarousel;
adto.IsImportant = obj.IsImportant;
adto.HeaderImage = obj.HeaderImage;
adto.Title = obj.Title;
adto.ByLine = obj.ByLine;
adto.Content = obj.Content;
adto.Author = obj.Author;
adto.PublishStartDate = obj.PublishStartDate;
adto.PublishEndDate = obj.PublishEndDate;
using (ArticleEntities dbcontext = new ArticleEntities())
{
dbcontext.Tbl_Articles.Add(adto);
dbcontext.SaveChanges();
return "test";
}
}
</code></pre>
<p>I hope someone could help me fix these. Thankie so much!</p>
| 3 | 1,163 |
Token authorization in swagger in ASP.NET
|
<p>I am documenting the API of my application through Swagger, which works with validation through a session token, that is, through a username and password a token is generated for a certain time that allows the user to navigate the site. What I need is for swagger to capture this session token and place it in the header of the requests for the rest of the API methods automatically, the only thing I could achieve so far is to pass the token as a parameter, but doing it manually. The idea is to make it automatic. I leave the configuration of SwaggerConfig.cs that I carry for now.</p>
<pre class="lang-cs prettyprint-override"><code>public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
// HABILITAMOS SWAGGER.
.EnableSwagger(c =>
{
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\bin\";
var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".xml";
var commentsFile = Path.Combine(baseDirectory, commentsFileName);
c.SingleApiVersion("v1", "API");
c.OperationFilter<AddRequiredHeaderParameter>();
c.PrettyPrint();
c.ApiKey("apikey")
.Description("API Key Authentication")
.Name("Bearer")
.In("header");
c.IgnoreObsoleteActions();
c.IgnoreObsoleteProperties();
c.DescribeAllEnumsAsStrings();
.EnableSwaggerUi(c =>
{ c.DocumentTitle("Documentación API");
c.EnableApiKeySupport("apikey", "header");
});
}
}
</code></pre>
<p>In turn, add a class to validate the application from where it is made on request</p>
<pre class="lang-cs prettyprint-override"><code>public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters.Add(new Parameter
{
name = "AuthorizedClient",
@in = "header",
type = "intenger",
description = "Aplicacion",
required = true,
@default = axaxax
});
operation.parameters.Add(new Parameter
{
name = "ClientKey",
@in = "header",
type = "string",
description = "Cliente",
required = true,
@default = "bxbxbx"
});
operation.parameters.Add(new Parameter
{
name = "Authorization",
@in = "header",
type = "apikey",
description = "Token de sesión",
});
}
}
</code></pre>
| 3 | 1,356 |
Trying to understand the use of the populate method
|
<p>I see that one way we use populate is to put one document from another collection into a "parent" collection. I was just going through <a href="https://stackoverflow.com/questions/34984199/why-wont-my-refs-populate-documents">this</a> question and I was hoping someone could explain the answer to me better. And show me a practical use. Here is an example from the answer.</p>
<pre><code>var PersonSchema = new mongoose.Schema({
t: String
}, {collection: 'persons'});
var User = mongoose.model('User', PersonSchema.extend({
_id: String,
name: String
}));
var ParentSchema = new mongoose.Schema({
s: String
}, {collection: 'parent'});
var Like = mongoose.model('Like', ParentSchema.extend({
_id: String,
user_id: {
type: String,
ref: 'User'
}
}));
</code></pre>
<p>Insert Data into DB,</p>
<pre><code>var user = new User({
t: 't1',
_id: '1234567',
name: 'test'
});
var like = new Like({
s: 's1',
_id: '23456789',
});
user.save(function(err, u){
if(err)
console.log(err);
else {
like.user_id = u._id;
console.log(like);
like.save(function(err) {
if (err)
console.log(err);
else
console.log('save like and user....');
});
}
});
</code></pre>
<p>Query by</p>
<pre><code>Like.findOne({}).populate('user_id').exec(function(err, doc) {
if (err)
console.log(err);
else
console.log(doc);
});
</code></pre>
<p>And the result is</p>
<pre><code>{ _id: '23456789',
__t: 'Like',
user_id: { _id: '1234567', __t: 'User', t: 't1', name: 'test', __v: 0 },
s: 's1',
__v: 0 }
</code></pre>
<p>QUESTION </p>
<ol>
<li>where does <code>__t: 'User'</code> come from?</li>
<li>I was thinking that using populate() or ref that would separate the collections but it looks like at the end the like collection has the users document in it. I think I wanted to use populate so I could make a document smaller.
3.Also if someone really wanted to help explain this to me I have an example that I have been trying to do and I don't know if I should use populate but if I should it would be great if you show me how. Here is the example.</li>
</ol>
<p>You have </p>
<ol>
<li>doctors </li>
<li>patients </li>
<li>information about the practice</li>
</ol>
<p>There could be like a 1000 doctors and lots of patients for each doctor. and the information will be about their practice(like how many employees they have). so I feel that there should be a separation of concern.(one reason is to prevent a single document for a patient from getting to big). So If we're going with the populate method If you could explain how to set it up for this case. I guess I could have a doctor as a parent and a child refs for patients and another child refs for information about practice. so maybe there should be an array of objectId for the patients and an array for Other information</p>
| 3 | 1,076 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.