id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23532600
|
The provided request does not include an access token. An access token is
required in order to request this resource.
the code is relatively simple; I'm including the library, calling the initialiser with the nameidentifier claim I get from WIF and then requesting the me path.
from the error message I surmise I failed to provide an access token... but wouldn't my app have this already since I successfully retrieved the claim?
here's my code:
<script src="https://js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/javascript">
WL.init({ client_id: 'O0UpnnhoiFljBJAtTxhVliu4qtbUWoEVxdgfK7SBR+M=' });
WL.api({ path: "me", method: "GET" }, function (response) {
// response.error.message
});
* update *
it occurred to me perhaps I need to log into the system so I now have:
WL.init({ client_id: 'O0UpnnhoiFljBJAtTxhVliu4qtbUWoEVxdgfK7SBR+M=' });
WL.login();
WL.api({ path: "me", method: "GET" }, function (response) {
but same error...
A: so it was a little more complicated... apparently one has to create an application with the LiveID system at:
https://manage.dev.live.com/
the site give you a ClientID and then the code needs to be like this:
<script src="https://js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/javascript">
WL.init({ client_id: '#YOUR-CLIENT-ID-HERE#' });
WL.login({ scope: ["wl.signin"] });
WL.api({ path: "me", method: "GET" }, function (response) {
alert(response.first_name + ' ' + response.last_name);
});
interestingly, the ekkis I see myself logged in as everywhere doesn't appear anywhere and I'm confused now but I think I've been using a Passport account, thinking it was a LiveID account. I'm not sure I understand what the difference is but now that I've configured my LiveID account to have a first/last name it all works.
one final note: creating the app on the live.com site requires one to provide a return url. when the WL.login() gets called, the browser pops up a window requesting the user for permissions (even though s/he has already signed on). When the user clicks Ok, the return url is loaded INTO THAT WINDOW. grr... so now you have to have a special page that all it does is close the window (unless someone else here can suggest how it's supposed to work).
* update *
what I had wanted was the bloody e-mail (I can get it from all the other IPs). so to do that:
WL.login({ scope: ["wl.signin", "wl.emails"] });
and then:
WL.api({ path: "me", method: "GET" }, function (response) {
$('#Auth .SignedIn').html(response.emails.account);
});
that will get the e-mail address associated with the account. there are other e-mails available, see: http://msdn.microsoft.com/en-us/library/hh243648.aspx#user
| |
doc_23532601
|
from sympy import symbols
alpha, beta, delta, gamma = symbols("alpha,beta,delta,gamma")
but this feels terribly wasteful/redundant. I think the answers to this question get me most of the way there; ideally I'd like a function where I could say
foo(("alpha", "beta", "delta", "gamma"))
(or possibly foo("alpha", "beta", "delta", "gamma"), whichever seems to be more Pythonic) and have these symbols added to my environment.
A: I think this (a slight modification of the examples given in the linked question) will do it:
def makesyms(s):
globals().update(dict(zip(s, symbols(s))))
return None
makesyms(("a", "b", "c"))
or
def makesyms2(*s):
globals().update(dict(zip(s, symbols(s))))
return None
makesyms2("A", "B", "C")
| |
doc_23532602
|
I have a DataGrid that has a DataGridTemplateColumn, the template of which contains a ComboBox control. My problem is that when the displayed member of the selected item is too long to fit into the width of the ComboBox, then the width of the ComboBox does not expand to accommodate the width of the displayed memeber, as it does if the same ComboBox is not in the DataGrid.
Working Example
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<DataGrid Height="150"
Margin="0,4,0,0"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserResizeColumns="False"
HorizontalAlignment="Stretch"
ColumnWidth="SizeToCells"
HeadersVisibility="Column"
AutoGenerateColumns="False"
RowHeaderWidth="0"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=Entities, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding Path=SelectedEntity}"
SelectionUnit="FullRow"
SelectionMode="Single">
<DataGrid.Resources>
<DataTemplate x:Key="TextBox_Template">
<TextBox Text="{Binding Path=Text}" Margin="2,2,2,2"/>
</DataTemplate>
<DataTemplate x:Key="ComboBox_Template">
<ComboBox Margin="2,2,2,2"
Width="Auto"
ItemsSource="{Binding Path=DataContext.AvailableActions,
Mode=OneTime,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
SelectedValue="{Binding Path=Action, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Key"
DisplayMemberPath="Value"
IsEditable="False"
IsSynchronizedWithCurrentItem="False"/>
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Width="*"
CanUserReorder="False" CanUserResize="False"
CellTemplate="{StaticResource TextBox_Template}"
Header="Text Field"/>
<DataGridTemplateColumn Width="Auto"
CanUserReorder="False" CanUserResize="False"
CellTemplate="{StaticResource ComboBox_Template}"
Header="Action"/>
</DataGrid.Columns>
</DataGrid>
<Separator Margin="0,5,0,5"/>
<StackPanel Orientation="Horizontal">
<Button Content="Add Row" Margin="2,2,2,2"
Command="{Binding AddRowCommand}"/>
<Button Content="Remove Row" Margin="2,2,2,2"
Command="{Binding RemoveRowCommand}"/>
</StackPanel>
<Separator Margin="0,5,0,5"/>
<ComboBox Width="Auto"
ItemsSource="{Binding Path=AvailableActions}"
SelectedValuePath="Key"
DisplayMemberPath="Value"
IsEditable="False"
HorizontalAlignment="Left"/>
</StackPanel>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public static Dictionary<ActionType, string> AvailableActions { get; set; }
public EntityClass SelectedEntity { get; set; }
public ObservableCollection<EntityClass> Entities { get; set; }
public AddRowCommandClass AddRowCommand { get; set; }
public RemoveRowCommandClass RemoveRowCommand { get; set; }
static MainWindow()
{
AvailableActions = new Dictionary<ActionType, string>()
{
{ActionType.Accept, "Accept the text"},
{ActionType.Reject, "Reject the text"},
{ActionType.Refer, "Refer the text"},
{ActionType.Postpone, "Postpone the text"},
};
}
public MainWindow()
{
Entities = new ObservableCollection<EntityClass>()
{
new EntityClass() { Text = "First Example Text", Action = ActionType.Accept},
new EntityClass() { Text = "Second Example Text", Action = ActionType.Reject},
new EntityClass() { Text = "Third Example Text", Action = ActionType.Refer},
};
AddRowCommand = new AddRowCommandClass(this);
RemoveRowCommand = new RemoveRowCommandClass(this);
InitializeComponent();
}
public enum ActionType
{
Accept,
Reject,
Refer,
Postpone,
}
public class EntityClass
{
public string Text { get; set; }
public ActionType Action { get; set; }
}
public class AddRowCommandClass : ICommand
{
public event EventHandler CanExecuteChanged;
private MainWindow _window;
public AddRowCommandClass(MainWindow window)
{
_window = window;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_window.Entities.Add(new EntityClass() { Text = "Hello World!", Action = ActionType.Postpone });
}
}
public class RemoveRowCommandClass : ICommand
{
public event EventHandler CanExecuteChanged;
private MainWindow _window;
public RemoveRowCommandClass(MainWindow window)
{
_window = window;
}
public bool CanExecute(object parameter)
{
return _window.SelectedEntity != null;
}
public void Execute(object parameter)
{
_window.Entities.Remove(_window.SelectedEntity);
_window.SelectedEntity = null;
_window.PropertyChanged?.Invoke(_window, new PropertyChangedEventArgs("SelectedEntity"));
}
}
}
}
Steps to reproduce
*
*First observe that the ComboBox at the bottom of the page changes size as the size of it's selected value changes.
*Next add a new row to the DataGrid or edit the ComboBox in one of the already present rows to select the "Postpone the text" option; notice how the ComboBox doesn't change size to fit the larger text, leading to the text being clipped.
*Finally resize the window to a larger size with one of the rows having selected "Postpone the text", and notice how the ComboBox now increases in width to accommodate the longer text without clipping.
Conclusion/Question
My question is how can I force the ComboBox controls to automatically accommodate the width of their selected item, and increase the width of the grid row if necessary to do so. I want it such that the selected text will never be clipped, even if this means modifying the width of particular columns in the DataGrid to accommodate.
A: I would suggest setting the width of the second column from "auto" to "*", just like you did in the first column. And then setting a MaxWidth so the combobox wont get to big when sizing.
<DataGridTemplateColumn Width="*" MaxWidth="200"
CanUserReorder="False" CanUserResize="False"
CellTemplate="{StaticResource ComboBox_Template}"
Header="Action"/>
A: The problem is reproducable with a lot simpler datagrid: just place a star-sized column in front of another column that is not star-sized. The Layout process will not try to shrink the columns to the left in order to give columns to the right more space as long as the grid size as a whole stays the same.
The following solution is based on https://stackoverflow.com/a/5651287/5265292
Establish some event that indicates a possibly necessary column resize, then remove the star size column widths, update the layout, restore the column widths. In my example, I used the SelectionChanged event and need to dispatch the layout update for it to work:
void dg1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.OriginalSource is ComboBox)
{
Dispatcher.BeginInvoke(new Action(() =>
{
dg1.Columns[0].Width = new DataGridLength();
dg1.UpdateLayout();
dg1.Columns[0].Width = new DataGridLength(1, DataGridLengthUnitType.Star);
}));
}
}
My sample XAML with items sources in code behind:
<Grid x:Name="grid1">
<Grid.Resources>
<CollectionViewSource x:Key="ComboBoxItemsSource" Source="{Binding ComboItems}"/>
</Grid.Resources>
<DataGrid
x:Name="dg1"
ItemsSource="{Binding DataItems}"
AutoGenerateColumns="False"
SelectionChanged="dg1_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn
Width="*"/>
<DataGridComboBoxColumn
Header="B"
ItemsSource="{Binding Source={StaticResource ComboBoxItemsSource}}"
SelectedItemBinding="{Binding Text}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
For sake of completeness, the initialization and viewmodels:
public MainWindow()
{
InitializeComponent();
grid1.DataContext = vm = new MyViewModel()
{
DataItems =
{
new ItemVM(),
},
ComboItems =
{
"A",
"AAAAAAAAAAAAAAAAAAAAAAA"
}
};
}
public class MyViewModel
{
private ObservableCollection<ItemVM> _DataItems = new ObservableCollection<ItemVM>();
public ObservableCollection<ItemVM> DataItems
{
get { return _DataItems; }
}
private ObservableCollection<string> _ComboItems = new ObservableCollection<string>();
public ObservableCollection<string> ComboItems
{
get { return _ComboItems; }
}
}
public class ItemVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent([CallerMemberName]string prop = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(prop));
}
private string _Text;
public string Text
{
get { return _Text; }
set { _Text = value; RaisePropertyChangedEvent(); }
}
}
A: Try by adding the DataTemplate directly to the 'DataGridTemplateColumn'.
I would do something like this:
<DataGridTemplateColumn Width="Auto"
CanUserReorder="False" CanUserResize="False"
Header="Action">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Margin="2 2 2 2"
ItemsSource="{Binding Path=DataContext.AvailableActions,
Mode=OneTime,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
SelectedValue="{Binding Path=Action, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Key"
DisplayMemberPath="Value"
IsEditable="False"
IsSynchronizedWithCurrentItem="False"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
A: Have you tried HorizontalAlignment and/or HorizontalContentAlignment to Stretch on the combobox?
| |
doc_23532603
|
I will post an anticipated result which works when put in a single file, and my decoupled codes.
Main.java
package gui;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Main {
//Basic Components
JFrame frame = new JFrame();
JMenuBar menubar = new JMenuBar();
JMenu menuPanels = new JMenu("Assignments");
JMenuItem assign_1 = new JMenuItem("Assignment 1");
JMenuItem assign_2 = new JMenuItem("Assignment 2");
JMenuItem assign_3 = new JMenuItem("Assignment 3");
JPanel panel = new JPanel();
JPanel pnlAss_1 = new JPanel();
JPanel pnlAss_2 = new JPanel();
JPanel pnlAss_3 = new JPanel();
CardLayout cardLayout = new CardLayout();
public Main()
{
panel.setLayout(cardLayout);
Assignment_1 pnlAss_1_class = new Assignment_1();
pnlAss_1 = pnlAss_1_class.CreatePanel(pnlAss_1);
panel.add(pnlAss_1, "pnlAss_1");
panel.add(pnlAss_2, "pnlAss_2");
cardLayout.show(panel, "pnlAss_1");
//Menubars and menupanels
menubar.add(menuPanels);
menuPanels.add(assign_1);
menuPanels.add(assign_2);
assign_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E)
{
cardLayout.show(panel, "pnlAss_1");
}
});
assign_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
cardLayout.show(panel, "pnlAss_2");
}
});
frame.setJMenuBar(menubar);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(800, 300);
frame.setVisible(true);
}
public static void main(String[] ar)
{
new Main();
}
}
Assignment_1.java
package gui;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Assignment_1 extends Main {
JLabel ID, Name, Contact, Address; JLabel Intro;
JTextField id, name, contact, address;
JButton close;
Assignment_1()
{
}
JPanel CreatePanel(JPanel panel)
{
panel.setSize(500, 300);
panel.setLayout(null);
Intro = new JLabel("First Assignment"); Intro.setBounds(10, 10, 300, 20);
panel.add(Intro);
//Labels definition & addition
ID = new JLabel("Student ID"); ID.setBounds(10, 30, 100, 20);
Name = new JLabel("Name"); Name.setBounds(110, 30, 100, 20);
Contact = new JLabel("Phone Number"); Contact.setBounds(210, 30, 100, 20);
Address = new JLabel("GitHub Address"); Address.setBounds(310, 30, 100, 20);
panel.add(ID); panel.add(Name); panel.add(Contact); panel.add(Address);
//TextFields definition & addition
id = new JTextField("2012203079"); id.setBounds(10, 50, 100, 20); id.setEditable(false);
name = new JTextField("정상원"); name.setBounds(110, 50, 100, 20); name.setEditable(false);
contact = new JTextField("010-8611-9898"); contact.setBounds(210, 50, 100, 20); contact.setEditable(false);
address = new JTextField("https://github.com/swj0418"); address.setBounds(310, 50, 160, 20); address.setEditable(false);
panel.add(id); panel.add(name); panel.add(contact); panel.add(address);
//Buttons definition& addition
close = new JButton("Close");
close.setBounds(400, 100, 70, 30);
close.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
panel.add(close);
return panel;
}
}
I think the problem here has to do something with JFrame.
I hava not posted Assignment_2 java since it is symmetrical with Assignment_1
Please help me out with this matter.
A: Do you really need Assignment1 class to be inherited from Main, you are not at all using any inheritance properties.
The problem is On object constructor of Main, you are trying to initiate Assignment1 object, which in turn class its super constructor, which is Main's constructor, which in turn again invokes constructor of Assignment1 to create a object, this loops go on and on recursively without any stoppage. Hence stackoverflow error.
Just try removing extends Main, if you really donot want inheritance as you are not using any from parent class
| |
doc_23532604
|
This is my simple playbook, the goal is to create an instance in AWS and add it to a security group.
I am quite confused as to what the problem is as I am getting 2 different errors from different yaml checkers:
1) Yamllint tells me: "(): did not find expected key while parsing a block mapping at line 2 column 3 "
2) Swagger tells me: "YAML Syntax Error. Bad indentation of a sequence entry at line 6, column 3: - name: Create a security group ^" (Points to the second "- name")
Any help would be great~
Cheers~
---
- name: Provision an EC2 Instance and assign an SG
hosts: local
connection: local
gather_facts: False
- name: Create a security group
local_action:
module: ec2_group
name: test_sg
region: us-west-2
rules:
- proto: tcp
type: ssh
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
type: all
cidr_ip: 0.0.0.0/0
- name: Create new instance
local_action: ec2
group= test_sg
instance_type= t1.micro
image= ami-9ff7e8af
wait= true
region= us-west-2
keypair= XXX-keypair
count= 1
register: ec2
A: In line 6 you're introducing a new item of a list (the dash symbol). But the yaml parser doesn't know what to do with the item. There are two approaches.
*
*Swagger considers it is part of the main list and it is at the same level as line 2. So it complains about bad indentation in line 6.
*Yamllint understand it's a sublist but it doesn't know what key to assign the sublist.
Most likely, yamllint is correct, and you've missed a key called tasks. Even with that bit fixed, you'll find there are other identations problems. Below I've pasted what I understand is the correct text (from a Yaml perspective)
---
- name: Provision an EC2 Instance and assign an SG
hosts: local
connection: local
gather_facts: False
tasks:
- name: Create a security group
local_action:
module: ec2_group
name: test_sg
region: us-west-2
rules:
- proto: tcp
type: ssh
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
type: all
cidr_ip: 0.0.0.0/0
- name: Create new instance
local_action: ec2
group= test_sg
instance_type= t1.micro
image= ami-9ff7e8af
wait= true
region= us-west-2
keypair= XXX-keypair
count= 1
register: ec2
| |
doc_23532605
|
A: On your machine installed VS Code tslint extension. it will help you to findout unused var and functions in your angular project.
| |
doc_23532606
|
<body>
<div w3-include-html="./src/nav.html"></div>
<script>w3.includeHTML();</script>
.
.
.
</body>
My question now: Is there anyway to make this work in the head tag? So that one doesn't have to repeat the same block of multiple links on every single page?
A: W3.js can include elements in the head as well as the body.
I created a quick test to be sure, and it works using:
<html>
<head>
<title>Include Test</title>
<link w3-include-html="head_include.html"/>
</head>
<body>
<h1>This is a test</h1>
<div w3-include-html="body_include.html"></div>
</body>
<script src="w3.js"></script>
<script>w3.includeHTML();</script>
</html>
Here it is using the W3.js include HTML functionality to add a stylesheet in to the link tag.
However:
*
*This won't work for "file://" if you are working on this locally, because it is using an AJAX call, and the CORS policy may block it.
*This is relying upon a Javascript executing on the page, altering the DOM, so this won't work if Javscript is disabled on the client, as it will be on things like web crawlers.
*Unlike the php includes this is visible to the client.
There are lots of templating alternatives, if that is your goal, and you may wish to look into Server-Side Includes if PHP is not available on your hosting solution, as this will allow you to perform inclusion of HTML with a properly configured server.
| |
doc_23532607
|
i have a script to do some editing in it, but the editing is done into output.txt and is renamed as file1and this changes the eol to windows/dos
the code is given
set uu=file1
set vv=file2
setlocal EnableDelayedExpansion
(for /F "delims=" %%a in (%uu%) do (
set "line=%%a"
if "!line:345=!" neq "!line!" (
if "!line:123=!" neq "!line!" (
if not defined flag (
findstr "123" %vv% | findstr "345"
set flag=true
)
) else (
echo !line!
)
) else (
echo !line!
)
)) >output.txt
del %uu%
rename output.txt file1
any way to change it back or retain unix eol via cmd without user input?
have tried directly inputing into the file1, gives a 0 kb file
tried type output.txt>file1 gave dos/win eol
echoing anything other than a blank line echo.>file1 changed the eol char
A: try this:
@echo off&setlocal enabledelayedexpansion
set "uu=file1"
set "vv=file2"
set LF=^
rem keep two empty lines between set LF and here
setlocal EnableDelayedExpansion
(for /F "delims=" %%a in (%uu%) do (
set "line=%%a"
if "!line:345=!" neq "!line!" (
if "!line:123=!" neq "!line!" (
if not defined flag (
findstr "123" %vv% | findstr "345"
set flag=true
)
) else (
<nul set/p"=!line!!LF!"
)
) else (
<nul set/p"=!line!!LF!"
)
)) >output.txt
type output.txt
A: Here's a solution:
@echo off
::Syntax: batchfile "file.txt" >"file2.txt"
:init
for /f %%c in ('copy /z "%~dpnx0" nul') do set cr=%%c
(set lf=^
)
del file.tmp 2>nul
for /f "delims=" %%i in ('findstr /n "^" "%~1"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:*:=!!lf!"
echo(!line!
endlocal
)>>file.tmp
setlocal enabledelayedexpansion
findstr /v "!cr!!lf!" file.tmp
endlocal
del file.tmp 2>nul
A: Using pure CMD I'd say unlikely.
GNU SED should be capable of this transformation though.
sed -b s/\r//g infile >outfile
| |
doc_23532608
|
Suppose I would like to write 2 functions, pack and unpack, which let you pack integers of smaller width into, say, a 64-bit integer. However, the location and width of the integers is given at runtime, so I can't use C bitfields.
Quickest is to explain with an example. For simplicity, I'll illustrate with 8-bit integers:
* *
bit # 8 7 6 5 4 3 2 1
myint 0 1 1 0 0 0 1 1
Suppose I want to "unpack" at location 5, an integer of width 2. These are the two bits marked with an asterisk. The result of that operation should be 0b01. Similarly, If I unpack at location 2, of width 6, I would get 0b100011.
I can write the unpack function easily with a bitshift-left followed by a bitshift right.
But I can't think of a clear way to write an equivalent "pack" function, which will do the opposite.
Say given an integer 0b11, packing it into myint (from above) at location 5 and width 2 would yield
* *
bit # 8 7 6 5 4 3 2 1
myint 0 1 1 1 0 0 1 1
Best I came up with involves a lot of concatinating bit-strings with OR, << and >>. Before I implement and test it, maybe somebody sees a clever quick solution?
A: Off the top of my head, untested.
int pack(int oldPackedInteger, int bitOffset, int bitCount, int value) {
int mask = (1 << bitCount) -1;
mask <<= bitOffset;
oldPackedInteger &= ~mask;
oldPackedInteger |= value << bitOffset;
return oldPackedInteger;
}
In your example:
int value = 0x63;
value = pack(value, 4, 2, 0x3);
To write the value "3" at an offset of 4 (with two bits available) when 0x63 is the current value.
| |
doc_23532609
|
I then drag the lower-right handle of the bounding box to increase the size of the selected objects and thus produce the following results:
My questions are as follows:
*
*How do I get the amount of scaling to be applied to each object?
*How do I get the amount of translation to be applied to each object?
I hope this question makes sense. And I hope you could help.
A: Hi I dont think there is any Translation , There is only Scaleing . One easy way to do that is preserve the Width and Height of your object like (TextBoxes above) and then when you want to get Scaleing values of that object
ScaleTransform scale = new ScaleTransform();
//_text is the scaled object
scale.ScaleX = text.ActualWidth - _width; //_width is width of the textbox at beginning.
scale.ScaleY = text.ActualHeight - _height; //_height is the height of textbox at the beginning.
This will give you the amount by which object is scaled corressponding to the Width and Height of TextBox at the beginning (i.e When window initialized) . I hyope this will give you an idea.
| |
doc_23532610
|
I'm able to login on my private registry:
$ docker login
-p <password>
-u <user>
docker-registry-default.si-origin-cluster.t-systems.es
Login Succeeded
With maven I'm getting:
[ERROR] Failed to execute goal com.google.cloud.tools:jib-maven-plugin:2.5.0:build (default-cli) on project connector: Build image failed, perhaps you should make sure your credentials for 'docker-registry-default.si-origin-cluster.t-systems.es/arxius/connector' are set up correctly. See https://github.com/GoogleContainerTools/jib/blob/master/docs/faq.md#what-should-i-do-when-the-registry-responds-with-unauthorized for help: Unauthorized for docker-registry-default.si-origin-cluster.t-systems.es/arxius/connector: 401 Unauthorized
My mvn command is:
$ mvn clean package
jib:build -Dimage=docker-registry-default.si-origin-cluster.t-systems.es/arxius/connector
-Djib.to.auth.username=<user>
-Djib.to.auth.password=<password>
Any ideas?
A: Please note that Jib is not complaining about authentication (login) but authorization. You may login into a registry and pull an image from it but may not push an image to it, depending on your permissions.
Check by pushing any image with "docker image push" if you are authorized to push an image to that registry.
| |
doc_23532611
|
Someone knows how can I do that ???
this is the beginning of my development:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(816, 603)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget1 = QtWidgets.QListWidget(MainWindow)
self.listWidget1.setGeometry(QtCore.QRect(370, 120, 151, 311))
self.listWidget1.setObjectName("listWidget1")
self.listWidget1.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
item = QtWidgets.QListWidgetItem()
self.listWidget1.addItem(item)
item = QtWidgets.QListWidgetItem()
self.listWidget1.addItem(item)
self.listWidget_2 = QtWidgets.QListWidget(MainWindow)
self.listWidget_2.setGeometry(QtCore.QRect(600, 120, 151, 311))
self.listWidget_2.setObjectName("listWidget_2")
self.listWidget_2.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
self.pushButton_3 = QtWidgets.QPushButton(MainWindow)
self.pushButton_3.setGeometry(QtCore.QRect(540, 220, 51, 21))
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(MainWindow)
self.pushButton_4.setGeometry(QtCore.QRect(540, 270, 51, 21))
self.pushButton_4.setObjectName("pushButton_4")
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
__sortingEnabled = self.listWidget1.isSortingEnabled()
self.listWidget1.setSortingEnabled(False)
item = self.listWidget1.item(0)
item.setText(_translate("MainWindow", "test1"))
item = self.listWidget1.item(1)
item.setText(_translate("MainWindow", "test2"))
self.listWidget1.setSortingEnabled(__sortingEnabled)
self.pushButton_3.setText(_translate("MainWindow", "-->"))
self.pushButton_4.setText(_translate("MainWindow", "<--"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
A: I just find the answer. I put the result here if one day someone has the same problem.
I created a new fonction when Iclicked on the button and used the 3 fonctions:
- selectedIndexes
- takeItem (to remove from the first QListWidget)
- addItem (to add the item in the second QListWidget)
def click_pushButton(self):
# sort rows in descending order in order to compensate shifting due to takeItem
rows = sorted([index.row() for index in self.listWidget1.selectedIndexes()],
reverse=True)
print('AAA')
for row in rows:
# assuming the other listWidget is called listWidget_2
self.listWidget_2.addItem(self.listWidget1.takeItem(row))
| |
doc_23532612
|
algorithm_a.py:
def compute_1(x):
# do some computation
return (x+1.)**2
def compute_2(x):
# do some other computation
# etc
algorithm_b.py:
def compute_1(x):
# do same computation in another way
return x*x + 2.0*x + 1.0
def compute_2(x):
# do some other computation in another way
# etc
Both modules have approximately 10 functions, but the number might grow in the future.
In a third module, I have functions defined that are not aware of the details of how the computation is performed, i.e. they only care about getting the correct answer. The interface to the user is provided by a class. All in all, the third module looks similar to:
simulation.py:
import XXX as algo #????
def do_computation_1(x):
v1 = algo.compute_1(x)
v2 = algo.compute_2(x)
# Do some computations using v1, v2
return result
def do_computation_2(x):
return algo.compute_2(x)
# etc etc
class Simulation(object):
def __init__(self, method):
# Do some magic here so that
# if method == "A":
# algo = algorithm_a
# if method == "B"
# algo = algorithm_b
def run(self, x):
do_computation_1(x)
do_computation_2(x)
How can I get the correct module loaded and applied in do_computation() to depend on the method parameter supplied to the class?
Note that the do_computation functions need to remain outside of the Simulation class.
CONCLUSION: The comment by @BrenBarn below summarises well the available options. Thanks all for the great help!
A: The better way to do this is to actually save (or pass) the function you want to use.. E.g.
import algorithm_a
import algorithm_b
class Simulation(object):
def __init__(self, method):
# Do some magic here so that
if method == "A":
self.compute_func = algorithm_a.compute
if method == "B"
self.compute_func = algorithm_b.compute
def run(self, x):
self.compute_func(x)
If you really must have your external def do_computation(x) function you can pass the algorithm you want to use as an argument
def do_computation(x, compute):
return compute(x)
class Simulation(object):
def __init__(self, method):
# Do some magic here so that
if method == "A":
self.compute_func = algorithm_a.compute
if method == "B"
self.compute_func = algorithm_b.compute
def run(self, x):
do_computation(x, self.compute_func)
A: With the way your code is structured, you can't have the import depend on a parameter passed to the class. Python files are executed top-to-bottom. Your import occurs before the class definition, so by the time the class is defined, the import has already occurred. (And you won't be passing method in until you instantiate the class, which will be even later.)
If it's okay to import both modules and you just want to use the specified one, you can do almost literally what you wrote in the comments:
import algorithm_a
import algorithm_b
class Simulation(object):
def __init__(self, method):
if method == "A":
self.algo = algorithm_a
if method == "B"
self.algo = algorithm_b
def do_computation(self, x):
return self.algo.compute(x)
def run(self, x):
self.do_computation(x)
(I have here made do_computation a method of the class. It doesn't make much sense to have it as a separate function if its behavior is determined by a parameter passed to the class.)
If the actual import of the modules may be slow, you could conditionally import one module or the ohter as shown in Reblochon's answer. However, to do this you must put the imports inside the class. If you are going to specify the algorithm via something like Simulation("A"), there's no way to determine which import to do at the time you do import simulation, because you haven't yet specified the algorithm at that time; you would have to wait until you actually call Simulation("A"). (If the import is slow, this will cause a slowdown at that point, which may not be desirable.)
Edit: if you really need to have do_computation be a global function because of Numba, you can work around it by setting a global variable. Change the __init__ to:
def __init__(self, method):
global algo
if method == "A":
algo = algorithm_a
if method == "B"
algo = algorithm_b
And make a global do_computation function like this:
def do_computation(x):
return algo.compute(x)
This will be more confusing because every time you create a new Simulation it will change the global behavior, even for previously-created simulations. But if you aren't creating multiple simulations with different algorithms at the same time, it should be okay.
| |
doc_23532613
|
when trying to run elm-reactor, I get this error:
*
*Uncaught TypeError: runElmProgram is not a function
but when I try to run: elm make src/Exercises.elm --warn --output elm.js
then I get no warnings but this errors:
*
*Uncaught ReferenceError: Elm is not defined
*Uncaught TypeError: Cannot read property 'Native' of undefined
this is my elm-package:
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [".", "src"],
"exposed-modules": [],
"native-modules": true,
"dependencies": {
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0",
"elm-lang/dom": "1.1.1 <= v < 2.0.0",
"NoRedInk/elm-simple-fuzzy": "1.0.2 <= v < 2.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
}
A: you were lucky this compiled as this is an old library. The Elm code itself looks seems to use syntax that has not changed since it was written, but the native code on which it relies has changed completely and that's what's causing your error.
You could try to use https://github.com/elm-lang/persistent-cache instead, but this is a package that seems to be deliberately left as is, and you are expected to use ports instead. Frustrating I know....
| |
doc_23532614
|
Straight question: Do I need to upload more than the FireBreath generated .dll file (needing proper .js, .html, and .json are obvious) for a FireBreath plugin within a Chrome extension?
Big picture:
FireBreath generates a .dll and I believe putting loading this .dll file into the Chrome extension folder I upload using chrome://extensions/ unpacked is sufficient. In other words, I think I do not need to upload additional C++ code. Calling plugin.openUserIdFromFile() generates my error.
Success: I loaded the desktop username from a file to a Chrome extension using a NPAPI FireBreath plugin. It works on the Windows desktop on which the plugin was developed.
Failure: Error calling method on NPObject. Error is received on all Windows environments: XP, 7, or 8 outside the development environment.
Known: A buddy ran http://www.dependencywalker.com/ software on it and found that IEShims.dll was a missing dependency in his environment, but I included it in the uploaded folder to no avail.
JavaScript Chrome extension makes call to FireBreath plugin dll:
$(document).ready(function () {
setInterval(getAllChromeTabs, 10000);
var plugin = document.getElementById("pluginId");
while (user.length < 1) {
user = plugin.openUserIdFromFile();
}
console.log(user);
});
C++ FireBreath plugin function called from Chrome Extension:
std::string LabStatsPluginAPI::openUserIdFromFile()
{
std::string aTempFileName = "aTempFileName";
DWORD nBufferLength = MAX_PATH;
LPTSTR lpBuffer = (new TCHAR[nBufferLength]);
DWORD tempPath = GetTempPath(nBufferLength, lpBuffer);
char* localTempPathArray = new char[nBufferLength];
for (int i = 0; i < nBufferLength; i++) {
localTempPathArray[i] = (char)lpBuffer[i];
}
std::string localTempPath(localTempPathArray);
localTempPath = localTempPath + aTempFileName;
std::ifstream streamFromFile;
std::ifstream::pos_type fileSize;
streamFromFile.open( localTempPath, std::ios::in|std::ios::binary|std::ios::ate );
char* userNameString;
int userNamesize = streamFromFile.tellg();
streamFromFile.seekg(0, std::ios::beg);
userNameString = new char[userNamesize];
streamFromFile.read(userNameString, userNamesize);
delete[] lpBuffer;
delete[] localTempPathArray;
std::string userNameSafeString(userNameString);
delete[] userNameString;
return userNameSafeString;
}
A: The following modification to the C++ (the if statement inserted) fixes the function.
char* userNameString;
int userNamesize = streamFromFile.tellg();
if (userNamesize < 1) {
return ""; // no file found
}
streamFromFile.seekg(0, std::ios::beg);
userNameString = new char[userNamesize];
streamFromFile.read(userNameString, userNamesize);
| |
doc_23532615
|
Using // ignore: argument_type_not_assignable does supress the error message. Although I use this quite often, so it is annoying to have this comment spread accross the code base.
In the Settings > Inspections couldn't find anything neither under Dart nor General.
Is there a way to supress specific inspections?
A: You can configure that using the analysis_options.yaml file
https://www.dartlang.org/guides/language/analysis-options
analyzer:
errors:
argument_type_not_assignable: ignore
See also Suppress hint about use of protected member
| |
doc_23532616
|
from scipy.interpolate import UnivariateSpline
s = base_data1.groupby(['MDSE_ITEM_I','CO_LOC_I'])\
.transform(lambda x: UnivariateSpline(np.arange(x.count()), x['PCT_TILL_DATE'].value, s=x.count()))
Here I am passing np.arange(x.count()) as x monotonically increasing array and passing values of Pandas series x['PCT_TILL_DATE'].value as y with good enough smoothing factor s as x.count(). However I am getting error:
KeyError: ('PCT_TILL_DATE', u'occurred at index GREG_D')
What I am missing here?
A: You dont need to select the column you want, because transform() already turns it into a Series, which you cant index like that.
Also, UnitvariateSpline returns a 'fitted' object which you need to call again with your desired x-output to get some actual values.
import pandas as pd
from scipy.interpolate import UnivariateSpline
n = 16
df = pd.DataFrame({'data1': np.cos(np.linspace(0,np.pi*4, n)),
'data2': np.random.randn(n),
'class_a': np.array([0]*(n//2)+[1]*(n//2)),
'class_b': np.array([1]*n)})
def grpfunc(grp):
n = len(grp)
x = np.arange(n)
spl = UnivariateSpline(x, grp.values, s=n)
return spl(x)
df.groupby(['class_a', 'class_b']).transform(grpfunc)
| |
doc_23532617
|
But I typed a different website address in address bar and clicked. This site has fully
GWT code.
But I like to back to the previous page of www.google.com.
So I clicked back button of browser.but how can I get event of back button from current
GWT code. Can I set any backbutton event handler in GWT of current page?
One which notifies an alert to me that back button was pressed.
Is there any solution from GWT?
A: +1 to Igor and Alex. Here's some code you can use, if you want to use the ClosingHandler:
Window.addWindowClosingHandler(new Window.ClosingHandler() {
@Override
public void onWindowClosing(final ClosingEvent event) {
event.setMessage("Don't you think my site is awesome?");
}
});
Some info from the Javadoc of ClosingHandler.onWindowClosing():
/* Fired just before the browser window closes or navigates to a different
* site. No user-interface may be displayed during shutdown. */
A: There's Window.ClosingEvent:
Fired just before the browser window
closes or navigates to a different
site.
The other option is History.addValueChangeHandler, which listens for changes in the browser's history stack (see the docs for more info).
A: You can implement the HistoryListener interface: your class's method onHistoryChanged will be called (with a String token) on every click to the back and forward buttons. You can then interact with the History class, which has e.g. a back() static method to "go back". However, I'm not entirely sure if it goes back all the way to before GWT started (but it's sure worth trying;-).
A: try this it will work
Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(final NativePreviewEvent event) {
if (event.getTypeInt() == Event.ONKEYDOWN) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_BACKSPACE) {
Element element = Element.as(event.getNativeEvent().getEventTarget());
String tagName = element.getTagName();
System.out.println(tagName);
// Add checks for other input controls
if (!tagName.equalsIgnoreCase("INPUT")
&& !tagName.equalsIgnoreCase("TEXTAREA")) {
boolean result = Window.confirm("Are you sure?");
if (!result) {
event.cancel();
}
}
}
}
}
});
A: you also can use this native code
public native void call()/*-{
$wnd.onkeydown = GetChar;
function GetChar (event)
{
var key = event.keyCode;
var bb = event.target.nodeName;
if(key==8 && bb=="BODY")//checking keyCode of key for backspace
{
var x= window.confirm("Are you sureyou want to leave the page");
if (x==true)
{
window.history.back();
}
else if(x==false)
{
return false;
}
}
}
}-*/;
| |
doc_23532618
|
used to display a slider with featured articles--similar to the slider on the home page. One day, it stops and I got this error on my console:
basic-jquery-slider.min.js:1 Uncaught TypeError: Cannot read property 'eq' of undefinedA @ basic-jquery-slider.min.js:1(anonymous function) @ basic-jquery-slider.min.js:1
My hunch is the basis-jquery-slider.min.js, which is hosted on : http://housingtrustfundproject.org/wp-includes/js/wp-embed.min.js?ver=4.5.3
Any hints on where and how to troubleshoot this will be great.
| |
doc_23532619
|
I'm using tcpdump to watch packets. I loop over each line in live and aggregate data during 60s.
Then, after 60s, I update the database. I need to constantly have data every 60s, even if there is no packet (by inserting null data).
Problem
If there is no internet or packet, the loop doesn't continue and I have to wait x seconds for the next output. The problem is that the interval can be > 60s.
Current code
ts = int(time.time())
p = subprocess.Popen(
(
"tcpdump",
"-neqli",
"eth0"
),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
interval = 60
sessions = {}
for row in iter(p.stdout.readline, ""):
# Do some work, aggregate data
splited_row = row.split(" ")
log_ts = splited_row[0]
sessions[log_ts] = "Anything"
if int(time.time()) - interval > ts:
# Insert in database
insert_in_database(sessions)
ts = int(time.time())
Solution
Thanks to @Gerd, I had to use thread and queue.
In the producer, I use the code above without the time section. First I get the current queue data to update it at every new input. Then instead of insert, I put my aggregated data in it.
Then, my consumer loop every 60s, get the queue data and insert it.
A: I suggest to use a producer-consumer approach with two threads: Here is a complete example (with random integer values rather than strings).
In your case, the producer thread would read the tcpdump output from the subprocess and put the results in a queue, the consumer thread would look at the queue every 60 seconds and either find some data or that the queue is empty. So you consumer thread main loop would look something like this:
while True:
if not q.empty():
item = q.get()
print('Getting ' + str(item) + ' : ' + str(q.qsize()) + ' items in queue')
# insert data into database
else:
print('No data')
# insert null data into database
time.sleep(60.0)
| |
doc_23532620
|
Also it is working on InteliJ IDEA 2016 ultimate, cause my friend is using it, but he could not help me with my problem.
I have installed InteliJ IDEA 2016.1.2 Ultimtate and opened my project.
Then i installed Lombok
And restarted IDEA.
The problem is that IDEA does not resolve many imports that STS does.
I've tried for example:
1)
*
*Right click on the code editor
*Hover on Maven and expand
*Click on Reimport
2)
*
*File | Invalidate Caches
but these options did not help me.
I have occured this problem recently(this week) on 2 PC's.
A: Intellij and Lombok are not actually good friends. As far as I know, the intellij does not want to support lombok annotations but then, I saw a plugin is developed to meet this requirement. I think, this thread will help you.
| |
doc_23532621
|
For example I've run through some of them such as: SmartBear, National Instrument and IBM. Most of these guys are MS Windows based or commercial Linux distros which remove them from our list since we are all Debian based.
Any recommendation or guideline would be much appreciated.
Ps. We don't have any budget limit!
A: You're going to have a hard time getting tooling for non-technical testers to build test cases if you limit yourselves to Debian OS for developing and running the tests on. There's no reason you couldn't have a few Windows system to manage your test suites from -- those would run against your web site just fine, regardless of what stack it's hosted on. That would open you up to the tools you mentioned (and Telerik's Test Studio, the tool I help promote).
Those Windows systems could easily be run via whatever virtualization host you prefer, so you wouldn't even need physical systems to deal with that. You could easily share the same source control repository as your devs, too, since nearly every decent SCM has Windows clients.
If you're unwilling to consider having a few Windows boxes around for your testing, then you'll need to have a look at getting all your testers proficient in APIs and frameworks like WebDriver and Robot Framework. The Pages gem from Jeff Morgan (@chzy) in Ruby would be another option, as would Adam Goucher's Saunter (in Python).
| |
doc_23532622
|
if ((a.indexOf(select1) > -1 && b.indexOf(select2) > -1) || (b.indexOf(select1) > -1 && a.indexOf(select2) > -1) || (a.indexOf(select1) > -1 && a.indexOf(select2) > -1))
{
//do something;
}
Right now I will have 14 else if's with more of this unless there is an easier way. I just need it to find ab or ba, cd or dc, whatever is chosen. Thanks in advance.
A: Since both selects have numbers only we can convert them to integers and then compare, which is easier than string comparison.
var a = parseInt(document.getElementById('marked').value);
var b = parseInt(document.getElementById('marked1').value);
if(!isNaN(a) && !isNaN(b)) {
if(a<b) {
alert("marked select is greater than marked1!");
} else if(b>a) {
alert("marked1 select is greater than marked!");
} else {
alert("marked & marked1 select have same values selected!");
}
} else {
alert("select options in both selects!");
}
| |
doc_23532623
|
Everything works fine except dimming view. When I'm starting search dimming view's width is equal to screen width:
When I start entering search string or clear textfield my searchResultsTableView resizes properly and everything works as it should:
I tried to change searchResultsTableView frame inside -searchDisplayControllerWillBeginSearch: method using this line
controller.searchResultsTableView.frame = myFrame;
but it doesn't work as well. Any suggestions besides implementing my own search display controller?
A: I also needed to change the frame of the dimming view but for a different reason. In my case I created a UISearchDisplayController and UISearchBar programmatically in a regular UIViewController not a UITableViewController. I was also using MFSideMenu which added to the complexity of the problem. What ended up happening was the dimming view was in the correct position initially but the next time the search was cleared the dimming view shifted leftwards and upwards by exactly half of it's size. Given the UISearchDisplayController you can find the dimming view like so.
for(UIView * v in controller.searchContentsController.view.subviews)
{
if([v isMemberOfClass:[UIControl class]])
{
v.frame = newFrame; //This frame should account for the UISearchBar
}
}
To handle for the initial incorrect frame you should change it in this delegate method:
- (void) searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView;
To handle for an incorrect frame on any subsequent clears you should change it in this delegate method:
- (void) searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView;
Note: this solution runs through the subviews of the searchContentsController which is one of the reasons I used isMemberOfClass instead of isKindOfClass (UIButton is a subclass of UIControl). Further discrimination would be required if you added a UIControl instance into your view (you could use tags to help determine which ones are yours).
| |
doc_23532624
|
A: ReferLink
document.addEventListener('copy', function(e) {
e.clipboardData.setData('text/plain', 'Please do not copy text');
e.clipboardData.setData('text/html', '<b>Please do not copy text</b>');
e.preventDefault();
});
| |
doc_23532625
|
I have problem to the display data from this variable with map method. I get the error: Cannot read property 'map' of undefined. Can spot somebody where the problem is?
ShopScreen.js:
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { fetchShops } from '../services/fetchShops';
const ShopsScreen = props => {
const [data, setShops] = useState({});
useEffect(() => {
fetchShops()
.then(response => response.json())
.then(data => setShops(data));
}, []);
return(
<View>
<Text>The Shops Screen!</Text>
{data.result.map(shop => {return (<Text>{shop.address}</Text>)})}
</View>
);
};
export default ShopsScreen;
My service for fetching data is fetchShops.js
export const fetchShops = () => {
const URL = `https://vilvumbiyl.execute-api.eu-west-1.amazonaws.com/Dev/store/MEBD/list`;
return fetch(URL)
}
A: You can try:
const [data, setShops] = useState({result : {}});
or test data.result before use map on it.
ShopsScreen returns your view(JSX) before you get answer from your rest API. The result is null. You get the exception.
A: useEffect without any params is equal to componentDidMount and for this reason, is called after the render.
So, the first time your jsx code is called, data.result.map is undefined and only after the re-render, do to the response of fetchShops(), it has a value.
You simply need to check the value like this:
data.result && data.result.map()
| |
doc_23532626
|
Also, when I am trying to copy a file from the git.workspace to some other directory, Permission denied error is coming.
The user under which the github actions is running has full admin permission. Still the error exists.
Thanks.
| |
doc_23532627
|
-Works Good if i only install the beta version instead of updating playstore version
I use it to retrive the image in DCIM folder, i gets the image path,size,name but image is not loaded
| |
doc_23532628
|
A: Here is the complete solution of your problem.
public class EntertainmentActivity extends Activity {
private static final String MEDIA_PATH = new String( "/mnt/sdcard/VideoFolder");
static String[] fileList = null;
GridView gridView;
static String FILE_PATH = "/mnt/sdcard/VideoFolder/";
String MiME_TYPE = "video/mp4";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
updateSongList();
gridView = (GridView) findViewById(R.id.gridView1);
File dir = new File(MEDIA_PATH);
if (dir.exists()) {
} else {
dir.mkdirs();
}
if (fileList != null) {
gridView.setAdapter(new ImageAdapter(this, fileList));
}
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String videoFilePath = FILE_PATH + fileList[position];
System.out.println("******************************videoFilePath****************" + videoFilePath);
System.out.println("******************************MiME_TYPE****************"+ MiME_TYPE);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File newFile = new File(videoFilePath);
intent.setDataAndType(Uri.fromFile(newFile), MiME_TYPE);
startActivity(intent);
}
});
}
public void updateSongList() {
File videoFiles = new File(MEDIA_PATH);
Log.d("*********Value of videoFiles******", videoFiles.toString());
if (videoFiles.isDirectory()) {
fileList = videoFiles.list();
}
if (fileList == null) {
System.out.println("File doesnot exit");
Toast.makeText(this, "There is no file please add files to "+MEDIA_PATH, Toast.LENGTH_SHORT).show();
} else {
System.out.println("fileList****************" + fileList);
for (int i = 0; i < fileList.length; i++) {
Log.e("Video:" + i + " File name", fileList[i]);
}
}
}
GridView Adapter
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] VideoValues;
public ImageAdapter(Context context, String[] VideoValues) {
this.context = context;
this.VideoValues = VideoValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("***********IngetView************");
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from gridlayout.xml
gridView = inflater.inflate(R.layout.grid_row, null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(EntertainmentActivity.fileList[position]);
System.out.println("value of fileList[position]" + EntertainmentActivity.fileList[0]);
// set image
ImageView imageThumbnail = (ImageView) gridView
.findViewById(R.id.grid_item_image);
Bitmap bmThumbnail;
System.out
.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>> file path>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
+ EntertainmentActivity.fileList[position]);
bmThumbnail = ThumbnailUtils
.createVideoThumbnail(EntertainmentActivity.FILE_PATH + EntertainmentActivity.fileList[position],
MediaStore.Video.Thumbnails.MINI_KIND);
if (bmThumbnail != null) {
System.out
.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>> THUMB NAIL>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
imageThumbnail.setImageBitmap(bmThumbnail);
} else {
System.out
.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>NO THUMB NAIL>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}
} else {
gridView = (View) convertView;
}
return gridView;
}
public int getCount() {
// return 0;
return VideoValues.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
}
main.xml Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff99cc00" >
<GridView
android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="200dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:padding="10dp"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
</RelativeLayout>
grid_row.xml Row Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:orientation="vertical" >
<ImageView
android:id="@+id/grid_item_image"
android:layout_width="320dp"
android:layout_height="300dp" />
<TextView
android:id="@+id/grid_item_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#92d050"
android:ellipsize="marquee"
android:gravity="center"
android:padding="3dp"
android:singleLine="true"
android:text="test string"
android:textColor="@android:color/white" />
</LinearLayout>
AndroidManifest.xml
don't forget to put user-permission in AndroidManifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
| |
doc_23532629
|
downloadTaskWithResumeData
because it's not working when the app crashed.
the answer How do I download large file with streaming in AFNetworking 3 does not resove the problem.
The afnetworking 2.0 can set the outputstream, but i don't know how to set the outputstream in 3.0.
so i really need your help.
| |
doc_23532630
|
<extra><technique><double_sided>1</double_sided></technique></extra>
did not render.
It appears that the polygons are being culled. If I force _gl.disable( _gl.CULL_FACE ); my model shows up as expected. But why would it cull all of my faces all of the time? (even if I had the winding order backward, I should see the other side of the object, right?)
A: It turns out that my parameter to setFaceCulling wasn't right. I was passing false instead of a culling mode.
With the r51 implementation, false happened to disable all culling.
With the r57 implementation, it dumped me into the new default behavior ... which is to enable culling and set it to cull both front and back faces.
So, I was able to fix it ... but I'm not sure I would have made that the default behavior. ;o)
| |
doc_23532631
|
I am using this function to convert the unicode data to hex. Str variable contains the Unicode data
convertToHex: function(str) {
var hex = '';
var i = 0;
while (str.length > i) {
hex += '' + str.charCodeAt(i).toString(16);
i++;
}
console.log(hex);
return hex;
},
This is first line of the result i am getting in hex variable
504b3414060800021062ee9d685e10090400130825b436f6e74656e745f54797065735d2e786d6c20a24228a002
Now when i am uploading same data to SAP Netweaver gateway, it converts the unicode data to hex as follows (First line) :
504B03041400060008000000210062EE9D685E01000090040000130008025B436F6E74656E745F54797065735D2E786D6C20A2040228A00002
This is the decoded unicode:
PK!bîh^[Content_Types].xml ¢(
For my application to work i need both hex codes to be same but i am not able to generate the correct hex code in Javascript whereas in SAP i am getting the correct hex values.
| |
doc_23532632
|
does not work, only if I load it with command:heroku local on localhost:8080 works.
Thanks:)
A: instead of var socket = io.connect('https://towd-server.herokuapp.com:8080')
try this one
var http = require('http');
var io = require('socket.io').(http);
var port = process.env.PORT || 8080;
| |
doc_23532633
|
Here is an example of the dataset:
1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 3
1 1 1 1 1 1 1 1 1 1 1 1 2
1 1 1 1 1 1 1 1 1 1 1 3 1
1 1 1 1 1 1 1 1 1 1 1 3 3
1 1 1 1 1 1 1 1 1 1 1 3 2
As you can see rows 1-3 and 4-6 are identical except the last column. So, given threshold of 1 I would like to outcome to be two rows (one row from 1-3 and one row from 4-6). For threshold 2 we can see how all rows are identical for all columns except the last two, therefore only one row should be the outcome. To be honest it doesnt really matter which row to keep (first, last, random).
I've tried the following code from another thread but it only returns one row: (Removing *NEARLY* Duplicate Observations - Python)
from sklearn.preprocessing import OrdinalEncoder
import pandas as pd
import numpy as np
#load dataframe
data = pd.read_csv(r'testfile.csv')
df = pd.DataFrame(data, columns=['File_1', 'File_2', 'File_3', 'File_4', 'File_5', 'File_6', 'File_7', 'File_8', 'File_9', 'File_10', 'File_11', 'File_12', 'File_13'])
def dedupe_partially_vectorized(df, threshold=1):
"""
- Iterate through each row starting from the last; examine all previous rows for duplicates.
- If found, it is appended to a list of duplicate indices.
"""
# convert field data to integers
enc = OrdinalEncoder()
X = enc.fit_transform(df.to_numpy())
"""
- loop through each row, starting from last
- for each `row`, calculate hamming distance to all previous rows
- if any such distance is `threshold` or less, mark `idx` as duplicate
- loop ends at 2nd row (1st is by definition not a duplicate)
"""
dupe_idx = []
for j in range(len(X) - 1):
idx = len(X) - j - 1
row = X[idx]
prev_rows = X[0:idx]
dists = np.sum(row != prev_rows, axis=1)
if min(dists) <= threshold:
dupe_idx.append(idx)
dupe_idx = sorted(dupe_idx)
df_dupes = df.iloc[dupe_idx]
df_deduped = df.drop(dupe_idx)
return (df_deduped, df_dupes)
#send output to csv
(df_deduped, df_dupes) = dedupe_partially_vectorized(df)
print(df_deduped)
When running the code on the above dataset it returns:
File_1 File_2 File_3 File_4 ... File_10 File_11 File_12 File_13
0 1 1 1 1 ... 1 1 1 1
[1 rows x 13 columns]
Process finished with exit code 0
I'd be really helpful if someone can help me solve this!
Edit:
After trying the new code it doesn't remove all nearly observations: Example of a dataset which should only keep one row out of seven (right now keeps 5/7):
1 1 3 3 3 2 1 2 1 1 2 2 1
1 3 3 3 3 2 1 2 1 1 2 2 1
1 1 3 3 3 2 1 2 1 1 2 2 2
1 1 3 3 3 2 3 2 1 1 2 2 1
1 1 3 3 3 2 1 2 1 1 2 1 1
1 1 3 3 3 2 1 2 1 1 2 3 1
1 1 3 3 3 2 1 2 2 1 2 2 1
A: One way unsg itertools.combinations with drop_duplicates:
from itertools import combinations
n = 1
colsets = [c for c in combinations(df.columns, len(df.columns) - n)]
min((df.drop_duplicates(subset=c) for c in colsets), key=len)
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12
0 1 1 1 1 1 1 1 1 1 1 1 1 1
3 1 1 1 1 1 1 1 1 1 1 1 3 1
| |
doc_23532634
|
I'm not sure where to start.
Sample file1 text:
alert $home_net any > $External_net any (msg: example; content: something; sid: 12345; rev:1)
#alert $home_net any > $External_net any (msg: example; content: something; sid: 67895; rev:1)
alert $home_net any > $External_net any (msg: example; content: something; sid: 18975; rev:1)
Sample file2 text:
alert $home_net any > $External_net any (msg: example; content: something; sid: 12345; rev:1)
<insert #>alert $home_net any > $External_net any (msg: example; content: something; sid: 67895; rev:1)
alert $home_net any > $External_net any (msg: example; content: something; sid: 18975; rev:1)
Edit: Provided solution works with initial sample data I provided above however, it doesn't work with actual signatures. So I'm providing actual signatures below. Also rules may or may not have white-space between each line.
Sample file1 text:
#alert tcp $EXTERNAL_NET any -> $HOME_NET 2200 (msg:"ET EXPLOIT CA BrightStor ARCserve Mobile Backup LGSERVER.EXE Heap Corruption"; flow:established,to_server; content:"|4e 3d 2c 1b|"; depth:4; isdataat:2891,relative; reference:cve,2007-0449; reference:url,doc.emergingthreats.net/bin/view/Main/2003369; classtype:attempted-admin; sid:2003369; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
alert udp $EXTERNAL_NET any -> $HOME_NET 111 (msg:"ET EXPLOIT Computer Associates Brightstor ARCServer Backup RPC Server (Catirpc.dll) DoS"; content:"|00 00 00 00|"; offset:4; depth:4; content:"|00 00 00 03|"; distance:8; within:4; content:"|00 00 00 08|"; distance:0; within:4; content:"|00 00 00 00|"; distance:0; within:4; content:"|00 00 00 00|"; distance:4; within:4; content:"|00 00 00 00 00 00 00 00|"; distance:8; within:32; reference:url,www.milw0rm.com/exploits/3248; reference:url,doc.emergingthreats.net/bin/view/Main/2003370; classtype:attempted-dos; sid:2003370; rev:3; metadata:created_at 2010_07_30, updated_at 2020_08_20;)
#alert tcp $EXTERNAL_NET any -> $HOME_NET 1900 (msg:"ET EXPLOIT Computer Associates Mobile Backup Service LGSERVER.EXE Stack Overflow"; flow:established,to_server; content:"0000033000"; depth:10; isdataat:1000,relative; reference:url,www.milw0rm.com/exploits/3244; reference:url,doc.emergingthreats.net/bin/view/Main/2003378; classtype:attempted-admin; sid:2003378; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
Sample file2 text:
#alert tcp $EXTERNAL_NET any -> $HOME_NET 2200 (msg:"ET EXPLOIT CA BrightStor ARCserve Mobile Backup LGSERVER.EXE Heap Corruption"; flow:established,to_server; content:"|4e 3d 2c 1b|"; depth:4; isdataat:2891,relative; reference:cve,2007-0449; reference:url,doc.emergingthreats.net/bin/view/Main/2003369; classtype:attempted-admin; sid:2003369; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
alert udp $EXTERNAL_NET any -> $HOME_NET 111 (msg:"ET EXPLOIT Computer Associates Brightstor ARCServer Backup RPC Server (Catirpc.dll) DoS"; content:"|00 00 00 00|"; offset:4; depth:4; content:"|00 00 00 03|"; distance:8; within:4; content:"|00 00 00 08|"; distance:0; within:4; content:"|00 00 00 00|"; distance:0; within:4; content:"|00 00 00 00|"; distance:4; within:4; content:"|00 00 00 00 00 00 00 00|"; distance:8; within:32; reference:url,www.milw0rm.com/exploits/3248; reference:url,doc.emergingthreats.net/bin/view/Main/2003370; classtype:attempted-dos; sid:2003370; rev:3; metadata:created_at 2010_07_30, updated_at 2020_08_20;)
< insert #>alert tcp $EXTERNAL_NET any -> $HOME_NET 1900 (msg:"ET EXPLOIT Computer Associates Mobile Backup Service LGSERVER.EXE Stack Overflow"; flow:established,to_server; content:"0000033000"; depth:10; isdataat:1000,relative; reference:url,www.milw0rm.com/exploits/3244; reference:url,doc.emergingthreats.net/bin/view/Main/2003378; classtype:attempted-admin; sid:2003378; rev:3; metadata:created_at 2010_07_30, updated_at 2010_07_30;)
A: First, examine the first file and find out what sids are commented out:
sed -En '/^#/ s/.*sid:([0-9]+).*/\1/p' file1
The above command prints out the sid of the lines that begin with a #, one sid per line. Now let's aggregate those lines and build a list of sids separated with |:
sed -En '/^#/ s/.*sid:([0-9]+).*/\1/p' file1 | paste -sd '|'
Fine, now we have sid1|sid2|...|sidN. As it is written, this can be used as a regex to identify the lines in file2 that need to be commented out. Let's put this regex in a variable:
sid_regex=$(sed -En '/^#/ s/.*sid:([0-9]+).*/\1/p' file1 | paste -sd '|')
Now, we can modify file2 so that every line 1) with a sid that matches the regex and 2) that doesn't already begin with # is commented out:
sed -E "/sid:($sid_regex);/ s/^[^#]/#&/" file2 > file2.new
Voilà! To sum it up:
$ sid_regex=$(sed -En '/^#/ s/.*sid:([0-9]+).*/\1/p' file1 | paste -sd '|')
$ sed -E "/sid:($sid_regex);/ s/^[^#]/#&/" file2 > file2.new
[update] You have so many commented lines that the resulting huge regex makes the command too big ("Argument list too long"). Let us try another approach: instead of building a one-line sed program with a gigantic regex, we will build a multi-line sed program, with one line for each sid.
This first sed command generates the second sed program:
sed -En '/^#/ s|.*(sid:[0-9]+;).*|/\1/ s/^[^#]/#\&/|p' file1
The result should be something like:
/sid:111;/ s/^[^#]/#&/
/sid:222;/ s/^[^#]/#&/
...
/sid:123456;/ s/^[^#]/#&/
Now we feed a second sed with that program in order to process file2:
sed -En '/^#/ s|.*(sid:[0-9]+;).*|/\1/ s/^[^#]/#\&/|p' file1 | sed -f - file2 > file2.new
| |
doc_23532635
|
Can someone explain what those values represent? How do they describe the wave form? I suppose because they are positive and negative that the axis is in the center of the wave form.
How would I convert the values to decibel such that 0 dB is loudest?
A: Although the sample type is a 32-bit int, the values you received will generally fit in a 16-bit int (ie, 32767..-32767). 32767 (or floating point 1.0) corresponds to 0dB.
After converting the sample to floating point value, the power in decibels looks something like this:
double sampleValue = (double)intSampleValue / 32767.0;
double db = 20.0 * log10(value);
I've done the above calculations as double precision to avoid overflow.
| |
doc_23532636
|
In the related Railscasts episode, he uses a helper method which uses a lot of content_tag's... but my partial is quite complex and I don't want to do it that way (I want it in embedded ruby).
The problem is that when a partial is being rendered recursively, the local variables are not being passed.
Initial rendering of comments (where the recursion starts):
def index
@comments = @commentable.comments.includes(:user).arrange(order: :created_at)
render partial: 'shared/comments', locals: { comments: @comments }
end
That creates a hash of nested objects. From there, the partial should take over:
<% comments.each do |comment, child_comments| %>
<div class="comment" data-id="<%= comment.id %>">
<%= image_tag comment.user.avatar_url, class: 'avatar', size: '40x40' %>
<div class="content">
<%= simple_format h(comment.body) %>
<!-- binding.pry -->
<%= render('shared/comments', locals: { comments: child_comments }) if child_comments %>
</div>
</div>
<% end %>
However, when I run this I get undefined local variable or method 'comments' referencing line 1 of the partial above. This only happens on the recursive 2nd loop though (and I assume any beyond that), the initial loop works fine.
I know the variables are correct because immediately before the render call you will see I put <!-- binding.pry -->. If I use pry there I can see that comments do indeed have the proper values.
I'm not sure what to do here... thanks!
A: Either do:
<%= render( partial: 'shared/comments', locals: { comments: child_comments }) if child_comments %>
Or:
<%= render('shared/comments', comments: child_comments) if child_comments %>
| |
doc_23532637
|
I am trying to define a scale variable (s), where the image scales dynamically according to its value. I don't think the expression s*100 is evaluating as there is no difference in size. What is wrong.
<html>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var s = 10000;
ctx.fillStyle = "rgba(0, 0, 200, 0.1)";
ctx.fillRect (0, 0, s*100, s*100);
}
}
</script>
</html>
A: The reason you don't see any change is because you are trying to render a gigantic rectangle onto a 150x150 canvas, so the part outside the canvas is ignored. Make your canvas really big and you'll see it working. Here's a working example, it keeps rendering the same square by increasing the scale each time. http://jsfiddle.net/3ZAex/2/
A: Figured it out.. it was because my canvas was too small.. width="150" height="150"
| |
doc_23532638
|
select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1
from table1
join table2 on table1.col3 = table2.col3
group by table1.col1
select
table1.col1
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table3 on table1.col3 = table3.col3
group by table1.col1
How can I merge these querys into a single select? the problem is I want all the 'C1' rows only when is joined with table2, the same way with 'C2'.
This is an example of the joins, as you can see the col3 in both joins are equivalent (in terms of type of column) but not in value
select table1.col1, table1.col2, table2.col3 from table1 join table2 on table1.col3 = table2.col3
table1.col1 | table1.col2 | table2.col3
'COD1' 'C1' 543
'COD1' 'C2' 329
'COD2' 'C2' 123
'COD1' 'C1' 943
select table1.col1, table1.col2, table3.col3 from table1 join table3 on table1.col3 = table3.col3
table1.col1 | table1.col2 | table3.col3
'COD2' 'C2' 632
'COD1' 'C1' 895
'COD1' 'C2' 248
'COD2' 'C1' 458
A: If you want all C1 and C2 in single column then you can go for UNION or UNION ALL(duplicates are also included):
select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1
from table1
join table2 on table1.col3 = table2.col3
union
select
table1.col1
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table3 on table1.col3 = table3.col3
And if you want C1 and C2 in separate columns then you can simple add case statement for column C2 in your first query:
select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1,
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table2 on table1.col3 = table2.col3
join table3 on table1.col3 = table3.col3
A: I'm not sure I really understand the question but what about
select col1, C1, C2
from table
left join ( ... first query ...) as t1 using(col1)
left join ( ... second query ...) as t2 using(col2)
Using this technique you probably can transform the subqueries into joins.
A: Assuming that your queries should have the obvious group by clause, you can do:
select t1.col1,
sum(case when t1.col3 in (select col3 from table2) and
t1.col2 = 'C1'
then t1.value else 0
end) as C1,
sum(case when t1.col3 in (select col3 from table3) and
t1.col2 = 'C2'
then t1.value else 0
end) as C2
from table1 t1
group by t1.col1;
I would caution you from doing explicit joins. Multiple matching rows in the table2 and table3 would throw off your sums.
| |
doc_23532639
|
so, I need the code to export the Calc Files data to server.
| |
doc_23532640
|
public void MostrarCombobox(ComboBox cmbIDart)
{
Command = "SELECT idArtigoAvaliar FROM dbo.PorAvaliasao WHERE (avaliado = 0) AND (idAutor ='" + Autor.id2 + "')";
SqlCommand Comm1 = new SqlCommand(Command, Conn);
SqlDataAdapter data = new SqlDataAdapter(Comm1);
SqlCommand sqlCommand = new SqlCommand();
using (Conn)
{
sqlCommand = Conn.CreateCommand();
sqlCommand.CommandText = Command;
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, Conn);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
//Criar uma tabela para receber os dados
DataTable dTable = new DataTable();
//Preencher a tabela
sda.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
cmbIDart.DataSource = bSource;
Conn.Close();
}
}
My problem is that when I am starting to call the ComboBox, it shows System.Data... and I want them to show the value.
What am I doing wrong?
A: I think in your combobox rows look like showing like;
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
System.Data.DataRowView
You need to set your Combobox DisplayMember and ValueMember properties.
If this is not fix your problem, try to make things more clear dynamically.
Combobox1.Items.Clear();
string Command = "SELECT idArtigoAvaliar FROM dbo.PorAvaliasao WHERE (avaliado = 0) AND (idAutor ='" + Autor.id2 + "')";
SqlCommand cmd = new SqlCommand(Command, Conn);
cmd.CommandText = Command;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Combobox1.Items.Add(dr["idArtigoAvaliar"].ToString());
}
| |
doc_23532641
|
As soon as I hover over the Menu, .drp-btn:hover .menu-content-container doesn't work.
<div class="nav-container">
<div class="drp-btn"> Menu </div>
<div class="menu-content-container">
<ul class="menu-content">
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Booking</a></li>
</ul>
</div>
</div>
.nav-container {
margin-top: 2px;
display: flex;
flex-direction: column;
}
.menu-content-container {
border: 5px solid red;
}
.drp-btn {
margin-left: 60vw;
border: 2px solid red;
font-size: 20px;
}
.drp-btn:hover .menu-content-container {
display: flex;
background-color: red;
color: white;
}
.menu-content-container {
display: none;
}
.nav-container ul li {
margin-left: 2%;
list-style-type: none;
}
.nav-container a {
font-size: 20px;
text-decoration: none;
}
A: <div class="nav-container">
<div class="drp-btn"> Menu
<div class="menu-content-container">
<ul class="menu-content">
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Booking</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</div>
</div>
wrap the code drp-btn div
A: You need to wrap your menu-content-container into the drp-btn div to make that work:
.nav-container {
margin-top: 2px;
display: flex;
flex-direction: column;
}
.menu-content-container {
border: 5px solid red;
}
.drp-btn {
margin-left: 60vw;
border: 2px solid red;
font-size: 20px;
}
.drp-btn:hover .menu-content-container {
display: flex;
background-color: red;
color: white;
}
.menu-content-container {
display: none;
}
.nav-container ul li {
margin-left: 2%;
list-style-type: none;
}
.nav-container a {
font-size: 20px;
text-decoration: none;
}
<div class="nav-container">
<div class="drp-btn"> Menu
<div class="menu-content-container">
<ul class="menu-content">
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Booking</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</div>
</div>
| |
doc_23532642
|
*
*A: sample.com
*B: sample.com/en
I tried to write a code in PHP following these conditions, but when I access the RUL of A:sample.com, a browser(chrome) shows an error.
So would you mind telling me how should I solve this problem?
Thank you in advance.
the conditions for access
*
*The first access is only to [A: sample.com]
*Users whose browser language is set to Japanese access to [A:
sample.com]
*All users whose browser language setting is not set to Japanese
access [B: sample.com/en]
The errors messages in the browser(chrome)
This page isn’t working
sample.com redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
The code for adding in functions.php
<?php
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang == 'ja') {
$url = get_site_url();
}
header("Location: $url");
exit();
}
?>
Development environment
*
*CentOS (7 x86_64)
*Apache (2.4.6 CentOS)
*PHP (7.1.33)
*wordpress(5.2.5)
A: Just make below change in your code:
if ($lang != 'ja') {
header("Location: $url");
exit();
}
Edited:
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang != 'ja') {
header("Location: $url");
exit();
}
}
| |
doc_23532643
|
I google searched everywhere, tried many different things, the closest thing to getting it work correctly is this question, however, he is assuming you can compile the library... the very step I am having trouble with.
Ok, so I am using MinGW with Code::Blocks, and I can run an OpenGL + GLUT program, it compiles and runs fine.
I'm not very experienced with compiling libraries, so please be gentle.
So, FTGL doesn't use CMake, it uses ./configure, make, make install... and I saw the different configure.??? and Makefile.??? files, which I figured out where used with autoconf and automake, I believe. So I tried downloading these, there is no executable to point my PATH environment variable at, so I figured out they use Python...
Now the Python shell I can't seem to get that to the right place to run the ./configure command. Somehow I feel like I'm going in the wrong direction.
Well, that is all too hard, maybe MSYS has the auto tools built in? Well, if it does, I can't navigate to the source files for the library and can't find autoconf and can't find automake.
All I want to do is compile FTGL in MinGW. Can somebody please help me?
A: I was facing the same problem some weeks ago. I ended up using a custom Makefile, not that convenient but pretty doable since FTGL is not that huge.
if found those two links very helpful:
*
*Instruction and sample
Makefile
i was able to use the Makefile provided there with very little
modification
*Adaption of FTGL header
files
| |
doc_23532644
|
The following question in particular touches on this subject but is not resolved.
Gathering wide columns into multiple long columns using pivot_longer
Take the following sample data. As you can see there is a unique identifier variable, and then 8 other variables. Of the other 8, you can group them into two sets, gpa and percent_a. For each set there is a class, group, course, and dept value.
In my actual data I have about 20 different sets, all with the same structure, the same four descriptors in each set.
What I would like to do is perform a function similar to pivot_longer. Except instead of combining multiple columns into a set of key and value columns, each unique set in my data (class, group, course, dept) would be grouped into there own key/value columns.
set.seed(101)
df <- data.frame(
id = 1:10,
class_gpa = rnorm(10, 0, 1),
course_gpa = rnorm(10, 0, 1),
group_gpa = rnorm(10, 0, 1),
dept_gpa = rnorm(10, 0, 1),
class_percent_a = rnorm(10, 0, 1),
course_percent_a = rnorm(10, 0, 1),
group_percent_a = rnorm(10, 0, 1),
dept_percent_a = rnorm(10, 0, 1)
)
So in this example, lets say I group all of the gpa values into two columns (gpa_type, and gpa_value) and the percent_a values into two columns (percent_a_type, percent_a_value), then I would end up at the end with only 5 columns:
id, gpa_type, gpa_value, percent_a_type, percent_a_value
Is there a way to do this? Either with pivot_longer or another method. Thanks.
A: Honestly, I would rather simply do:
df %>% pivot_longer(-id, names_to = c("type", ".value"), names_pattern = "([^_]+)_(.*)")
And keep the data into a more practical format:
# A tibble: 40 x 4
id type gpa percent_a
<int> <chr> <dbl> <dbl>
1 1 class -0.326 0.482
2 1 course 0.526 -1.15
3 1 group -0.164 -0.260
4 1 dept 0.895 1.51
5 2 class 0.552 0.758
6 2 course -0.795 -0.274
7 2 group 0.709 -1.41
8 2 dept 0.279 1.62
9 3 class -0.675 -2.32
10 3 course 1.43 0.578
# … with 30 more rows
Why duplicate the "type" attribute for each "set"?
For your desired output:
# A tibble: 40 x 5
id gpa_type gpa_value percent_a_type percent_a_value
<int> <chr> <dbl> <chr> <dbl>
1 1 class -0.326 class 0.482
2 1 course 0.526 course -1.15
3 1 group -0.164 group -0.260
4 1 dept 0.895 dept 1.51
5 2 class 0.552 class 0.758
6 2 course -0.795 course -0.274
7 2 group 0.709 group -1.41
8 2 dept 0.279 dept 1.62
9 3 class -0.675 class -2.32
10 3 course 1.43 course 0.578
# … with 30 more rows
You could try:
lst_df <- df %>%
gather(key, value, -id) %>%
extract(key, into = c("var", "type"), "([^_]+)_(.*)") %>%
split(.$type)
names(lst_df) %>%
map_dfc(~ setNames(
lst_df[[.x]] %>%
select(-type),
c("id", paste0(.x, c("_type", "_value"))))) %>%
select(-matches("id\\d+"))
| |
doc_23532645
|
I have this state:
state = {
tasks: {
workingProgress: [],
toDo: [],
done: [],
},
};
And from api I get objects like these:
{id: "1", task: "add button", team: "Metro", status: "workingProgress", …}
{id: "8", task: "fixed accessibility SR", team: "Metro", status: "toDo", …}
My idea is transform my state in something like this:
tasks: {
workingProgress: [{id: "1", task: "add button", team: "Metro", ...},{}, {}],
toDo: [{id: "8", task: "fixed accessibility SR", team: "Metro", ...}, {}, {}],
done: [],
},
I have this and works as a charm:
state = {
tasks: {
workingProgress: [],
toDo: [],
done: [],
},
};
componentDidMount() {
TasksAPI.getAll().then((res) => {
this.setState(({ tasks }) => {
res.forEach((item) => {
if (tasks[item.status]) {
tasks[item.status].push(item);
}
});
return { tasks };
});
});
}
My question is because I intend to change from "setState" code from hooks.
const [tasks, setTasks] = useState({
workingProgress: [],
toDo: [],
done: [],
});
const history = useHistory();
useEffect(() => {
TasksAPI.getAll().then((res) => {
setTasks(({ tasks }) => {
res.forEach((item) => {
if (tasks[item.status]) {
tasks[item.status].push(item);
}
});
return { tasks };
});
});
}, []);
But when I try this my code is break:
Tasks.js:21 Uncaught (in promise) TypeError: Cannot read property
'toDo' of undefined
This is my return:
<div>
{Object.entries(tasks).map(([key, status]) => (
<div key={key}>
<div >
<ol>
{status.map((item) => (
<li>
<div>
......
</div>
Is my "hooks" approach incorrect?
A: I think the problem lies inside the code of your useEffect and specifically setTasks(({ tasks }) =>... and return { tasks };, which have 2 main problems:
*
*In this piece of code you create a local tasks variable that overiddes your tasks from state, returned by useState.
*You also trying to destruct this state and grab tasks property but this is wrong since your state is already the tasks. You carried this logic from the previous implementation where your state was an object containing a tasks property.
Your useEffect should be changed like below:
useEffect(() => {
TasksAPI.getAll().then((res) => {
setTasks((previousTasks) => {
const newTasks = {...previousTasks}
res.forEach((item) => {
if (newTasks[item.status]) {
newTasks[item.status] = [...newTasks[item.status], item]
}
});
return newTasks;
});
});
}, []);
newTasks = [...previousTasks] and newTasks[item.status] = [...newTasks[item.status], item] ensure that you don't mutate the previous tasks object and status arrays and create new ones.
Even your 1st solution (with classes) does not tackle this problem which can lead to bugs with react updates.
However if you don't care about deep immutability you can simplify the code inside forEach to (although i wouldn't advise so):
if (newTasks[item.status]) {
newTasks[item.status].push(item);
}
A: Issue
From what I can see you've a simple state mutation issue. The effect hook callback is for-each'ing over the res array and directly pushing into the tasks state instead of creating new array and state references.
You are also attempting to destructure tasks from the tasks state, which of obviously not a defined property. When it was this.state.tasks and "previousState" was this.state you could destructure tasks, but now in the useState hook tasks is the state! You then return an object return { tasks }; with a single tasks property with the real state nested deeper, i.e. making it tasks.tasks.toDo for example.
Solution
Instead of looping through and enqueueing multiple state updates, which necessarily need to correctly update from each previously enqueued update, just loop though and create the new next state object and enqueue a single state update.
const [tasks, setTasks] = useState({
workingProgress: [],
toDo: [],
done: [],
});
useEffect(() => {
TasksAPI.getAll()
.then((res) => {
setTasks(tasks => res.reduce(
(tasks, task) => ({
...tasks, // <-- shallow copy the state
[task.status]: [
...(tasks[task.status] ?? []), // <-- shallow copy array
task // <-- append new task item
],
}),
tasks, // <-- start from the previous state
));
});
}, []);
| |
doc_23532646
| ||
doc_23532647
|
A: Running rake db:drop:all will only clean your database.
If you plan on changing your models and you think your migrations will not reflect your data model anymore, simply delete them.
You might want to clean the file db/schema.rb too
You might want to checkout rails migration guide http://guides.rubyonrails.org/migrations.html
| |
doc_23532648
|
I am developing MVC 3 application and using razor syntax.
In this application I am giving commenting facility.
I have given the facility to adding a comment and it saved in DB.
and when user clicks on delete button it displays the message as "Clicked".
When user load entity, previously added comments get displayed on page with
delete button and when user click on that button the "clicked" msg appears.
now, when user add a new comment, it saved in DB sucsessfully and also appear on the page
along with Delete button.
now when user click on delete button msg wontcome...
( I append the Div tag while loading the new comment from DB)
I think , there is a issue regarding append, means previous comments Delete button
work well, but when I add button using append it wont works...
Here is the code which is in partial view which add comment in DB and again fetches latest comment back to view to display It.
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#AddCommentButton').click(function ()
{
var comment1 = $('#Comment').val();
if (comment1 == '') {
alert('Please enter a comment');
return;
}
$.ajax({
type: 'post',
url: '/Comment/SaveComments',
dataType: 'json',
data:
{
'comments' : $('#Comment').val(),
'EType' : @Html.Raw(Json.Encode(ViewBag.EType)),
'EId' : @Html.Raw(Json.Encode(ViewBag.EId))
},
success: function (data) {
$("p.p12").append('<button type="button" id=' + data.Id + ' class="deleteComment2">Delete</button></div>')
}
});
});
});
</script>
I use below code, when i clicked on the delete button...
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$('.deleteComment').live('click', function () {
alert('Clicked');
});
</script>
Now , the summary of a problem is I append div and in that div I add a button and I am trying to get click event of that button but I cant get that event.
Can anyone please give the simple code for handling of button's click event when button get added runtime in the Div tag.
Here is the new code, I have added your code in page, but it still not working.
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
@model IEnumerable<CRMEntities.Comment>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!DOCTYPE html>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).on('click', '.deleteComment', function()
{
alert('comment deleted');
});
$(document).ready(function () {
alert("Doc loaded");
});
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#AddCommentButton').click(function () {
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
});
});
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".ShowComments").click(function () {
$(".ParentBlock").slideToggle("slow");
});
});
</script>
</head>
<body>
@{
<div class="ParentBlock">
@foreach (var item in Model)
{
<div class="OwnerClass" id="OwnerName">
<span class="EmpName"> @Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { @style = "color:#1A6690;" })</span>
@Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName"><button type="button" id = "@item.Id" class="deleteComment">Delete</button></span>
<span class="EmpName"> @Html.ActionLink("Delete", "Delete", "Comment", new { id = item.Id }, new { @style = "color:#1A6690;" })</span>
<p class="CommentP">
@Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
<a class="Delete222" style="cursor:move;display:none;">DeleteNew</a>
<br />
</div>
}
<p class="p12">
</p>
</div>
<p id="ClassPara" class="ShowComments" onclick="chkToggle()">Show All Comments</p>
}
@Html.TextArea("Comment", "", 5, 80, "asdsd")
<input type="button" value="Add Comment" id="AddCommentButton"/>
<input type="button" value="Clear" onclick="clearText()"/>
<br />
<div id="comments22">
<input type="button" class="deleteComment" value="Delete" /><br/>
<input type="button" class="deleteComment" value="Delete" /><br/>
<input type="button" class="deleteComment" value="Delete" /><br/>
</div>
</body>
</html>
A: How many times do you intend to include jQuery in your page? 1 should be enough. You seem to have included it in a 3 different places. Also you seem to have placed your scripts outside if the <html> element which is completely wrong.
Only one inclusion is necessary:
<script src="@Url.Content("~/Scripts/jquery-1.8.0.min.js")" type="text/javascript"></script>
Also you should use the .on() method to subscribe to the click event of the delete button in a lively manner:
$(document).on('click', '.deleteComment', function () {
alert('Clicked');
});
And last but not least you seem to be using the runat="server" attribute on your <head> element. That's Razor, not WebForms - forget about those attributes.
So let me clean this code for you because it is a complete mess:
@model IEnumerable<CRMEntities.Comment>
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="ParentBlock">
@foreach (var item in Model)
{
<div class="OwnerClass" id="OwnerName">
<span class="EmpName">
@Html.ActionLink(
item.Owner.FullName,
"Details",
"EMployee",
new { id = item.OwnerId },
new { @style = "color:#1A6690;" }
)
</span>
@Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName">
<button type="button" id = "@item.Id" class="deleteComment">Delete</button>
</span>
<span class="EmpName">
@Html.ActionLink(
"Delete",
"Delete",
"Comment",
new { id = item.Id },
new { @style = "color:#1A6690;" }
)
</span>
<p class="CommentP">
@Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
<a class="Delete222" style="cursor:move;display:none;">DeleteNew</a>
<br />
</div>
}
<p class="p12"></p>
</div>
<p id="ClassPara" class="ShowComments" onclick="chkToggle()">Show All Comments</p>
@Html.TextArea("Comment", "", 5, 80, "asdsd")
<input type="button" value="Add Comment" id="AddCommentButton"/>
<input type="button" value="Clear" onclick="clearText()"/>
<br />
<div id="comments22">
<input type="button" class="deleteComment" value="Delete" /><br/>
<input type="button" class="deleteComment" value="Delete" /><br/>
<input type="button" class="deleteComment" value="Delete" /><br/>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<!-- or use your own jQuery version locally: -->
@*<script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.8.1.js")"></script>*@
<script type="text/javascript">
$(document).on('click', '.deleteComment', function () {
alert('comment deleted');
});
$('.ShowComments').click(function () {
$('.ParentBlock').slideToggle('slow');
});
$('#AddCommentButton').click(function () {
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
$('#comments22').append('<input type="button" class="deleteComment" value="Delete" /><br/>');
});
</script>
</body>
</html>
A: You can show your delete message when user click on delete button like below
In my application when user click on delete button link then this div open for confirmation message .
<div id="dialog-confirm" title="Delete Country">
<p>
Are you soure you wont to delete this record ?</p>
</div>
<script type="text/javascript">
$(function () {
$(".lnkDelete").button();
$(".lnkDelete").button();
$("#dialog-confirm").dialog({
autoOpen: false,
model: true,
width: 300,
resizable: false,
height: 200
});
$(".lnkDelete").click(function (e) {
e.preventDefault();
var targeturl = $(this).attr("href");
$("#dialog-confirm").dialog({
buttons: {
"Confirm": function () {
window.location.href = targeturl;
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$("#dialog-confirm").dialog("open");
});
});
</script>
In the view
@foreach (var item in Model)
{
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID }, new { @Class = "lnkDelete" })
</td>
</tr>
}
i think this will help you.
A: If you're using a jQuery version of 1.7 or above then you should use .on()
$('body').on('.deleteComment', 'click', function () {
alert('Clicked');
});
A: You are adding the event in the document Ready event .. But the elements are not available then to attach the events.
You need to make sure you add the event after element is created... So add that in the success callback function ..
Otherwise the created element will not be associated with the event handler...
success: function(data) {
$("p.p12").append('<button type="button" id=' + data.Id + ' class="deleteComment2">Delete</button></div>');
// Add the event to the Delete button when created...
$('#' + data.Id).on('click', function() {
alert('Clicked');
});
}
| |
doc_23532649
|
I have a background-size: cover image set as the header of single posts which used to fill the screen, with content beginning immediately below. For some reason, it no longer does this. The background image itself is scaling to fit the screen, but the content below it (the text of the post) is beginning immediately after the overlaid text.
You can see what I mean in this fiddle.
If I set #hero-header to position:absolute; min-height: 100%; min-width:100%; then the image does fill the screen when you load the page. The problem then is that the content below it runs over the top, rather than beginning just off screen.
Can anyone suggest a solution?
To clarify what I mean by 'fill the screen', following a response below:
The div that contains the background image should fill the entire screen when you load it. At the moment the background image is scaling to fit the screen, but #hero-header is not forcing the content below it off the page – it is falling after the text element, .hero-text, within it instead.
A: This has fixed the problem:
Background image moved to html and #hero-header set to height: 100vh.
| |
doc_23532650
|
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // some day in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename={$file}");
header("Content-Transfer-Encoding: binary");
readfile($file);
This works fine with smaller files but not with larger ones and even after turning errors on I get no errors and no error log. I'm sure this is to do with the shared memory limit (or possibly a timeout) but does anyone know how I go about forcing downloads of large files on shared servers, ideally without javascript as i'm sure i won't be able to set the memory limits to be high enough?
Thanks very much,
Dave
A: The usual solution is to do the file output yourself and let the web server's own buffers handle things:
$fh = fopen($file, 'rb') or die("Unable to open $file");
while($data = fread($fh, 10240)) { // 10kbyte chunks.
echo $data;
}
fclose($fh);
| |
doc_23532651
|
When I use Workbooks.open method to open this csv file, it takes me 30 seconds.
However, Excel foramtted the data automatically during file opening. It formats some values like date, currency, etc. And I have no idea how to stop Excel from doing auto formatting....
To avoid this, now I use QueryTable to load a csv file instead.
Nevertheless, it's horribly slow. It took me over 90 seconds to open the same file.
I have checked that it takes less than 10 seconds for excel to build a connection with the target file.
Besides, I believe that I've already optimize the codes that I am using. (Or maybe not? any suggestion is appreciated)
Is there any other good idea to have excel open a csv file as quick as possible as Workbook.open without formatting it?
Either by improving my sample codes, or giving out a totally different way is acceptable. (This function is a part of a big automation process, so the solution must be using VBA)
By the way, the data in my csv file will certainly contains comma in the value.
I need a safe way (without parsing comma by myself) to open the csv file quickly than what I currently have.
I once tried open a big csv file as text, but it cannot distinguish commas in values...
I also appreciate any explanation that why QueryTable takes much more time to open a file than using Workbooks.open...
Public Function ImportCsv(path As Variant, TargetWb As Workbook) As Worksheet
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
TargetWb.Activate
Dim QueryTableName As String
QueryTableName = "tmp_" & Format(Now, "hhmmss") & Right(Format(Timer, "0000"), 4) 'Use time stamp since delete might fail due to unexpected reason.
ActiveWorkbook.Queries.Add Name:=QueryTableName, Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source= Csv.Document(File.Contents(""" & path & """),[Delimiter="","", Columns=null, Encoding=932, QuoteStyle=QuoteStyle.Csv])," & Chr(13) & "" & Chr(10) & " Transformation = Table.TransformColumnTypes( Source, Table.ToRows(Table.FromColumns({Table.ColumnNames(Source), List.Repeat({type text}, List.Count(Table.ColumnNames(Source)) )})))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Transformation"
ActiveWorkbook.Worksheets.Add 'Only ActiveSheet works for some properties of QueryTable.
With ActiveSheet.ListObjects.Add(LinkSource:=False, SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & QueryTableName & ";Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [" & QueryTableName & "]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = False
.ListObject.DisplayName = QueryTableName
.ListObject.ShowHeaders = False
.ListObject.ShowTableStyleRowStripes = False
.Refresh BackgroundQuery:=False
.MaintainConnection = False
End With
ActiveSheet.Rows("1:1").Delete Shift:=xlUp 'Remove empty row which was once header.
'ActiveSheet.QueryTables(QueryTableName).Delete 'Delete unneeded TempQueryTable.
Set ImportCsv = ActiveSheet
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Function
| |
doc_23532652
|
I am programming on vc10 / win7
I deliberately not handle error to keep clear the code on this post.
First step, I make a rgb24 bitmap file and save it as "test.bmp" :
void GetBitmap24FromDcToFile(HDC winDC, int x, int y, int w, int h)
{
int imgsize;
if((3 * w) % 4 > 0)
imgsize = ((3 * w) / 4 + 1) * 4 * h;
else if((3 * w) % 4 == 0)
imgsize = 3 * w * h;
BITMAPINFO bi;
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = h;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 24;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = imgsize;
bi.bmiHeader.biXPelsPerMeter = 0;
bi.bmiHeader.biYPelsPerMeter = 0;
bi.bmiHeader.biClrUsed = 0;
bi.bmiHeader.biClrImportant = 0;
void *pvBits = NULL;
HBITMAP hbmp = ::CreateDIBSection(winDC, &bi, DIB_RGB_COLORS, &pvBits, NULL, 0);
HDC hdc = ::CreateCompatibleDC(winDC);
HBITMAP holdbmp = (HBITMAP)::SelectObject(hdc, hbmp);
::BitBlt(hdc, 0, 0, w, h, winDC, x, y, SRCCOPY);
HANDLE hFile = ::CreateFile(_T("test.bmp"), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwCnt;
BITMAPFILEHEADER bmfh;
ZeroMemory(&bmfh, sizeof(BITMAPFILEHEADER));
bmfh.bfType = 0x4d42;
bmfh.bfSize = imgsize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
bmfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
WriteFile(hFile, (char*)&bmfh, sizeof(BITMAPFILEHEADER), &dwCnt, NULL);
WriteFile(hFile, (char*)&bi.bmiHeader, sizeof(BITMAPINFOHEADER), &dwCnt, NULL);
WriteFile(hFile, (char*)pvBits, imgsize, &dwCnt, NULL);
CloseHandle(hFile);
::SelectObject(hdc, holdbmp);
::DeleteDC(hdc);
::DeleteObject(hbmp);
}
Second step, i make a bitmap from a device context :
HBITMAP GetBitmap24FromDC(HDC winDC, int x, int y, int w, int h)
{
HDC hMemDC = ::CreateCompatibleDC( winDC );
HBITMAP hbmp; // = ::CreateCompatibleBitmap( winDC, w, h);
BITMAPINFOHEADER infoHeader;
infoHeader.biSize = sizeof(infoHeader);
infoHeader.biWidth = (LONG)w;
infoHeader.biHeight = (LONG)h;
infoHeader.biPlanes = 1;
infoHeader.biBitCount = 24;
infoHeader.biCompression = BI_RGB;
infoHeader.biSizeImage = 0;
infoHeader.biXPelsPerMeter = 0;
infoHeader.biYPelsPerMeter = 0;
infoHeader.biClrUsed = 0;
infoHeader.biClrImportant = 0;
BITMAPINFO info;
info.bmiHeader = infoHeader;
unsigned char *mem;
hbmp = CreateDIBSection(winDC, &info, DIB_RGB_COLORS, (void**)&mem, 0, 0);
HBITMAP holdbmp = (HBITMAP) ::SelectObject(hMemDC, hbmp);
::BitBlt(hMemDC, 0, 0, w, h, winDC, x, y, SRCCOPY);
::SelectObject(hMemDC, holdbmp);
::DeleteDC(hMemDC);
return hbmp;
}
And i use this method for comparaison :
// Author: PJ Arends - codeproject
bool CompareBitmaps(HBITMAP HBitmapLeft, HBITMAP HBitmapRight)
{
if (HBitmapLeft == HBitmapRight)
{
return true;
}
if (NULL == HBitmapLeft || NULL == HBitmapRight)
{
return false;
}
bool bSame = false;
HDC hdc = GetDC(NULL);
BITMAPINFO BitmapInfoLeft = {0};
BITMAPINFO BitmapInfoRight = {0};
BitmapInfoLeft.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
BitmapInfoRight.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
if (0 != GetDIBits(hdc, HBitmapLeft, 0, 0, NULL, &BitmapInfoLeft, DIB_RGB_COLORS) &&
0 != GetDIBits(hdc, HBitmapRight, 0, 0, NULL, &BitmapInfoRight, DIB_RGB_COLORS))
{
// Compare the BITMAPINFOHEADERs of the two bitmaps
if (0 == memcmp(&BitmapInfoLeft.bmiHeader, &BitmapInfoRight.bmiHeader,
sizeof(BITMAPINFOHEADER)))
{
// The BITMAPINFOHEADERs are the same so now compare the actual bitmap bits
BYTE *pLeftBits = (BYTE*)malloc(sizeof(BYTE) * BitmapInfoLeft.bmiHeader.biSizeImage);
BYTE *pRightBits = (BYTE*)malloc(sizeof(BYTE) * BitmapInfoRight.bmiHeader.biSizeImage);
BYTE *pByteLeft = NULL;
BYTE *pByteRight = NULL;
PBITMAPINFO pBitmapInfoLeft = &BitmapInfoLeft;
PBITMAPINFO pBitmapInfoRight = &BitmapInfoRight;
// calculate the size in BYTEs of the additional
// memory needed for the bmiColor table
int AdditionalMemory = 0;
switch (BitmapInfoLeft.bmiHeader.biBitCount)
{
case 1:
AdditionalMemory = 1 * sizeof(RGBQUAD);
break;
case 4:
AdditionalMemory = 15 * sizeof(RGBQUAD);
break;
case 8:
AdditionalMemory = 255 * sizeof(RGBQUAD);
break;
case 16:
case 32:
AdditionalMemory = 2 * sizeof(RGBQUAD);
}
if (AdditionalMemory)
{
// we have to allocate room for the bmiColor table that will be
// attached to our BITMAPINFO variables
pByteLeft = new BYTE[sizeof(BITMAPINFO) + AdditionalMemory];
if (pByteLeft)
{
memset(pByteLeft, 0, sizeof(BITMAPINFO) + AdditionalMemory);
memcpy(pByteLeft, pBitmapInfoLeft, sizeof(BITMAPINFO));
pBitmapInfoLeft = (PBITMAPINFO)pByteLeft;
}
pByteRight = new BYTE[sizeof(BITMAPINFO) + AdditionalMemory];
if (pByteRight)
{
memset(pByteRight, 0, sizeof(BITMAPINFO) + AdditionalMemory);
memcpy(pByteRight, pBitmapInfoRight, sizeof(BITMAPINFO));
pBitmapInfoRight = (PBITMAPINFO)pByteRight;
}
}
if (pLeftBits && pRightBits && pBitmapInfoLeft && pBitmapInfoRight)
{
// zero out the bitmap bit buffers
memset(pLeftBits, 0, BitmapInfoLeft.bmiHeader.biSizeImage);
memset(pRightBits, 0, BitmapInfoRight.bmiHeader.biSizeImage);
// fill the bit buffers with the actual bitmap bits
if (0 != GetDIBits(hdc, HBitmapLeft, 0,
pBitmapInfoLeft->bmiHeader.biHeight, pLeftBits, pBitmapInfoLeft,
DIB_RGB_COLORS) && 0 != GetDIBits(hdc, HBitmapRight, 0,
pBitmapInfoRight->bmiHeader.biHeight, pRightBits, pBitmapInfoRight,
DIB_RGB_COLORS))
{
// compare the actual bitmap bits of the two bitmaps
bSame = 0 == memcmp(pLeftBits, pRightBits,
pBitmapInfoLeft->bmiHeader.biSizeImage);
}
}
// clean up
free(pLeftBits);
free(pRightBits);
free(pByteLeft);
free(pByteRight);
}
}
ReleaseDC(NULL, hdc);
return bSame;
}
So, in my main code i have something like that :
(...)
HWND capture = ::FindWindow(_T("the_window_class"), NULL);
HDC winDC = ::GetDC(capture);
GetBitmap24FromDcToFile(winDC, 0, 0, 200, 200); // generate bitmap file "test.bmp"
HBITMAP bmpFile = (HBITMAP)LoadImage( NULL, _T("test.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION );
HBITMAP bmpMem = GetBitmap24FromDC(winDC, 0, 0, 200, 200); // get bitmap from DC
bool isEqual = CompareBitmaps(bmpFile, bmpMem); // test both bitmaps
if(isEqual)
AfxMessageBox(_T("Success"));
(...)
Comparaison between two files return true; two bitmaps from dc return true;
Comparaison between a bitmap file and a dc bitmap always return false.
After debugging, it passe the first test-condition (in the Compare method) where we check the BITMAPINFOHEADERs. It fail on the last memcmp() where we compare the bits of the two bitmaps.
In the debugger, the structure are the same for both bitmaps, I have only a small difference between the two pBitmapInfoLeft\pBitmapInfoRight->bmiColors field.
Checking the bits from the two bitmaps headers are the same (pLeftBits\pRightBits).
An idea, an alternative, an example? let me know! thank you!
*
*JE
A: There's a sort of a bug though.
You use the BITMAPINFO structure, which is actually a fake, not designed to be used as-is.
The actual bitmap header consists of a fixed BITMAPINFOHEADER structure, and a variable-sized array of RGBQUAD structures, whereas the size of this array depends on the data in the BITMAPINFOHEADER. Depending on the bitmap bitness, this array should have the following length:
*
*1/4/8: the array size should be 2^bitness. I.e. 2/16/256 respectively. The bitmap is considered indexed, and the values in this array define the actual colors.
*16: The pixel values translate into colors using so-called bitfields. The array size depends on biCompression member:
*
*BI_RGB: the array should be empty. Default bitfields 5-5-5 are used.
*BI_BITFIELDS: The array should have 3 entries. The define the appropriate bitmasks for R/G/B channels.
*32: The pixel values either directly correspond to the colors, or translate using bitfields if biCompression is set to BI_BITFIELDS. As with 16-bit case, the array should be either empty or have 3 entries.
The BITMAPINFO structure consists of the BITMAPINFO structure (bmiHeader), and bmiColors, which always has one entry. Which is never the case.
That's why BITMAPINFO is actually a fake structure. In order to create the bitmap header one should first allocate the needed amount of memory for the BITMAPINFOHEADER and the needed array, and then cast it to the BITMAPINFO.
In simple words: comparing BITMAPINFO structures (i.e. using sizeof(BITMAPINFO)) doesn't make sense. The bmiColors will either contain uninitialized data, or be inaccessible, or will actually have larger size.
P.S. BTW, the whole bitmap comparison is somewhat dirty IMHO. Saving the bitmap to the file, just to compare - looks insane. Also you don't actually need to allocate the memory for the whole bitmap, it may be compared line-by-line.
Also, if one of the bitmaps is a DIB, you may directly get pointer to its bits, hence allocating extra memory and copying is not needed.
A: I believe you could use SoIL Library (or any other than WinApi, actually) for loading and operating on bitmap files. It's free and lightweight, and will shorten your code by about 90%.
| |
doc_23532653
|
namespace MyNameSpace{
public static class MyClass{
public static IEnumerable<MyDataObject> GetVeryLargeResponse(){
while(CheckForSomeFunkyConditionThatsRarelyTrue()){
yield return GetMyNextDataObject();
}
yield break;
}
}
}
In Matlab when I make a call
result = MyClass.GetVeryLargeResponse();
I would expect result to be of type IEnumerable<MyDataObject>, so as to be able to get the Enumerator<MyDataObject> by calling result.GetEnumerator().
Where as I'm getting result which is of type MyNameSpace.<GetVeryLargeResponse>d_3 with no GetEnumerator() method available. I do see one of result's Super class being System.Collections.Generic.IEnumerable<MyClass>.
Is there a way I can iterate over this in Matlab or even to 'cast' result to IEnumerable<MyClass> in Matlab.
p.s.
*
*Converting to Array / IList etc is not feasible due to data volume
*This is not duplicate of How can I iterate over a C# IEnumerable in Matlab?, as that is dealing with IQueryable specifically.
*I'm using Matlab 2010b
A: The result does have a GetEnumerator() method - it's just may be implemented with explicit interface implementation.
If Matlab isn't willing to handle that, you could always write your own mapping type and an extension method to make things simpler:
public static class Extensions
{
public static EnumerableWrapper<T> Wrap<T>(this IEnumerable<T> source)
{
return new EnumerableWrapper<T>(source);
}
}
public class EnumerableWrapper<T> : IEnumerable<T>
{
private readonly IEnumerable<T> source;
public EnumerableWrapper(IEnumerable<T> source)
{
this.source = source;
}
public IEnumerator<T> GetEnumerator()
{
return new EnumeratorWrapper<T>(source.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class EnumeratorWrapper<T> : IEnumerator<T>
{
private readonly IEnumerator<T> source;
public EnumeratorWrapper(IEnumerator<T> source)
{
this.source = source;
}
public T Current { get { return source.Current; } }
object IEnumerator.Current { get { return Current; } }
public bool MoveNext()
{
return source.MoveNext();
}
public void Reset()
{
source.Reset();
}
public void Dispose()
{
source.Dispose();
}
}
Then try:
result = MyClass.GetVeryLargeResponse().Wrap();
It seems very odd for Matlab not so support this out of the box though...
A: Consider the following example:
MyClass.cs
namespace MyNameSpace {
public class Person {
public string name { get; set; }
public int age { get; set; }
}
public class MyClass {
private static List<Person> people = new List<Person> {
new Person {name = "name1", age=10},
new Person {name = "name2", age=20},
new Person {name = "name3", age=30},
new Person {name = "name4", age=40},
new Person {name = "name5", age=50}
};
public static IEnumerable<Person> GetPeople() {
foreach (var p in people) {
yield return p;
}
}
}
}
code.m
%# load my assembly
str = 'C:\path\to\MyNameSpace.dll';
NET.addAssembly(str);
obj = MyNameSpace.MyClass.GetPeople(); %# IEnumerable<Person>
%# call ToArray() extension method: this forces immediate query evaluation
NET.addAssembly('System.Core'); %# contains 'System.Linq' namespace
arr = NET.invokeGenericMethod('System.Linq.Enumerable', 'ToArray', ...
{'MyNameSpace.Person'}, obj);
%# loop through results
for i=1:arr.Length
fprintf('name=%s, age=%d\n', char(arr(i).name), int32(arr(i).age));
end
The code produces the output:
name=name1, age=10
name=name2, age=20
name=name3, age=30
name=name4, age=40
name=name5, age=50
As you can see, I did convert the returned object as an array Person[] (which I realize you were trying to avoid). The weird thing is if you if we look at the hierarchy of classes:
>> superclasses(obj)
Superclasses for class MyNameSpace.<GetPeople>d__0:
System.Object
System.Collections.Generic.IEnumerable<MyNameSpace*Person>
System.Collections.IEnumerable
System.Collections.Generic.IEnumerator<MyNameSpace*Person>
System.IDisposable
System.Collections.IEnumerator
handle
you can see the System.Collections.Generic.IEnumerator<Person>, but somehow the object doesn't seem to expose the inherited GetEnumerator method:
>> methods(obj,'-full')
Methods for class MyNameSpace.<GetPeople>d__0:
MyNameSpace.<GetPeople>d__0 obj <GetPeople>d__0(int32 scalar <>1__state)
logical scalar RetVal Equals(MyNameSpace.<GetPeople>d__0 this, System.Object obj)
int32 scalar RetVal GetHashCode(MyNameSpace.<GetPeople>d__0 this)
System.Type RetVal GetType(MyNameSpace.<GetPeople>d__0 this)
System.String RetVal ToString(MyNameSpace.<GetPeople>d__0 this)
event.listener L addlistener(handle sources, char vector eventname, function_handle scalar callback) % Inherited from handle
event.proplistener L addlistener(handle sources, meta.property properties, char vector eventname, function_handle scalar callback) % Inherited from handle
event.proplistener L addlistener(handle sources, string propertyname, char vector eventname, function_handle scalar callback) % Inherited from handle
event.proplistener L addlistener(handle sources, cell propertynames, char vector eventname, function_handle scalar callback) % Inherited from handle
delete(handle obj) % Inherited from handle
logical TF eq(A, B) % Inherited from handle
handle HM findobj(handle H, varargin) % Inherited from handle
meta.property prop findprop(handle scalar object, string propname) % Inherited from handle
logical TF ge(A, B) % Inherited from handle
logical TF gt(A, B) % Inherited from handle
logical validity isvalid(handle obj) % Inherited from handle
logical TF le(A, B) % Inherited from handle
logical TF lt(A, B) % Inherited from handle
logical TF ne(A, B) % Inherited from handle
notify(handle sources, string eventname) % Inherited from handle
notify(handle sources, string eventname, event.EventData scalar eventdata) % Inherited from handle
A: You need to use explicit casts. First explicitly cast the IEnumerable instance:
result = MyClass.GetVeryLargeResponse();
resultEnumerable = NET.explicitCast(result,'System.Collections.IEnumerable');
Then get the enumerator:
resultEnumerator = resultEnumerable.GetEnumerator();
Then explicitly cast the enumerator:
resultEnumerator = NET.explicitCast(resultEnumerator, 'System.Collections.IEnumerator');
You can then iterate over the collection as desired:
while (resultEnumerator.MoveNext)
resultEnumerator.Current
end
| |
doc_23532654
|
but for some reason I don't get, additional headers are ignored.
This is my code:
$errors = '';
$myemail = 'my@email.com';
$myemail_bcc = 'my_bbc@email.com';
if(empty($_POST['nome']) || empty($_POST['email']))
{
$errors .= "Error: You must fill Name and Email fields";
}
$name = $_POST['nome'];
$email_address = $_POST['email'];
$telefono = $_POST['telefono'];
$message = $_POST['messaggio'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "<br />Error: You must use a valid email address";
}
// spediamo la mail
if( empty($errors))
{
$to = $myemail;
$email_subject = "New Request from: $name";
$email_body = "User data:.\n\n";
$email_body .= "Nome: $name \nEmail: $email_address \nTelefono: $telefono \n";
$email_body .= "Messaggio: \n$message";
$headers = "From: John Smith <$myemail>\r\n";
$headers .= "Reply-To: $name <$email_address>\r\n";
$headers .= "Bcc: $myemail_bcc";
mail($to,$email_subject,$email_body,$headers);
}
I've tried to vary the way I declare headers without names, just with emails:
$headers = "From: $myemail \r\n";
$headers .= "Reply-To: $email_address\r\n";
$headers .= "Bcc: $myemail_bcc";
and even just on one line
$headers = "From: $myemail\r\nReply-To: $name <$email_address>\r\nBcc: $myemail_bcc";
But in no case the mail is sento to the Bcc address, and the "reply" function in client email does not use the Reply-to address.
where am I wrong?
| |
doc_23532655
|
SetSkip()
SetLimit()
SetSort()
so that i should be able to do something like Find().SetSkip().SetLimit() in a single line , is that doable ?
Also I want to know the usage of MergeFindOptions
func MergeFindOptions(opts ...*FindOptions) *FindOptions
Any examples will be of great help.
A: Just embed the options.FindOptions struct into a custom one. Additionally you could add a FindOptions function to initialize this custom struct, like the mongo package do by options.Find().
package your_db_package
type YourFindOptions struct {
*options.FindOptions
}
func FindOptions() YourFindOptions {
return YourFindOptions{options.Find()}
}
// ---
package your_service_package
import "your_db_package"
func GetItems() {
opts := your_db_package.FindOptions().SetSkip(123).SetLimit(456)
}
As the name MergeFindOptions and the documentation says it's for merging multiple FindOptions into a new one:
MergeFindOptions combines the given FindOptions instances into a single FindOptions in a last-one-wins fashion.
| |
doc_23532656
|
The person at this link (http://grokbase.com/t/gg/cukes/12bk4kx7m0/cucumber-jvm-what-is-the-best-way-to-split-up-a-large-step-definition-class) seems to have had the same question, but the couple of links in the answers were dead ends as there was a site migration from GitHub/cucumber to cucumber.io.
A: Just define a step class that contains steps used in various features and the declare it's package in your Runner for every feature you will need it.
This will get a little bit more complicated if you have data shared between your steps. Let's say you have a shared step that collects user data and different Then-steps will have to evaluate this data. Since cucumber does not allow heritage you have tgo inject the data object in both step classes. One defines the user's data and the other will evaluate it.
| |
doc_23532657
|
When I print the word generated right after it is generated it gives me a list of words, as intended. When I am out of the word generating and stacking loop, and print an output of the words again, I get all the words mashed up in one long chain, it is really bizarre. What is wrong?
#include <stdio.h>
#define MAXWORDS 10
#define MAXLETTERS 6
int lcg(int Xcur) /*linear congruential generator*/
{
int A = 445, C = 700001, M = 2097152;
int Xnext = (A * Xcur + C) % M;
return Xnext;
}
int main()
{
int x;
printf("input seed for linear congruential generator: ");
scanf("%d",&x);
char consonants[]="bcdfghjklmnprstvwxz";
char vowels[]="aeiou";
int i,j;
int turn;
char words[MAXWORDS][MAXLETTERS];
for(i=0;i<MAXWORDS;i++)
{
turn=1;
for(j=0;j<MAXLETTERS;j++,turn++)
{
x=lcg(x); /* random number generated */
if(turn%2) /* one consonant, one vowel, in turn */
words[i][j]=consonants[x%19];
else
words[i][j]=vowels[x%5];
}
words[i][j]='\0';
/* print each word generated */
printf("word %d: %s\n", i+1, words[i]);
}
/* print the first word again */
printf("\n\nthe 1st word again: %s\n",words[0]);
return 0;
}
output:
input seed for linear congruential generator: 23
word 1: wuduca
word 2: navozo
word 3: depiza
word 4: jukiti
word 5: raliwi
word 6: danila
word 7: cexewi
word 8: bamohu
word 9: jiruzi
word 10: temomo
the 1st word again: wuducanavozodepizajukitiraliwidanilacexewibamohujiruzitemomo
A: It is because is is getting stored in continuous manner without any null char.
Method 1:
If you just want to print it properly you can do it by writing below line:
printf("\n\nthe 1st word again: %s\n",words[0]);
as
printf("\n\nthe 1st word again: %.*s\n",MAXLETTERS, words[0]);
Method 2:
Declare words as
char words[MAXWORDS][MAXLETTERS+1];
and write the inside for loop as
for(j=0;j<MAXLETTERS;j++,turn++)
{
x=lcg(x); /* random number generated */
if(turn%2) /* one consonant, one vowel, in turn */
words[i][j]=consonants[x%19];
else
words[i][j]=vowels[x%5];
}
words[i][MAXLETTERS] = '\0';
A: There is no room in the array for the string terminator. Consequently writing the '\0' terminator is undefined behaviour. In practice (since a 2D array is contiguous), the terminator was written to the next string, which was then overwritten by its data.
Try changing
char words[MAXWORDS][MAXLETTERS];
to
char words[MAXWORDS][MAXLETTERS+1];
A: Also,
Watch out for int overflow.
Code does not insure 0 <= Xcur <= (INT_MAX - C)/A, so A * Xcur + C results can then exceed INT_MAX...
int A = 445, C = 700001, M = 2097152;
int Xnext = (A * Xcur + C) % M;
... resulting in UB: likely negative values can then return from the function.
x=lcg(x);
words[i][j]=consonants[x%19];
x%19 results then in -18 ... 18 leading to bad indexing.
Simple fix, yet does not address the root of the issue.
//Use %19u so the result is never < 0, unlike %19
words[i][j]=consonants[x%19u];
I would also use unsigned math to avoid UB of overflow and not generate negative results.
int lcg(int Xcur) /*linear congruential generator*/
{
unsigned A = 445, C = 700001, M = 2097152;
int Xnext = (A * Xcur + C) % M;
return Xnext;
}
Code also has issue with 16-bit int.
| |
doc_23532658
|
A: You are right nodejs and iojs do not support ES6 syntax. But react native:
As of version 0.5.0, React Native ships with the Babel JavaScript compiler.
Read more here
That means that there is another transpiler (Babel) at work in the React packager. It converts from ECMAScript 2015 (ES6) to ES5. This allows you to use the ES6 features like: destructuring, computed property keys, classes, arrow functions, block-scoped variables and more.
If you want to use those features in the React (not Native) app, you will need to include Babel in your project.
Edit:
There is no another transpiler.
React and React Native have both switched their respective build systems to make use of Babel. This replaced JSTransform, the source transformation tool that we wrote at Facebook.
More in Deprecating JSTransform and react-tools
| |
doc_23532659
|
[merchant] [clean value] [desired output]
UPS1Z3734A345 UPS UPS
UPS 1Z68A3125 UPS UPS
HOME DEPOT #3421 HOME DEPOT HOME DEPOT
STAPLES - #123 STAPLES STAPLES
STPLS #4560 STPLS STAPLES
There are a number of different cases I need to be able to tackle (e.g. "-", numeric values, "#" characters, etc.)
I am fairly new in regex, but this is what I have come up with so far
(.+)[?=#]
However, this only addresses when there is a "#" in the string. Furthermore, if there are no non-letter characters in the string, the field returns blank
I'd love to get some help on how to properly craft this expression.
A: Try this:
((?:[^\d#-]){2,}).*$
it will create a group that should contain your clean value. (any char until it finds a digit, # or -)
https://regex101.com/r/tFUcct/1
| |
doc_23532660
|
I tried where(:date.year == year) but of course I got NoMethodError: undefined method 'year' for :date:Symbol. Is it possible to do this type of query?
A: You can use a scope to build something like:
scope :for_year, lambda {|date| where("date >= ? and date <= ?", "#{date.year}0101", "#{date.year}1231")}
A: In your Model:
scope :by_year, lambda { |year| where('extract(year from created_at) = ?', year) }
In your Controller:
@courses = Course.by_year(params[:year])
A: Jesse gave you, I think, the idea for the actual solution, but to explain why this failed - it's because it tried to evaluate ".year" as a method on the symbol you passed it: ":date".
The word :date is just a parameter to tell "where" which value it will later use to construct the SQL query to pass to the db.
It doesn't turn into the actual date of the record. But the ".year" will evaluate as you're passing it as a parameter, before anything has been done with the ":date" symbol.
A: Assuming your date format is: YYYY-MM-DD HH:MM:SS
Try this:
where(Date.strptime(:date, "%Y-%m-%d %H:%M:%S").year == year)
OR
where(["YEAR(?) = ?", :date, year])
| |
doc_23532661
|
if (grade >= 90) { letterGrade = "A"; }
if (grade >= 80) { letterGrade = "B"; }
if (grade >= 70) { letterGrade = "C"; }
if (grade >= 60) { letterGrade = "D"; }
Just a HW problem I can't figure out.
A: You should have an if-else if ladder:
if (grade >= 90) { letterGrade = "A"; }
else if (grade >= 80) { letterGrade = "B"; }
else if (grade >= 70) { letterGrade = "C"; }
else if (grade >= 60) { letterGrade = "D"; }
.. otherwise all the if statements will be executed.
You should avoid hardcoding values like that. Consider the case when later on sometime, the grade system changes, and you start providing grade E for grade >= 50. Then it will be nightmare for you to change the code.
A better to handle this is to use an enum. You might notice a behaviour in those ranges. Diving any value in a certain range by 10, will give you the same number. You can use this logic to create an enum of grades:
enum Grade {
A(9), B(8), C(7), D(6);
private final Grade[] GRADES = values();
private final int grade;
private Grade(int grade) { this.grade = grade; }
public int getGrade() { return this.grade; }
public Grade valueOf(int grade) {
for (Grade grade: GRADES) {
if (grade.getGrade() == grade / 10)
return grade;
}
return null;
}
}
Then, for a particular grade value, you can get the letter grade by using getValue(grade) method:
Grade letterGrade = Grade.valueOf(grade);
Now, it's easy to expand the enum when a new grade range is added. Now, this enum wouldn't work if the range is something like - [85, 100] for A. For that, you can have the value of grade in enum as lower bound, like 85 for A. Then change the logic of returning Grade to > instead of ==.
There can be other ways to form the logic, but that would depend upon the situation. But this approach will be far more maintainable.
Here's a quote from Effective Java - Item 50:
Strings are poor substitutes for enum types. As discussed in Item 30,
enums make far better enumerated type constants than strings.
A: Your conditions satisfying all the if statements.Use if else
String letterGrade = "F";
if (grade >= 90) {
letterGrade = "A";
}
else if (grade >= 80) {
letterGrade = "B";
}
else if (grade >= 70) {
letterGrade = "C";
}
else if (grade >= 60) {
letterGrade = "D";
}else {
letterGrade="none"; //remove else it. so grade "F" remain
}
}
| |
doc_23532662
|
I'm trying to read a blob stored in my blob storage account which is just a text file containing some numeric data delimited by spaces for example. I used the template generated by databricks for reading blob data
spark.conf.set(
"fs.azure.account.key."+storage_account_name+".blob.core.windows.net",
storage_account_access_key)
df = spark.read.format(file_type).option("inferSchema", "true").load(file_location)
where file_location is my blob file (https://xxxxxxxxxx.blob.core.windows.net).
I get the following error:
No filesystem named https
I tried using sc.textFile(file_location) to read in an rdd and get the same error.
A: Your file_location should be in the format:
"wasbs://<your-container-name>@<your-storage-account-name>.blob.core.windows.net/<your-directory-name>"
See: https://docs.databricks.com/spark/latest/data-sources/azure/azure-storage.html
A: You need to mount the blob with external location to access it via Azure Databricks.
Reference: https://docs.databricks.com/spark/latest/data-sources/azure/azure-storage.html#mount-azure-blob-storage-containers-with-dbfs
A: These three lines of code worked for me:
spark.conf.set("fs.azure.account.key.STORAGE_ACCOUNT.blob.core.windows.net","BIG_KEY")
df = spark.read.csv("wasbs://CONTAINER@STORAGE_ACCOUNT.blob.core.windows.net/")
df.select('*').show()
NOTE that line 2 ends with .net/ because I do not have a sub-folder.
| |
doc_23532663
|
- a path to a `directory` containing vocabulary files required by the tokenizer, for instance saved using the :func:`~transformers.PreTrainedTokenizer.save_pretrained` method, e.g.: ``./my_model_directory/``.
- (not applicable to all derived classes, deprecated) a path or url to a single saved vocabulary file if and only if the tokenizer only requires a single vocabulary file (e.g. Bert, XLNet), e.g.: ``./my_model_directory/vocab.txt``.
So, I went to the model hub:
*
*https://huggingface.co/models
I found the model I wanted:
*
*https://huggingface.co/bert-base-cased
I downloaded it from the link they provided to this repository:
Pretrained model on English language using a masked language modeling
(MLM) objective. It was introduced in this paper and first released in
this repository. This model is case-sensitive: it makes a difference
between english and English.
Stored it in:
/my/local/models/cased_L-12_H-768_A-12/
Which contains:
./
../
bert_config.json
bert_model.ckpt.data-00000-of-00001
bert_model.ckpt.index
bert_model.ckpt.meta
vocab.txt
So, now I have the following:
PATH = '/my/local/models/cased_L-12_H-768_A-12/'
tokenizer = BertTokenizer.from_pretrained(PATH, local_files_only=True)
And I get this error:
> raise EnvironmentError(msg)
E OSError: Can't load config for '/my/local/models/cased_L-12_H-768_A-12/'. Make sure that:
E
E - '/my/local/models/cased_L-12_H-768_A-12/' is a correct model identifier listed on 'https://huggingface.co/models'
E
E - or '/my/local/models/cased_L-12_H-768_A-12/' is the correct path to a directory containing a config.json file
Similarly for when I link to the config.json directly:
PATH = '/my/local/models/cased_L-12_H-768_A-12/bert_config.json'
tokenizer = BertTokenizer.from_pretrained(PATH, local_files_only=True)
if state_dict is None and not from_tf:
try:
state_dict = torch.load(resolved_archive_file, map_location="cpu")
except Exception:
raise OSError(
> "Unable to load weights from pytorch checkpoint file. "
"If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True. "
)
E OSError: Unable to load weights from pytorch checkpoint file. If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True.
What should I do differently to get huggingface to use my local pretrained model?
Update to address the comments
YOURPATH = '/somewhere/on/disk/'
name = 'transfo-xl-wt103'
tokenizer = TransfoXLTokenizerFast(name)
model = TransfoXLModel.from_pretrained(name)
tokenizer.save_pretrained(YOURPATH)
model.save_pretrained(YOURPATH)
>>> Please note you will not be able to load the save vocabulary in Rust-based TransfoXLTokenizerFast as they don't share the same structure.
('/somewhere/on/disk/vocab.bin', '/somewhere/on/disk/special_tokens_map.json', '/somewhere/on/disk/added_tokens.json')
So all is saved, but then....
YOURPATH = '/somewhere/on/disk/'
TransfoXLTokenizerFast.from_pretrained('transfo-xl-wt103', cache_dir=YOURPATH, local_files_only=True)
"Cannot find the requested files in the cached path and outgoing traffic has been"
ValueError: Cannot find the requested files in the cached path and outgoing traffic has been disabled. To enable model look-ups and downloads online, set 'local_files_only' to False.
A: I had this same need and just got this working with Tensorflow on my Linux box so figured I'd share.
My requirements.txt file for my code environment:
tensorflow==2.2.0
Keras==2.4.3
scikit-learn==0.23.1
scipy==1.4.1
numpy==1.18.1
opencv-python==4.5.1.48
seaborn==0.11.1
tensorflow-hub==0.12.0
nltk==3.6.2
tqdm==4.60.0
transformers==4.6.0
ipywidgets==7.6.3
I'm using Python 3.6.
I went to this site here which shows the directory tree for the specific huggingface model I wanted. I happened to want the uncased model, but these steps should be similar for your cased version. Also note that my link is to a very specific commit of this model, just for the sake of reproducibility - there will very likely be a more up-to-date version by the time someone reads this.
I manually downloaded (or had to copy/paste into notepad++ because the download button took me to a raw version of the txt / json in some cases... odd...) the following files:
*
*config.json
*tf_model.h5
*tokenizer_config.json
*tokenizer.json
*vocab.txt
NOTE: Once again, all I'm using is Tensorflow, so I didn't download the Pytorch weights. If you're using Pytorch, you'll likely want to download those weights instead of the tf_model.h5 file.
I then put those files in this directory on my Linux box:
/opt/word_embeddings/bert-base-uncased/
Probably a good idea to make sure there's at least read permissions on all of these files as well with a quick ls -la (my permissions on each file are -rw-r--r--). I also have execute permissions on the parent directory (the one listed above) so people can cd to this dir.
From there, I'm able to load the model like so:
tokenizer:
# python
from transformers import BertTokenizer
# tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
tokenizer = BertTokenizer.from_pretrained("/opt/word_embeddings/bert-base-uncased/")
layer/model weights:
# python
from transformers import TFAutoModel
# bert = TFAutoModel.from_pretrained("bert-base-uncased")
bert = TFAutoModel.from_pretrained("/opt/word_embeddings/bert-base-uncased/")
A: This should be quite easy on Windows 10 using relative path. Assuming your pre-trained (pytorch based) transformer model is in 'model' folder in your current working directory, following code can load your model.
from transformers import AutoModel
model = AutoModel.from_pretrained('.\model',local_files_only=True)
Please note the 'dot' in '.\model'. Missing it will make the code unsuccessful.
A: Where is the file located relative to your model folder? I believe it has to be a relative PATH rather than an absolute one. So if your file where you are writing the code is located in 'my/local/', then your code should be like so:
PATH = 'models/cased_L-12_H-768_A-12/'
tokenizer = BertTokenizer.from_pretrained(PATH, local_files_only=True)
You just need to specify the folder where all the files are, and not the files directly. I think this is definitely a problem with the PATH. Try changing the style of "slashes": "/" vs "\", these are different in different operating systems. Also try using ".", like so ./models/cased_L-12_H-768_A-12/ etc.
A: In addition to config file and vocab file, you need to add tf/torch model (which has.h5/.bin extension) to your directory.
in your case, torch and tf models maybe located in these url:
torch model: https://cdn.huggingface.co/bert-base-cased-pytorch_model.bin
tf model: https://cdn.huggingface.co/bert-base-cased-tf_model.h5
you can also find all required files in files and versions section of your model: https://huggingface.co/bert-base-cased/tree/main
A: bert model folder containd these files:
config.json
tf_model.h5
tokenizer_config.json
tokenizer.json
vocab.txt
instaed of these if we require bert_config.json
bert_model.ckpt.data-00000-of-00001
bert_model.ckpt.index
bert_model.ckpt.meta
vocab.txt
then how to do
A: Here is a short ans.
tokenizer = BertTokenizer.from_pretrained('path/to/vocab.txt',local_files_only=True)
model = BertForMaskedLM.from_pretrained('/path/to/pytorch_model.bin',config='../config.json', local_files_only=True)
Usually config.json need not be supplied explicitly if it resides in the same dir.
A: you can use simpletransformers library. checkout the link for more detailed explanation.
model = ClassificationModel(
"bert", "dir/your_path"
)
Here I used Classification Model as an example. You can use it for many other tasks as well like question answering etc.
| |
doc_23532664
|
Now, I am trying to get the intersect of each lists of potential numbers in a column. Something like the onlyOnePlaceForNbrInCol function bellow.
Code:
potentialNbrsAt :: Int -> Int -> Sudoku -> [Int]
potentialNbrsAt x y sudoku = intersect rowMissingNbrs $ intersect colMissingNbrs sqrMissingNbrs
where rowMissingNbrs = getMissingNbrs $ getRow y sudoku
colMissingNbrs = getMissingNbrs $ getCol x sudoku
sqrMissingNbrs = getMissingNbrs $ getSquare squareIndex sudoku
squareIndex = 3 * (y `div` 3) + (x `div` 3)
onlyOnePlaceForNbrInCol :: Int -> Int -> Sudoku -> Bool
onlyOnePlaceForNbrInCol colIndex nbr sudoku = -- What goes here? Some pointers please???
I think onlyOnePlaceForNbrInCol should, at some point, call potentialNbrsAt with each numbers from 0 to 8 as an argument for y. Telling me how to do this would greatly help.
A: So you're trying to determine whether all of the numbers [0..8] fulfill a given predicate.
A: What about [ potentialNbrsAt x y sudoku | y <- [0..8] ] ? This gives you a list of all the results for such values of y.
| |
doc_23532665
|
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *countrySelection;
switch (indexPath.section) {
case kFirstSection:
countrySelection = [[NSString alloc]
initWithFormat:@"The country you have chosen is %@",
[self.MyCountries objectAtIndex: indexPath.row]];
[self performSegueWithIdentifier:@"doneResults" sender:self];
self.countryResult.text = countrySelection;
break;
The label isn't updated and I just don't know what should be done.
Thanks in advance!
A: These kind of things really need to be set on the View Controller that owns them. Use a public property to pass the value of the selected country to that view controller as outlined below:
First, create a property called something like:
@property(non atomic,strong) NSString *countryChosen;
in the destination View Controller, and make sure to @synthesize it
No reason to create another property for the IndexPath. Just use
// Pass along the indexPath to the segue prepareForSegue method, since sender can be any object
[self performSegueWithIdentifier:@"doneResults" sender:indexPath];
in the didSelectRowAtIndexPath method.
Then in the prepareForSegueMethod:
MyDestinationViewController *mdvc = segue.destinationViewController;
NSIndexPath *indexPath = (NSIndexPath *)sender;
mdvc.countryChosen = [self.MyCountries objectAtIndex: indexPath.row]];
On the viewDidLoad event of the Destination VC, just use:
self.countryResult.text = countryChosen;
* EDIT *
To deal with a datasource that has multiple sections, just use the same logic that you have in the cellForRowAtIndexPath.
NSDictionary *selRow = [[self.countriesIndexArray valueForKey:[[[self.countriesIndexArray allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:sindexPath.row];
Change this to suit your needs, but basically you are implementing the same logic that you would to display a cell, except you are specifying the indexPath (both section and row) that you want.
Then something like the following to set that property on the destination VC:
self.countryResult.text = [selRow valueForKey@"Country"];
A: In your current view controller create a new property for the indexPath of the cell the user selected, like this:
@property(strong,nonatomic) NSIndexPath *path;
@synthesize it and then when a user selects a row, set it by using
self.path = indexPath;
When you perform a segue, it will always call
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
So what you can do now when prepareForSegue: gets called, is the following:
/* if this is not the only segue you are performing you want to check on the identifier first to make sure this is the correct segue */
NSString *countrySelection = [[NSString alloc]
initWithFormat:@"The country you have chosen is %@",
[self.MyCountries objectAtIndex: self.path.row]];
segue.destinationViewController.countryResult.text = countrySelection;
/* after creating the text, set the indexPath to nil again because you don't have to keep it around anymore */
self.path = nil;
For this to work the view controller you want to show after selecting the cell must have a property for the UILabel, on which you are trying to set the text.
| |
doc_23532666
|
This is mine
this is my code
i use DataSet to make this
Private Sub BtnCetakPerKelas_Click(sender As Object, e As EventArgs) Handles BtnCetakPerKelas.Click
Try
If CboSemester.Text = String.Empty Then
MessageBox.Show("Pilih semester")
Exit Sub
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Try
Try
query = "Select TA, Kelas, Semester From TblJadwal_Detail where TA = '" & TxtTA.Text & "' and Semester = '" & _
CboSemester.Text & "' order by kelas"
cmd = New SqlCommand(query, con)
adapter = New SqlDataAdapter(cmd)
tabel = New DataTable
adapter.Fill(tabel)
Dim tabel1 As New DataTable
tabel.Columns.Add(3)
tabel.Columns(3).ColumnName = "Sesi"
For i = 0 To 7
tabel.Rows.Add(i)
tabel.Rows(i)(3) = i + 1
Next
'senin
query = "Select MataPelajaran.MP From TblJadwal_Detail inner join MataPelajaran On TblJadwal_Detail.KodeMP = MataPelajaran.KodeMP where TA = '" & TxtTA.Text & "' and TblJadwal_Detail.Semester = '" & _
CboSemester.Text & "' and Hari = 'Senin'"
cmd = New SqlCommand(query, con)
adapter = New SqlDataAdapter(cmd)
Dim tabels As New DataTable
adapter.Fill(tabels)
tabel.Columns.Add(4)
tabel.Columns(4).ColumnName = "Senin"
For i = 0 To tabels.Rows.Count - 1
tabel.Rows.Add(i)
tabel.Rows(i)(4) = tabels.Rows(i)(0)
Next
'selasa
query = "Select MataPelajaran.MP From TblJadwal_Detail inner join MataPelajaran On TblJadwal_Detail.KodeMP = MataPelajaran.KodeMP where TA = '" & TxtTA.Text & "' and TblJadwal_Detail.Semester = '" & _
CboSemester.Text & "' and Hari = 'Selasa'"
cmd = New SqlCommand(query, con)
adapter = New SqlDataAdapter(cmd)
tabels = New DataTable
adapter.Fill(tabels)
tabel.Columns.Add(5)
tabel.Columns(5).ColumnName = "Selasa"
For i = 0 To tabels.Rows.Count - 1
tabel.Rows.Add(i)
tabel.Rows(i)(5) = tabels.Rows(i)(0)
Next
'Rabu
query = "Select MataPelajaran.MP From TblJadwal_Detail inner join MataPelajaran On TblJadwal_Detail.KodeMP = MataPelajaran.KodeMP where TA = '" & TxtTA.Text & "' and TblJadwal_Detail.Semester = '" & _
CboSemester.Text & "' and Hari = 'Rabu'"
cmd = New SqlCommand(query, con)
adapter = New SqlDataAdapter(cmd)
tabels = New DataTable
adapter.Fill(tabels)
tabel.Columns.Add(6)
tabel.Columns(6).ColumnName = "Rabu"
For i = 0 To tabels.Rows.Count - 1
tabel.Rows.Add(i)
tabel.Rows(i)(6) = tabels.Rows(i)(0)
Next
'kamis
query = "Select MataPelajaran.MP From TblJadwal_Detail inner join MataPelajaran On TblJadwal_Detail.KodeMP = MataPelajaran.KodeMP where TA = '" & TxtTA.Text & "' and TblJadwal_Detail.Semester = '" & _
CboSemester.Text & "' and Hari = 'Kamis'"
cmd = New SqlCommand(query, con)
adapter = New SqlDataAdapter(cmd)
tabels = New DataTable
adapter.Fill(tabels)
tabel.Columns.Add(7)
tabel.Columns(7).ColumnName = "Kamis"
For i = 0 To tabels.Rows.Count - 1
tabel.Rows.Add(i)
tabel.Rows(i)(7) = tabels.Rows(i)(0)
Next
'Jumat
query = "Select MataPelajaran.MP From TblJadwal_Detail inner join MataPelajaran On TblJadwal_Detail.KodeMP = MataPelajaran.KodeMP where TA = '" & TxtTA.Text & "' and TblJadwal_Detail.Semester = '" & _
CboSemester.Text & "' and Hari = 'Jumat'"
cmd = New SqlCommand(query, con)
adapter = New SqlDataAdapter(cmd)
tabels = New DataTable
adapter.Fill(tabels)
tabel.Columns.Add(8)
tabel.Columns(8).ColumnName = "Jumat"
For i = 0 To tabels.Rows.Count - 1
tabel.Rows.Add(i)
tabel.Rows(i)(8) = tabels.Rows(i)(0)
Next
'sabtu
query = "Select MataPelajaran.MP From TblJadwal_Detail inner join MataPelajaran On TblJadwal_Detail.KodeMP = MataPelajaran.KodeMP where TA = '" & TxtTA.Text & "' and TblJadwal_Detail.Semester = '" & _
CboSemester.Text & "' and Hari = 'Sabtu'"
cmd = New SqlCommand(query, con)
adapter = New SqlDataAdapter(cmd)
tabels = New DataTable
adapter.Fill(tabels)
tabel.Columns.Add(9)
tabel.Columns(9).ColumnName = "Sabtu"
For i = 0 To tabels.Rows.Count - 1
tabel.Rows.Add(i)
tabel.Rows(i)(9) = tabels.Rows(i)(0)
Next
Dim cr As New cetakjadwalkelas
Dim pr As New Vw1
cr.Database.Tables(0).SetDataSource(tabel)
pr.CrystalReportViewer1.ReportSource = cr
pr.WindowState = FormWindowState.Maximized
pr.Show()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
| |
doc_23532667
|
I can't find some buildin function/variable for it.
Can someone help/tell me the <DirectoryRef Id="TARGETDIR"> structure or the solution for my problem?
Thanks.
A: First, are you sure that you want to do this? You will get a behavior where each user who logs in and starts up your program will attempt to do a repair and ask for the original install if not found. Also when you uninstall you won't be able to clean up all the users profiles.
Many people prefer the "first run" pattern where you have the installer install to C:\Documents and Settings\All Users\ and when you run your program it copies the files to the current user profile if needed ( usually only if you are overriding something that is set for all users ).
Otherwise, here is a list of available directories in Windows Installer / WiX
System Folder Properties:
http://msdn.microsoft.com/en-us/library/aa370905(v=VS.85).aspx#system_folder_properties
You'll want to choose from AppDataFolder, LocalAppDataFolder and CommonAppDataFolder.
| |
doc_23532668
|
The numbers are using the OCR-B font and may also contain + and > characters.
This is my source image:
The scans using Tesseract weren't very good, even when limiting the character set to the mentioned characters. As I didn't find any OCRB training files for Tesseract, I decided to train it myself.
I created this training image and made a box file from it. The box file is correct, all letters are matched correctly.
Then I did all steps described here to create the other necessary files.
Using this newly trained OCR-B tessdata-set, I get pretty good results on the source image, with one little bug: All 1s are mistaken for 8s and vice-versa. The command used to process the image was
$ tesseract esr2c.tif ocrb-esr2c -l ocrb
and the output for the source image was
0800000001456>8 00000195731208 8 01050008 023+ 08 0301226>20
If you swap all 1s and 8s and compare it to the source image, the output would be correct (except for the last two letters which I can ignore).
How could this happen? Did I do some mistake in the training process? How can I fix it?
A: It's likely that somewhere in your box file has incorrect values (characters) for 1 and 8. You can verify using jTessBoxEditor program. If so, correct, regenerate the language data file, and try again.
A: I have trained tesseract 2.04 after 1 month efforts for OCR A extended font. Its working very well and showing above 90 Accuracy with font size 14.
Training image should be high Contrast image.
Use "GIMP" image editor and do following
Menu Colors->Info->Histgram- Read Std Deviation value
colors-> Threshould -> Write "Std Deviation value" as Threshould value
Save image
Use it for training.
Check and edit your box file using "qt-box-editor-1.06.exe".It is very easy to use.
Check All boxes and characters in it.
It is very important. Somewhere in your box file has incorrect characters for 1 and 8.
Run other cmds.
| |
doc_23532669
|
Usage:
rails new APP_PATH [options]
Options:
-r, [--ruby=PATH] # Path to the Ruby binary of your choice
# Default: /Users/ethanfranson/.rvm/rubies/ruby-2.2.1/bin/ruby
-m, [--template=TEMPLATE] # Path to some application template (can be a filesystem path or URL)
[--skip-gemfile], [--no-skip-gemfile] # Don't create a Gemfile
-B, [--skip-bundle], [--no-skip-bundle] # Don't run bundle install
-G, [--skip-git], [--no-skip-git] # Skip .gitignore file
[--skip-keeps], [--no-skip-keeps] # Skip source control .keep files
-O, [--skip-active-record], [--no-skip-active-record] # Skip Active Record files
-S, [--skip-sprockets], [--no-skip-sprockets] # Skip Sprockets files
[--skip-spring], [--no-skip-spring] # Don't install Spring application preloader
-d, [--database=DATABASE] # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
# Default: sqlite3
-j, [--javascript=JAVASCRIPT] # Preconfigure for selected JavaScript library
# Default: jquery
-J, [--skip-javascript], [--no-skip-javascript] # Skip JavaScript files
[--dev], [--no-dev] # Setup the application with Gemfile pointing to your Rails checkout
[--edge], [--no-edge] # Setup the application with Gemfile pointing to Rails repository
[--skip-turbolinks], [--no-skip-turbolinks] # Skip turbolinks gem
-T, [--skip-test-unit], [--no-skip-test-unit] # Skip Test::Unit files
[--rc=RC] # Path to file containing extra configuration options for rails command
[--no-rc], [--no-no-rc] # Skip loading of extra configuration options from .railsrc file
Runtime options:
-f, [--force] # Overwrite files that already exist
-p, [--pretend], [--no-pretend] # Run but do not make any changes
-q, [--quiet], [--no-quiet] # Suppress status output
-s, [--skip], [--no-skip] # Skip files that already exist
Rails options:
-h, [--help], [--no-help] # Show this help message and quit
-v, [--version], [--no-version] # Show Rails version number and quit
Description:
The 'rails new' command creates a new Rails application with a default
directory structure and configuration at the path you specify.
You can specify extra command-line arguments to be used every time
'rails new' runs in the .railsrc configuration file in your home directory.
Note that the arguments specified in the .railsrc file don't affect the
defaults values shown above in this help message.
Example:
rails new ~/Code/Ruby/weblog
My app is called bloccit, and in my terminal shell I am in my code/bloccit directory but still nothing. If anyone could help with any tips I would be very thankful!
A: rails s runs scripts located in your app's bin directory. Without it, you get the message shown above.
I asked for the contents of your app directory (using ls) and you responded:
Gemfile Rakefile config.ru log tmp Gemfile.lock
app db public vendor README.md config lib spec
As you can see, your bin directory is missing. It must be restored/replaced.
If you moved it or threw it in the trash, restore it.
If you deleted it, you can copy one from another/new Rails app. Create a folder somewhere outside your existing app, generate an empty Rails app (rails new throwaway), then go in and copy the bin folder to your existing app.
A: Make sure that you are in your root application directory. That error you posted is commonly seen if you are not in root application directory.
You can use pwd command to show where is your current directory. You said that your app name is bloccit and you should be in that root directory and fire rails s.
A: It's likely that it's suggesting you to create a new rails app because it's unable to identify your Rails app.
Since you're using Rails version 4.x, it looks for bin/rails to identify a Rails app. If you don't have bin directory at the root of your application, try to run rake rails:update:bin
| |
doc_23532670
|
Now I want change the textbox form and font because it's look ugly
How I do it?
It's how I create the textbox
HWND WindowManager::textbox(int width, int height, int xPos, int yPos, LPCSTR content, bool edit_able)
{
int type = (edit_able) ? (WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL) : (WS_CHILD|WS_VISIBLE|WS_HSCROLL|ES_AUTOHSCROLL);
return CreateWindowEx(
WS_EX_CLIENTEDGE,
"EDIT",
content,
type,
xPos,
yPos,
width,
height,
window,
(HMENU)50,
GetModuleHandle(NULL),
NULL
);
}
A: Several Windows controls are initialized with the ugly System font - if you want nice looking controls, you have to change the font yourself like so:
// create the text box
HWND hTextBox = CreateWindowEx(...);
// initialize NONCLIENTMETRICS structure
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(ncm);
// obtain non-client metrics
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0);
// create the new font
HFONT hNewFont = CreateFontIndirect(&ncm.lfMessageFont);
// set the new font
SendMessage(hTextBox, WM_SETFONT, (WPARAM)hNewFont, 0);
A: The WM_SETFONT message is what you're looking for.
| |
doc_23532671
|
My issue is when I click on a button, AJAX is done and content will be loaded (with this tab menu content), but the its not working as normal.
Here are my screen shots with on page onload and AJAX load,
Normal Page load
Works fine
AJAX load
Not working
May be the js file will be loaded only for page load.
How can can make it work for AJAX
My AJAX,
$.ajax({
type: 'GET',
url: destinationUrl,
data: content, // my parameters
dataType: "text",
success: function(data) { // data is tab menu content
$('#successDiv').html(data); // data is populated in successDiv
}
});
There are no errors in console. But tabbing is not working with ajax as working in page load
A: According to the example in: http://www.menucool.com/tabbed-content
<ul class="tabs">
<li><a href="#view1">Features</a></li>
<li><a href="#view2">How to Use</a></li>
<li><a href="#view3">Source Code</a></li>
</ul>
<div class="tabcontents">
<div id="view1">
content 1
</div>
<div id="view2">
content 2
</div>
<div id="view3">
content 3
</div>
</div>
you could do this:
$(document).ready(function(){
$("ul.tabs li a").click(function(){
var menuId = $(this).prop('href');
var el = $(menuId);
menuId = id.substring(1);
var request = $.ajax({
url: "script.php",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
el.html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
})
})
| |
doc_23532672
|
Application components contains EditView components which can contain many other EditView components and one Dialog component( if Dialog component is visible on a page).
Dialog component contains Application component. When I put that in Dialog component in declaration path:
directives:[Application]
I'am getting this error:
Unexpected directive value 'undefined' on the View of component 'Dialog'
Is it possible at all to have such structure where child component can contain component from upper level regarding some conditions?
If I drop Application component from Dialog or replace it with other components it works fine.
Zlaja
A: Putting it in the directives list won't work, but you can still have access to the parent component by having it injected in the constructor of the child directive:
constructor(@Host(Application) application: Application) {
}
And the parent component can get a live list of child components using @Query:
constructor(@Query(EditView) editViews: QueryList<EditView>){
}
A: I've solved problem using DynamicComponentLoader.
See https://groups.google.com/forum/#!topic/angular/tDU5sw1vBwc
| |
doc_23532673
|
Is there a way to hide the variables in the url.
for example the url get shown as
http://localhost/try.php?js_var=123abc
Is there a way to change the code to print
http://localhost/try.php
the javascript and html
<html>
<head>
</head>
<body>
<a href="#" id="link">Click me!</a>
<script>
var js_var = "123abc";
document.getElementById("link").onclick = function (e)
{
window.location = "try.php?js_var=" + js_var;
}
</script>
</body>
</html>
try.php
<?php
if (isset($_GET['js_var'])) $php_var = $_GET['js_var'];
else $php_var = "<br />js_var is not set!";
echo $php_var;
?>
A: I think there is no way of hiding the variables, but you could use POST method and form tag. Some info on GET vs POST - http://www.w3schools.com/TAGS/ref_httpmethods.asp
| |
doc_23532674
|
#include "stdafx.h"
#include "sl/camera.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
using namespace sl;
cv::Mat zed_to_ocv(sl::Mat zed_mat) {
int cv_type = -1;
switch (zed_mat.getDataType()) {
case MAT_TYPE_32F_C1: cv_type = CV_32FC1; break;
case MAT_TYPE_32F_C2: cv_type = CV_32FC2; break;
case MAT_TYPE_32F_C3: cv_type = CV_32FC3; break;
case MAT_TYPE_32F_C4: cv_type = CV_32FC4; break;
case MAT_TYPE_8U_C1: cv_type = CV_8UC1; break;
case MAT_TYPE_8U_C2: cv_type = CV_8UC2; break;
case MAT_TYPE_8U_C3: cv_type = CV_8UC3; break;
case MAT_TYPE_8U_C4: cv_type = CV_8UC4; break;
default: break;
}
return cv::Mat(zed_mat.getHeight(), zed_mat.getWidth(), cv_type, zed_mat.getPtr<sl::uchar1>(MEM_CPU));
}
int main(int argc, char **argv) {
InitParameters parameters;
parameters.depth_mode = DEPTH_MODE_PERFORMANCE;
parameters.coordinate_units = UNIT_METER;
parameters.camera_fps = 30;
if (argc > 1) {
parameters.svo_input_filename = argv[1];
}
sl::Camera zed;
ERROR_CODE err = zed.open(parameters);
if (err != SUCCESS) {
zed.close();
cout << "Error while opening ZED camera";
return -1;
}
RuntimeParameters runtime_parameters;
runtime_parameters.sensing_mode = SENSING_MODE_STANDARD;
Resolution image_size = zed.getResolution();
int new_width = image_size.width;
int new_height = image_size.height;
sl::Mat image_zed(new_width, new_height, MAT_TYPE_8U_C4);
cv::Mat image_ocv = zed_to_ocv(image_zed);
cv::Mat image(new_width, new_height, CV_8UC1);
while (true) {
if (zed.grab(runtime_parameters) == SUCCESS) {
zed.retrieveImage(image_zed, VIEW_LEFT, MEM_CPU, new_width, new_height);
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
imshow("camera", image);
waitKey(30);
}
}
zed.close();
return 0;
}
This code works just fine, but if I wanted to use 32F matrices instead (changing the type of both image_zed and image) I get a
Exception in correspondence of 0x00007FF97D175400 (opencv_imgproc340d.dll) in projectCV.exe: 0xC0000005: access violation error reading 0x000002C52DC13040.
error. I tried changing to
getPtr<sl::float1>
inside zed_to_ocv, but the error is still there.
EDIT: Debugging I found out the crash happens at line
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
but I still can't figure out why.
What is the problem here? Thanks.
| |
doc_23532675
|
private static final Collection<? extends GrantedAuthority> USER_ROLES = ImmutableSet.of((GrantedAuthority)ROLE_ADMIN);
private static final Collection<? extends GrantedAuthority> CUSTOM_GROUPS = AuthorityUtils.commaSeparatedStringToAuthorityList("SOME_GROUP");
In test I have the following mocking condition:
when(mapper.mapAuthorities(CUSTOM_GROUPS)).thenReturn(USER_ROLES);
Mapper in this case it is class that implements GrantedAuthoritiesMapper spring interface that require to implement this method:
Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities);
When I tried to perform this mocking condition I get compilation error:
The method thenReturn(Collection<capture#2-of ? extends GrantedAuthority>) in the type OngoingStubbing<Collection<capture#2-of ? extends GrantedAuthority>> is not applicable for the arguments (Collection<capture#3-of ? extends GrantedAuthority>)
I can fix it just overrite this condition with this one :
when(customGroupsMapper.mapAuthorities(CUSTOM_GROUPS)).thenReturn((Collection)USER_ROLES);
But actually I don't like warning message that will be appeared: Collection is a raw type. References to generic type Collection<E> should be parameterized.
Could someone explain why it's happening and why mockito couldn't match the same types? Are any alternative ways to fix such issue?
A: Unfortunately this has nothing to do with Mockito, but with way Java handles generics, i.e. with erasure.
What I recommend is to use a simple factory method :
when(mapper.mapAuthorities(GROUP)).thenReturn(authorities(ROLE1, ROLE2));
@SuppressWarnings("unchecked")
private <T> ImmutableSet<T> authorities(GrantedAuthority... authorities) {
return (ImmutableSet<T>) ImmutableSet.copyOf(authorities);
}
| |
doc_23532676
|
I am having an issue when passing the image to the canvas. It does not set the image using a relative position. The images will explain much better than I can.
Before Fill:
After Fill:
The image bitmap is written relative to the window and overlaps the toolbar. I am wondering how I can prevent this from happening. Attached is the relevant code from my Fill class.
public override void OnMouseDown(CCDrawingCanvas canvas, System.Windows.Input.MouseButtonEventArgs e) {
double dpi = 96d;
// Get the size of the canvas
System.Windows.Size size = new System.Windows.Size((int)canvas.ActualWidth, (int)canvas.ActualHeight);
// Measure and arrange the surface
canvas.Measure(size);
canvas.Arrange(new Rect(size));
RenderTargetBitmap source = new RenderTargetBitmap(
(int)canvas.ActualWidth,
(int)canvas.ActualHeight,
dpi,
dpi,
PixelFormats.Pbgra32);
source.Render(canvas);
WriteableBitmap modifiedImage = new WriteableBitmap(source);
int h = modifiedImage.PixelHeight;
int w = modifiedImage.PixelWidth;
int[] pixelData = new int[h * w];
int widthInByte = modifiedImage.PixelWidth * (modifiedImage.Format.BitsPerPixel / 8);
modifiedImage.CopyPixels(pixelData, widthInByte, 0);
int oldColor = BitConverter.ToInt32(new byte[] { System.Drawing.Color.White.B, System.Drawing.Color.White.G, System.Drawing.Color.White.R, System.Drawing.Color.White.A }, 0);
int newColor = BitConverter.ToInt32(new byte[] { System.Drawing.Color.Black.B, System.Drawing.Color.Black.G, System.Drawing.Color.Black.R, System.Drawing.Color.Black.A }, 0);
// Perform the recursive fill
FloodFill(pixelData, (int)p.X, (int)p.Y, w, h, oldColor, newColor);
modifiedImage.WritePixels(new Int32Rect(0, 0, w, h), pixelData, widthInByte, 0);
newFill = new GraphicsFill(modifiedImage);
// Adds newFill to canvas.GraphicsList
AddObject(canvas, newFill);
}
XAML Code:
<Window x:Class="ccGui.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:effects="clr-namespace:System.Windows.Media.Effects;assembly=presentationcore"
xmlns:lib="clr-namespace:ccDrawingLib;assembly=ccDrawingLib"
xmlns:local="clr-namespace:ccGui"
Title="MainWindow" Height="600" Width="800">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="New" Command="ApplicationCommands.New" />
<MenuItem Header="Open" Command="ApplicationCommands.Open" />
<MenuItem Header="Save" Command="ApplicationCommands.Save" />
<MenuItem Header="Save As" Command="ApplicationCommands.SaveAs" />
<MenuItem Header="Close" Command="ApplicationCommands.Close" />
</MenuItem>
<MenuItem Header="Tool" Name="menuTools">
<MenuItem Header="Brush" Name="ccToolBrush" Tag="Brush" />
<MenuItem Header="Fill" Name="ccToolFill" Tag="Fill" />
</MenuItem>
</Menu>
<lib:CCDrawingCanvas x:Name="canvas" Background="White" />
</DockPanel>
</Window>
A: In WPF, practically all UI controls extend the Visual class. You can use that Visual reference to pass to the RenderTargetBitmap.Render Method to easily save an image of that UI control. It seems to me that you shouldn't need to keep switching between the Shapes and BitMapImages to fill your Shapes. I guess that you're using a Path when drawing shapes. If this is true, then you can just use the Path.Fill property to fill it in without having to do any manual calculations.
Furthermore, if you set the Panel.Zindex Attached Property on each new drawn shape and use the next higher Zindex value each time, then the latest shapes will always sit on top of the lower ones, just as in a drawing standard program. You could even enable the users to switch the shape layers of their drawn picture using this property.
| |
doc_23532677
|
public AbstractModel newInstance(Class<? extends AbstractModel> clazz){
return injector.getInstance(clazz);
}
Currently i have to do this:
Person person = (Person) em.newInstance(Person.class);
I'm wondering if i can use generics to remove the casting that i have to do to make the AbstractModel object a Person. Ideally just this:
Person person = em.newInstance(Person.class);
I don't know if this is possible since i'm not passing in a Person object to the method though.
A: You can change the method signature to following -
public <T extends AstractModel> T newInstance(Class<T> clazz) {
| |
doc_23532678
|
/generated/source/apollo/generatedIR/main/src/main/graphql/client/backend/MainAPI.json. But the generateApolloClasses is failing with:
> java.io.FileNotFoundException: /Users/mctigg/Documents/Repositories/generated/source/apollo/generatedIR/main (Is a directory)
So it is looking into the wrong path! This is my gradle config:
apollo {
nullableValueType = "javaOptional"
outputPackageName = "generated.client.backend"
}
task generateBackendSchemaJson(type: ApolloSchemaIntrospectionTask) {
url = 'src/main/graphql/client/backend/schema.graphqls'
output = 'src/main/graphql/client/backend/schema.json'
}
tasks.findByName('generateMainApolloIR').dependsOn(['generateBackendSchemaJson'])
So how can I configure generateApolloClasses to look into:
/generated/source/apollo/generatedIR/main/src/main/graphql/client/backend/
Instead of
/generated/source/apollo/generatedIR/main/
A: May be you should set schema file path as follows:
apollo {
schemaFilePath = "/generated/source/apollo/generatedIR/main/src/main/graphql/client/backend/schema.json"
nullableValueType = "javaOptional"
outputPackageName = "generated.client.backend"
}
| |
doc_23532679
|
When I try to schedule it through oozie shell action, the action fails with error:
./../[other directory]/x1.sh not found, no such file or directory
I can't change the shell script.
It's working with absolute path but not relative path. Can oozie take relative paths? If oozie can what should I do so that it takes relative paths?
| |
doc_23532680
|
The detail error message : "c1xx : fatal error C1023: 'projectname.pch' : unexpected error with pch, try rebuilding the pch"
Here's some meet the same problem :
Fatal Error C1023
He fixed the problem by removing the /Zm compiler option. But I have to use that option because my PCH file is too large.
Here is another solution.
I tryed, but it doesn't work. After that change, the difference is that the same error will appear lot of times during one build.
and here "Visual C++ Precompiled Header Errors on Windows 7", seems like it is the same reason as mine, but there's no patch for visual studio 2005.
So, I need your help, I can't fix it by myself.
Thanks !
| |
doc_23532681
|
A: I don't think there's a way to use String's ToLower() method from a non-string value without some sort of ToString() approach.
If it's a syntatical issue, you could make it an extension method:
public static string ToLowerString(this YourEnum enumValue) => enumValue.ToString().ToLower();
And call it like:
YourEnum.SomeEnumValue.ToLowerString();
EDIT.
Since the OP said that he/she was trying to avoid overhead, I'm guessing the Dictionary approach suggested by Theodor (Dictionary<YourEnum, string>) is a much better solution.
A: You could build a lookup dictionary, initialize it once at startup (or the first time it's needed), and use this to obtain the lowercase values:
public static Dictionary<TEnum, string> BuildEnumToStringMapping<TEnum>()
where TEnum: struct
{
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException("TEnum is not an enum.");
}
return Enum.GetValues(typeof(TEnum))
.OfType<TEnum>()
.ToDictionary(e => e, e => e.ToString().ToLower());
}
Usage:
var lookup = BuildEnumToStringMapping<MyEnum>();
Console.WriteLine(lookup[MyEnum.Value]);
Try it online
A: There are no many ways of achieving this as you do not want two strings (It will void possibility to use ToString().ToLower()).
I would suggest to use DescriptionAttribute from the namespace System.ComponentModel.
Add DescriptionAttribute to each member of the enumeration.
public enum Items
{
[Description("item1")]
Item1 = 1,
[Description("item2")]
Item2 = 2,
}
Then use Reflection to get friendly lowercase name when required.
public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return en.ToString();
}
Reference: check this for more details.
| |
doc_23532682
|
new THREE.MeshPhongMaterial({ color: 0xff1493 }))
sphere2.position.set(-20, .2, 20)
sphere2.castShadow = true
sphere2.receiveShadow = true
scene.add(sphere2)
const sphere2BB = new THREE.Sphere(sphere2.position,1);
sphere2.geometry.computeBoundingSphere();
sphere2BB.copy(sphere2.geometry.boundingSphere).applyMatrix4(sphere2.matrixWorld);
The error is coming from part of the last line "sphere2.geometry.boundingSphere" =>
Argument of type 'Sphere | null' is not assignable to parameter of type 'Sphere'.
Type 'null' is not assignable to type 'Sphere'.ts
I think this has something to do with typescript but I am not sure
| |
doc_23532683
|
The link of my example is at the bottom but my main concern is this part:
eventClick: function(event){
$(".closon").click(function() {
$('#calendar').fullCalendar('removeEvents',event._id);
});
},
I want to delete an event from the calendar with my close button and not on direct click of the event. I already tried using the $element.click outside of the eventClick trigger but it closed all the events on the calendar and the max i could reach was this poor situation, where the user need to click first on the calendar event and after on the 'X' to delete it.
http://jsfiddle.net/59RCB/49/
A: Remove the eventClick function and replace the eventAfterAllRender function with this:
eventRender: function(event, element) {
element.append( "<span class='closeon'>X</span>" );
element.find(".closeon").click(function() {
$('#calendar').fullCalendar('removeEvents',event._id);
});
}
A: The way i found:
//HTML Code to add the button
<div id='calendar'></div>
<button id='Delete'>Delete Events</button></p>
-
//Our Js data
{id: '1', resourceId: 'a' , start: '2015-10-16T10:52:07', end: '2015-10-16T21:00:00', url: 'https//www.google.com', title: 'How to delete Events'},
{id: '2', resourceId: 'b' , start: '2015-10-16T11:00:10', end: '2015-10-18T17:03:00', title : 'Can we delete multiple events ?'},
{id: '2', resourceId: 'c' , start: '2015-10-16T10:00:00', end: '2015-10-16T23:00:02', title : 'How ?'},
],
//Need to set our button
select: function(start, end, jsEvent, view, resource) {
console.log(
'select callback',
start.format(),
end.format(),
resource ? resource.id : '(no resource)'
);
}
});
//Our button to delete Events
$('#Delete').on('click', function() {
$('#calendar').fullCalendar('removeEvents', 2); //Remove events with the id: 2
});
});
A: This code may better help you. In this code remove icon display you whenever your mouse moving over event and whenever your mouse goes outside remove button will hide or removed.
eventMouseover:function(event,domEvent,view){
var el=$(this);
var layer='<div id="events-layer" class="fc-transparent"><span id="delbut'+event.id+'" class="btn btn-default trash btn-xs">Trash</span></div>';
el.append(layer);
el.find(".fc-bg").css("pointer-events","none");
$("#delbut"+event.id).click(function(){
calendar.fullCalendar('removeEvents', event._id);
});
},
eventMouseout:function(event){
$("#events-layer").remove();
}
A: Above solution works perfectly on the month view, but if you are on weekview and dayview, this solution will not work as pointed out by nextdoordoc above.
Why? In weekview their is div element with ".fc-bg" as css class which is overlay with 25% opacity which blocks click event.
Workarround:
eventRender: function(event, element) {
element.find(".fc-bg").css("pointer-events","none");
element.append("<div style='position:absolute;bottom:0px;right:0px' ><button type='button' id='btnDeleteEvent' class='btn btn-block btn-primary btn-flat'>X</button></div>" );
element.find("#btnDeleteEvent").click(function(){
$('#calendar').fullCalendar('removeEvents',event._id);
});
Adding pointer-events:none allows click event propagation.
Note: This solution does not work in IE10 and older.
To work in IE10 you can directly append you delete button to (".fc-bg")
here is example:
eventRender: function(event, element) {
element.find(".fc-bg").append("<div style='position:absolute;bottom:0px;right:0px' ><button type='button' id='btnDeleteEvent' class='btn btn-block btn-primary btn-flat'>X</button></div>" );}
Hope to help someone
A: this will works for Month ,Week ,Day views
eventRender: function (event, element, view) {
if (view.name == 'listDay') {
element.find(".fc-list-item-time").append("<span class='closeon'>X</span>");
} else {
element.find(".fc-content").prepend("<span class='closeon'>X</span>");
}
element.find(".closeon").on('click', function () {
$('#calendar').fullCalendar('removeEvents', event._id);
});
| |
doc_23532684
|
Possible Duplicate:
Starting an exe on the server
I want to ftp an exe on the server and any asp.net webpage or a php page that will ultimately run the exe on being called. The exe will install an application on the server and start running and occupy a port on the server to listen to some clients.
Is it possible without making any change to the server's configuration?
If possible, is it secure?
A: http://uk.php.net/manual/en/function.exec.php
If you want to leave this URL public without any security layer then it's not secure obviously.
A: You can use the exec() function to run a .exe file on the server:
<?php
exec("file.exe");
?>
A: A. I want to ftp an exe on the serve
Yes it possible you can use exec or system
B. Secured ?? depending on where you get your arguments from .. but using escapeshellarg or escapeshellcmd will help reduce the risk
| |
doc_23532685
|
I would like to view the files on my mobile.
Where can I save video mp4 files and how to save?
I'm saving with filename.save(path) and I can see the files in directory.
I also can see the xfile in the directory returned from stopvideo.
I can see the files by printing the folders
but I can not see in browser + enable hidden files.
///init
appDirectory = await getApplicationDocumentsDirectory();
videoDirectory = '${appDirectory.path}';
await Directory(videoDirectory).create(recursive: true);
final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
filePath = '$videoDirectory/${currentTime}.mp4';
///code
videoFile = await controller.stopVideoRecording();
print ("XXXX videoFile-"+videoFile.path);
print (Directory("/data/user/0/com.flutter_app_camera1/cache").listSync());
print (Directory("/data/user/0/com.flutter_app_camera1/cache").listSync().length.toString());
await videoFile.saveTo(filePath);
print ("(XXXX filePath-"+filePath);
print (Directory(videoDirectory).listSync());
print (Directory(videoDirectory).listSync().length.toString());
///Prints
I/flutter (20330): XXXX videoFile-/data/user/0/com.flutter_app_camera1/cache/REC3520996093112925184.mp4
I/flutter (20330): [File: '/data/user/0/com.flutter_app_camera1/cache/REC3520996093112925184.mp4']
I/flutter (20330): 1
I/flutter (20330): (XXXX filePath-/data/user/0/com.flutter_app_camera1/app_flutter/1618663350463.mp4
I/flutter (20330): [Directory: '/data/user/0/com.flutter_app_camera1/app_flutter/flutter_assets', File: '/data/user/0/com.flutter_app_camera1/app_flutter/res_timestamp-1-1618663045614', File: '/data/user/0/com.flutter_app_camera1/app_flutter/1618663350463.mp4']
I/flutter (20330): 3
A: If would like to view the files on your mobile, you can use this gallery_saver plugin to save your video file in Gallery.
final video = await controller.stopVideoRecording();
await GallerySaver.saveVideo(video.path);
| |
doc_23532686
|
Process p = Runtime.getRuntime().exec("/bin/sh -c \"mkfifo ~/myFifo && tail -f ~/myFifo | csh -s\"");
But when I look for ~/myFifo after the call, it is not there. Is there any reason this would not work?
I also tried without the /bin/sh -c bit, but it didn't work either.
EDIT
final String [] cmds = {"/bin/sh", "-c", "\"mkfifo ~/myFifo && tail -f ~/myFifo | csh -s\""};
Process p = Runtime.getRuntime().exec(cmds);
A: If you write out the third argument, you'll get this:
"mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"
And if you try to run that in a shell, you'll see that it doesn't work:
$ "mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"
bash: mkfifo ~/myFifo && tail -f ~/myFifo | csh -s: No such file or directory
Just remove the literal quotes you added:
final String [] cmds = {"/bin/sh", "-c", "mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"};
and remember to read from the Process.getInputStream().
| |
doc_23532687
|
SwiftUI create image slider with dots as indicators
Now I need to open the detail view on clicking the image in the slideshow. But now when I try to move the images the detail view is opening and could not move the images as in Pageview. I implemented the below code. Please let me know the solution to fix this. Thanks in advance.
PagingView(index: $index.animation(), maxIndex: images.count - 1){
ForEach(articles, id: \.self) { article in
NavigationLink(destination: ArticleDetailUIView(article: articles[self.index], isBookmark: false) , isActive: $areYouGoingToArticleView)
{
Image(article.image)
.resizable()
.scaledToFill()
.accessibility(identifier: "articleImage")
}
}
}
.aspectRatio(4/3, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 15))
A: After few browsing, the workaround was using the stepper to move around the slide show instead of scrolling the images. I added the below lines.
Stepper("Index: (index)", value: $index.animation(.easeInOut), in: 0...images.count-1)
.font(Font.body.monospacedDigit())
.labelsHidden()
| |
doc_23532688
|
The data in this table is coming mainly from a table “tblPatient” but the last entry in this table i.e. “AppointmentDate” is coming from another table but to get this single entry I have to linq my query with three tables i.e.
tblPatient
tblPatientBill & tblPatientAppointment.
For this I have written this query in my controller
public ActionResult PrintPartialViewToPdf(int id)
{
List<tblPatientAppointment> tblappointments = db.tblPatientAppointments.ToList();
List<tblPatientBill> tblbill = db.tblPatientBills.Where(x=>x.ID == id && x.is_active == true).ToList();
List<tblPatient> tblpatient = db.tblPatients.ToList();
var result = (from p in tblbill
join o in tblappointments on p.PatientAppointmentID equals o.ID
join c in tblpatient on o.patient_id equals c.Patient_id
select new
{
c.Patient_Name,
c.Patient_address,
c.Contact_no,
c.Age,
c.Gender,
c.Date_of_Birth,
o.AppointmentDate,
}).ToList();
var report = new PartialViewAsPdf("~/Views/Shared/PatientBillToPDF.cshtml", result);
return report;
}
In my view when I want to display the result in the view here is my code for it.
PatientBillToPDF.cshtml
@model IEnumerable<HMS.Models.tblPatient>
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<style>
.bottom {
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="container-fluid">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="block-header">
<h3>Patient's Personal Detail</h3>
</div>
<div class="card">
<div class="body table-responsive">
<table class="table table-bordered table-striped table-hover js-basic-example dataTable" style="width:100%">
@foreach (var item in Model)
{
<tr>
<th>@Html.DisplayNameFor(model => model.Patient_Name)</th>
<td>@Html.DisplayFor(model => item.Patient_Name)</td>
</tr>
<tr>
<th>@Html.DisplayNameFor(model => model.Patient_address)</th>
<td>@Html.DisplayFor(model => item.Patient_address)</td>
</tr>
<tr>
<th>@Html.DisplayNameFor(model => model.Contact_no)</th>
<td>@Html.DisplayFor(model => item.Contact_no)</td>
</tr>
<tr>
<th>@Html.DisplayNameFor(model => model.Age)</th>
<td>@Html.DisplayFor(model => item.Age)</td>
</tr>
<tr>
<th>@Html.DisplayNameFor(model => model.Gender)</th>
<td>@Html.DisplayFor(model => item.Gender)</td>
</tr>
<tr>
<th>@Html.DisplayNameFor(model => model.Date_of_Birth)</th>
<td>@Html.DisplayFor(model => item.Date_of_Birth)</td>
</tr>
<tr>
<th>@Html.DisplayNameFor(model => model.AppointmentDate)</th>
<td>@Html.DisplayFor(model => item.AppointmentDate)</td>
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
What I want to know:
Please check whether my linq query is according to the requirement? And the 2nd thing is in my View I am not able to get Appointment Date as it is including the tblPatient model. How can I display data from two different tables for which the query is returning the result but I am not able to display it in view because they belong to two different models.Thanks
A:
How can I display data from two different tables for which the query is returning the result
You actually need to create a ViewModel here and strongly type your view with it. Your ViewModel would look like:
public class PatientAppointmentViewModel
{
public string PatientName { get;set; }
public string PatientAddress { get;set; }
public string ContactNo { get;set;}
......
......
public DateTime AppointmentDate { get;set;}
}
In the controller we need to populate the ViewModel :
var result = (from p in tblbill
join o in tblappointments on p.PatientAppointmentID equals o.ID
join c in tblpatient on o.patient_id equals c.Patient_id
select new PatientAppointmentViewModel
{
PatientName = c.Patient_Name,
PatientAddress = c.Patient_address,
......
......
AppointmentDate = o.AppointmentDate
}).ToList();
And the View would need to bind with the IEnumerable<PatientAppointmentViewModel>:
@model IEnumerable<HMS.Models.PatientAppointmentViewModel>
@{
Layout = null;
}
Please check whether my linq query is according to the requirement
Your queries might be correct but One important thing that you are loading all data in memory and then doing linq queries on it which will not work in production if the data is too large.
For example the following will load all patient appointments from db which is not correct:
List<tblPatientAppointment> tblappointments = db.tblPatientAppointments.ToList();
and same is the case with other two lines after this one.
You should directly use context object in the linq query so that it only loads those rows in memory that match the query criteria like:
var result = (from p in db.tblPatientBills
join o in db.tblPatientAppointmentson p.PatientAppointmentID equals o.ID
join c in db.tblPatients on o.patient_id equals c.Patient_id
where p.ID == id && p.is_active == true
select new PatientAppointmentViewModel
{
PatientName = c.Patient_Name,
PatientAddress = c.Patient_address,
......
......
AppointmentDate = o.AppointmentDate
}).ToList();
A: Your code seems incorrect when you displaying the Appointment date.
<tr>
<th>@Html.DisplayNameFor(model => model.AppointmentDate)</th>
<td>@Html.DisplayFor(model => item.Date_of_Birth)</td>
</tr>
The third line will display date of birth.
Change that to
<td>@Html.DisplayFor(model => model.AppointmentDate)</td>
To know if the query is efficient, you will have to explain what you are trying to do. Are you getting result for a single patient. Also i would not load the entire table in memory before running the query if i was you.
| |
doc_23532689
|
My query is:
$user = Users::all(); <- this displays me an error
But if I want to do it like every 25 rows:
$user = Users::paginate(25);
the thing is that if I add this piece of code as above it will not work because it will return me 25 rows only I wonder:
how can I make that it returns me 25 rows it finishes to process that 25 rows and then it restarts in a new 25 rows again?
Thanks
A: You're looking for either the chunk feature (which will process batches of records in chunks of a size you select) or the lazy feature (which will fetch one at a time).
You may still run into timeouts on the server side if this is a web request. If so, you may need to do this in an Artisan command, or split it up into queue jobs.
| |
doc_23532690
|
My js functions
var countCopies1;
var clone ;
function duplicate() {
var original = document.getElementById('duplicater1');
clone = original.cloneNode(true);
var countCopies = $('body').html().split('duplicater').length;
clone.id = "duplicater"+countCopies;
original.parentNode.appendChild(clone);
countCopies1 = countCopies;
}
My table with id duplicater1. When I duplicate it id changes to duplicater2, duplicater3 and so on, but my id customer, project, post, hours stay the same in new duplicated table. How can I change them & I need in duplicater2 id customer1, project1, post1, hours1.
I will be thankful if u help me!
<div id="duplicater1">
<br></br>
<table class="table table-bordered">
<thead>
<tr>
<th style="width:16%;text-align:center">{Customer}</th>
<th style="width:16%;text-align:center">{Project}</th>
<th style="width:16%;text-align:center">{Activity}</th>
<th style="width:16%;text-align:center">{Hours}</th>
<th style="width:16%;text-align:center">{Comment}</th>
<th style="width:5%"> </th>
</tr>
</thead>
<tbody>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="customer" class="form-control" onchange="getCustomerAddWork(this)">{CUSTOMERS}</select></div>
</td>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="project" class="form-control" onchange="getProjectAddWork(this)"></select></div>
</td>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="post" class="form-control"></select></div>
</td>
<td>
<div class="form-inline" style="text-align:center">
<div class="form-group">
<input type="number" class="form-control" id="hours" placeholder="{Hours}">
</div>
</div>
</td>
<td>
<div class="form-inline" style="margin-bottom:1em;text-align:center">
<div class="form-group">
<textarea class="form-control" id="comment" placeholder="{Comment}"></textarea>
</div>
</div>
</td>
<td>
<button type="button" class="btn btn-danger" style="width:70px"
onclick="Remove()">{Delete}</button>
</td>
</tbody>
</table>
</div>
</div>
<div class="container-fluid bg-2 text-center" style="margin-top:5em;margin-bottom:3em;">
<button type="button" class="btn btn-success" onclick="duplicate()">{Add}</button>
<button type="button" class="btn btn-info" onclick="AddWork()">{Submit}</button>
<button type="button" class="btn btn-primary" onclick="Redirect()">{Cancel}</button>
</div>
</form>
A: Since you have jQuery, I would do something like this:
var original = $("#duplicater1");
function duplicate() {
var countCopies = $("[id^='duplicater']").length + 1;
var cloned = original.clone();
var cloned.attr("id", "duplicater" + countCopies);
$(cloned).find("[id]").each(function(){
var current = $(this);
var currentId = current.attr("id");
var ids = $("[id='" + currentId + "']");
if(ids.length > 1 && ids[0]==this){
var newId = currentId.substring(0, currentId - 1);
current.attr("id", newId + countCopies);
}
});
original.parent().append(cloned);
}
A:
My table with id duplicater1. When I duplicate it id changes to
duplicater2, duplicater3 and so on, but my id customer, project, post,
hours stay the same in new duplicated table. How can I change them & I
need in duplicater2 id customer1, project1, post1, hours1.
Yes, as duplicate identifiers are not good markup you should indeed change them.
However, duplicate identifiers within unique identifiable containers are functionally not an issue (Though still should be changed).
To address your actual question, yes you can write a loop that goes through each element within the duplicator container and append a number to it and I'm sure there are answers showing you how to and they are perfectly fine.
I would however try to address the duplicate identifier issue in another way that doesn't require maintaining code to do this.
An approach I have been using in numerous web projects in those type of scenarios is to use data-id as an attribute to identify the containers and to allow you to group them as well as the elements inside.
Note, you can use classes or data-xxx or what ever takes your fancy, I personally just prefer data-id for these cases
Instead of using <div id="duplicater1/2/3"> just use <div data-id="duplicater"> to identify the "type" of component/form you are working with.
Inside, do the same with each element, such as <select data-id="customer"> or <select data-id="project">
This solves the cloning problem all together as you can now clone each
duplicator without the need to rename anything at all and you don't
need to maintain custom code renaming element identifiers
In regards to the bound events, you don't have to worry about them either as each element when it raises an event such as getProjectAddWork(this) is already within context.
Say you trigger the getProjectAddWork(this) event and need to get to your duplicator container your are in, you can simple do something similar to $(this).closest('[data-id="duplicator"]'); or to get to the outer form $(this).closest('form'); etc..
Sure, you can achieve the same by only renaming the duplicator id as you already do and then do $(this).closest('#duplicator'); but in my humble opinion I rather prevent duplicate identifiers and not having to maintain code to rename identifiers as well as base selectors on contextual awareness within their respective "component"
I use jQuery as you tagged your question with it but you can do the same with just plain JavaScript
| |
doc_23532691
|
Servers are IIS6 web servers
I have root which have App_Data folder (network has full persmisions on that) .
I have FiftyOne.Foundation.dll on bin folder, downloaded from https://51degrees.codeplex.com/releases/view/133106
I have 51Degrees.config (above part of it) on root of my site
<configSections>
<sectionGroup name="fiftyOne">
<section name="log" type="FiftyOne.Foundation.Mobile.Configuration.LogSection, FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere" restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
<section name="redirect" type="FiftyOne.Foundation.Mobile.Configuration.RedirectSection, FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere" restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
<section name="detection" type="FiftyOne.Foundation.Mobile.Detection.Configuration.DetectionSection, FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere" restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
<section name="imageOptimisation" type="FiftyOne.Foundation.Mobile.Configuration.ImageOptimisationSection, FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere" restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
</sectionGroup>
</configSections>
<fiftyOne>
<log logFile="~/App_Data/Log.txt" logLevel="Debug"/>
<detection binaryFilePath="~/App_Data/51Degrees-Premium.dat"/>
<imageOptimisation enabled="false" maxWidth="1000" maxHeight="1000" widthParam="width" heightParam="height" factor="1" />
web-config has this:
<httpModules>
<add name="Detector" type="FiftyOne.Foundation.Mobile.Detection.DetectorModule, FiftyOne.Foundation"/>
</httpModules>
I have lic file on bin folder which has my lisence file on it.
The problem is that I can not get anything to error log (log.txt) the file does not even exists. I can not get 51Degrees-Premium.dat downloaded to app_data directory.
I have another site on same server (much higher volume of users), which has identical settings to this one and that site is donwnloadin new dat file and making log-file.
Where do I go wrong with this?
The working one has log like this:
2014-10-29T10:39:26.1560896Z - 6392 - Debug - Initialising redirection module
2014-10-29T10:39:57.0154646Z - 3012 - Debug - Disposing Redirection Module
2014-10-29T10:39:57.2967146Z - 3012 - Debug - Disposing Detector Module
2014-10-29T10:39:59.8904646Z - 6392 - Debug - Disposing Redirection Module
2014-10-29T10:39:59.8904646Z - 6392 - Debug - Disposing Detector Module
2014-10-29T10:40:07.4373396Z - 3012 - Debug - Bandwidth monitoring 'False'
2014-10-29T10:40:07.4373396Z - 3012 - Debug - Image Optimisation 'False'
2014-10-29T10:40:07.4373396Z - 3012 - Debug - Profile Override 'False'
2014-10-29T10:40:07.4373396Z - 3012 - Debug - Initialising redirection module
2014-10-29T10:41:27.0184008Z - 3012 - Debug - Disposing Redirection Module
2014-10-29T10:41:27.2996526Z - 3012 - Debug - Disposing Detector Module
2014-10-29T10:43:49.0965464Z - 3012 - Debug - Could not write device information to URL 'http://devices.51degrees.mobi/new.ashx'. Exception 'The request was aborted: The operation has timed out.'
2014-10-29T10:45:37.5685412Z - 3012 - Debug - Bandwidth monitoring 'False'
2014-10-29T10:45:37.5685412Z - 3012 - Debug - Image Optimisation 'False'
2014-10-29T10:45:37.5685412Z - 3012 - Debug - Profile Override 'False'
2014-10-29T10:45:37.5685412Z - 3012 - Debug - Initialising redirection module
2014-10-29T10:45:37.6154162Z - 3012 - Debug - Bandwidth monitoring 'False'
2014-10-29T10:45:37.6154162Z - 3012 - Debug - Image Optimisation 'False'
2014-10-29T10:45:37.6154162Z - 3012 - Debug - Profile Override 'False'
2014-10-29T10:45:37.6154162Z - 3012 - Debug - Initialising redirection module
But even ths working one is working kind of odd. if I make this:
Request.Browser("IsMobile") It returns only empty value, not true or false
What is going wrong and how to fix this?
| |
doc_23532692
|
*
*I have 1000's of objects like below
{id:1,value:"value1"} . . {id:1000,value:"value1000"}
*I want to access above objects by id
*I want to clean the objects Lesser than certain id every few minutes (Because it generates 1000's of objects every second for my high frequency algorithm)
I can clean easily by using this.
myArray = myArray.filter(function( obj ) {
return obj.id > cleanSize;
});
I can find the object by id using
myArray.find(x => x.id === '45');
Problem is here , I feel that find is little slower when there is larger sets of data.So I created some objects of object like below
const id = 22;
myArray["x" + id] = {};
myArray["x" + id] = { id: id, value:"test" };
so I can access my item by id easily by myArray[x22]; , but problem is i am not able find the way to remove older items by id.
someone guide me better way to achieve the three points I mentioned above using arrays or objects.
A: The trouble with your question is, you're asking for a way to finish an algorithm that is supposed to solve a problem of yours, but I think there's something fundamentally wrong with the problem to begin with :)
If you store a sizeable amount of data records, each associated with an ID, and allow your code to access them freely, then you cannot have another part of your code dump some of them to the bin out of the blue (say, from within some timer callback) just because they are becoming "too old". You must be sure nobody is still working on them (and will ever need to) before deleting any of them.
If you don't explicitly synchronize the creation and deletion of your records, you might end up with a code that happens to work (because your objects happen to be processed quickly enough never to be deleted too early), but will be likely to break anytime (if your processing time increases and your data becomes "too old" before being fully processed).
This is especially true in the context of a browser. Your code is supposed to run on any computer connected to the Internet, which could have dozens of reasons to be running 10 or 100 times slower than the machine you test your code on. So making assumptions about the processing time of thousands of records is asking for serious trouble.
Without further specification, it seems to me answering your question would be like helping you finish a gun that would only allow you to shoot yourself in the foot :)
All this being said, any JavaScript object inherently does exactly what you ask for, provided you're okay with using strings for IDs, since an object property name can also be used as an index in an associative array.
var associative_array = {}
var bob = { id:1456, name:"Bob" }
var ted = { id:2375, name:"Ted" }
// store some data with arbitrary ids
associative_array[bob.id] = bob
associative_array[ted.id] = ted
console.log(JSON.stringify(associative_array)) // Bob and Ted
// access data by id
var some_guy = associative_array[2375] // index will be converted to string anyway
console.log(JSON.stringify(some_guy)) // Ted
var some_other_guy = associative_array["1456"]
console.log(JSON.stringify(some_other_guy)) // Bob
var some_AWOL_guy = associative_array[9999]
console.log(JSON.stringify(some_AWOL_guy)) // undefined
// delete data by id
delete associative_array[bob.id] // so long, Bob
console.log(JSON.stringify(associative_array)) // only Ted left
Though I doubt speed will really be an issue, this mechanism is about as fast as you will ever get JavaScript to run, since the underlying data structure is a hash table, theoretically O(1).
Anything involving array methods like find() or filter() will run in at least O(n).
Besides, each invocation of filter() would waste memory and CPU recreating the array to no avail.
| |
doc_23532693
|
for(;;){
//something
}
There's an example of this here.
Can anyone elaborate as to what using ";;" within a for loop does? I can't seem to understand it.
A: Its a simple infinite loop syntax, a complete code looks like this
for(<initialize>; <condition>; <increment/decrement>) {
<body>
}
Those I labelled with '< .. >' are optional.
| |
doc_23532694
|
Is there a setting that populates a date when it's NULL?
A: There's either
*
*a DEFAULT value applied to that column, or
*a database trigger that does it.
This is how the first works:
SQL> create table test
2 (clock_in1 date,
3 clock_out1 date default sysdate
4 );
Table created.
SQL> insert into test (clock_in1) values (date '2020-08-23');
1 row created.
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';
Session altered.
SQL> select sysdate from dual;
SYSDATE
-------------------
03.11.2020 20:23:03
SQL> select * from test;
CLOCK_IN1 CLOCK_OUT1
------------------- -------------------
23.08.2020 00:00:00 03.11.2020 20:22:48
SQL>
And this is the second:
SQL> drop table test;
Table dropped.
SQL> create table test
2 (clock_in1 date,
3 clock_out1 date
4 );
Table created.
SQL> create or replace trigger trg_bi_test
2 before insert on test
3 for each row
4 begin
5 :new.clock_out1 := nvl(:new.clock_out1, sysdate);
6 end;
7 /
Trigger created.
SQL> insert into test (clock_in1) values (date '2020-08-23');
1 row created.
SQL> select * from test;
CLOCK_IN1 CLOCK_OUT1
------------------- -------------------
23.08.2020 00:00:00 03.11.2020 20:24:23
SQL>
How to "fix" it?
SQL> alter table test modify clock_out1 default null;
Table altered.
SQL>
As of the trigger, well ... it depends on what it is doing, but - removing a line that sets column value would do.
| |
doc_23532695
|
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('register/', views.register, name='register'),
path('usearch/', views.usearch, name='usearch'),
path('usearch/<str:query>', views.usearch_query, name='usearch_query'
]
views.py
def usearch(request):
return render(request, 'myapp/usearch.html')
def usearch_query(request, query):
context = {'query': query}
print(query) # Testing the search result
return render(request, 'myapp/usearch_query.html'}
usearch.html
<form method="GET" action="{% url 'usearch_query' %}
<input type="search" placeholder="Search here...">
<button type="submit"> Search </button>
</form>
usearch_query.html
{{ query }}
I essentially want the user to search something, have it navigate to usearch/<search_parameter> and process the search in the usearch_query function so I can do some computations with it.
| |
doc_23532696
|
Here is my Toggle code which works correctly:
<script type="text/javascript" >
$(function() {
$('#menuButton').toggle(function() {
$('#menuArea').slideDown();
}, function() {
$('#menuArea').slideUp();
});
return false;
});
</script>
And here is the No Toggle which hides again:
<script type="text/javascript" >
$(function() {
$('#menuButton').click(function() {
$('#menuArea').slideDown("fast");
});
return false;
});
</script>
Any ideas why this is?
| |
doc_23532697
|
After running python manage.py I get error relation does not exist. I am using Django version 1.11.11. I think that there no need to be an error with database, because when I downgrade Django version to 1.8.1, there is no errors and migration is successful. What might be the problem?
Traceback (most recent call last):
File "C:\Vizia_project\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "qa_qagroup" does not exist
LINE 1: SELECT (1) AS "a" FROM "qa_qagroup" LIMIT 1
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 12, in <module>
execute_from_command_line(sys.argv)
File "C:\Vizia_project\env\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line
utility.execute()
File "C:\Vizia_project\env\lib\site-packages\django\core\management\__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 327, in execute
self.check()
File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Vizia_project\env\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_checks
issues.extend(super(Command, self)._run_checks(**kwargs))
File "C:\Vizia_project\env\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Vizia_project\env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Vizia_project\env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Vizia_project\env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Vizia_project\env\lib\site-packages\django\urls\resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "C:\Vizia_project\env\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Vizia_project\env\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Vizia_project\env\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Vizia_project\env\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Vizia_project\env\lib\importlib\__init__.py", line 104, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2231, in _gcd_import
File "<frozen importlib._bootstrap>", line 2214, in _find_and_load
File "<frozen importlib._bootstrap>", line 2203, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1448, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "C:\Vizia_project\banknote\urls.py", line 24, in <module>
from qa.views import *
File "C:\Vizia_project\qa\views.py", line 11, in <module>
class QAGroupFilter(django_filters.FilterSet):
File "C:\Vizia_project\qa\views.py", line 13, in QAGroupFilter
if QAGroup.objects.exists():
File "C:\Vizia_project\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Vizia_project\env\lib\site-packages\django\db\models\query.py", line 670, in exists
return self.query.has_results(using=self.db)
File "C:\Vizia_project\env\lib\site-packages\django\db\models\sql\query.py", line 517, in has_results
return compiler.has_results()
File "C:\Vizia_project\env\lib\site-packages\django\db\models\sql\compiler.py", line 858, in has_results
return bool(self.execute_sql(SINGLE))
File "C:\Vizia_project\env\lib\site-packages\django\db\models\sql\compiler.py", line 899, in execute_sql
raise original_exception
File "C:\Vizia_project\env\lib\site-packages\django\db\models\sql\compiler.py", line 889, in execute_sql
cursor.execute(sql, params)
File "C:\Vizia_project\env\lib\site-packages\django\db\backends\utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Vizia_project\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "C:\Vizia_project\env\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Vizia_project\env\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Vizia_project\env\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "qa_qagroup" does not exist
LINE 1: SELECT (1) AS "a" FROM "qa_qagroup" LIMIT 1
^
requirements.txt looks this:
beautifulsoup4==4.6.0
certifi==2017.7.27.1
chardet==3.0.4
Django==1.11.11
django-crispy-forms==1.7.1
django-filter==1.1.0
django-modelcluster==3.1
django-session-security==2.6.0
django-taggit==0.22.1
django-treebeard==4.1.2
djangorestframework==3.6.4
html5lib==0.999999999
idna==2.6
olefile==0.44
Pillow==4.3.0
psycopg2==2.7.3.2
python-dateutil==2.6.1
pytz==2017.2
raven==6.3.0
requests==2.18.4
six==1.11.0
Unidecode==0.4.21
urllib3==1.22
wagtail==1.12.2
webencodings==0.5.1
wheel==0.24.0
Willow==0.4
views.py from qa
from django.shortcuts import render
import django_filters
from qa.models import QAGroup
from qa.forms import QAForm
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
# Create your views here.
class QAGroupFilter(django_filters.FilterSet):
if QAGroup.objects.exists():
initial = QAGroup.objects.first().pk
else:
initial = None
group = django_filters.ModelChoiceFilter(
queryset=QAGroup.objects.order_by('pk'),
# widget=LinkWidget(),
label='',
empty_label=None,
name='title',
initial=initial,
)
def __init__(self, data=None, *args, **kwargs):
# filterset is bound, use initial values as defaults
if data is not None:
data = data.copy()
for name, f in self.base_filters.items():
initial = f.extra.get('initial')
# filter param is either missing or empty, use initial as default
if not data.get(name) and initial:
data[name] = initial
super(QAGroupFilter, self).__init__(data, *args, **kwargs)
class Meta:
model = QAGroup
fields = ['group', ]
def qa_list(request):
filter = QAGroupFilter(request.GET, queryset=QAGroup.objects.all())
groups = QAGroup.objects.order_by('pk')
form = QAForm()
if request.method == 'POST':
form = QAForm(request.POST)
if form.is_valid():
form.send_email()
messages.add_message(request, messages.INFO, _('Some text here'))
return redirect('faq')
return render(request, 'qa/qa.html', {'filter': filter, 'groups': groups, 'form': form})
A: This is a frequently asked question.
You have code at class level, so it runs on import - before the migrations can run. In your case the code is in QAGroupFilter, where you do QAGroup.objects.exists(). That code needs to be moved into a method.
A: Thank you every one for help. Solved! I just deleted QAGroup.objects.exists() if statement
| |
doc_23532698
|
Here is my dynamic generated grid.
@using System.Dynamic
@model List<System.Collections.IDictionary>
<link href="~/Content/grid.css" rel="stylesheet" />
@{
var result = new List<dynamic>();
foreach (var emprow in Model)
{
var row = (IDictionary<string, object>)new ExpandoObject();
var eachEmpRow = (Dictionary<string, object>)emprow;
foreach (KeyValuePair<string, object> keyValuePair in eachEmpRow)
{
row.Add(keyValuePair);
}
result.Add(row);
}
var grid = new WebGrid(result, rowsPerPage: 50);
}
@if (@Model != null)
{
@grid.GetHtml(
htmlAttributes: new { id = "grdHoteling" },
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All)
}
Any help please? Thanks in advance.
A: Something along these lines. There's also a property that will disable the sorting, but you can always register on the click event and cancel the default behavior. Afterwards you can decide where to go. You can also get the DOM element by using the this keyword inside the click event callback. It's useful if you want to store additional data- or just get other info about the header.
$(".webgrid-header").click(function(event){
event.preventDefault();
//navigate to your other site
});
| |
doc_23532699
|
I'm trying to update a "likes" field in the palettes collection in a Firestore doc with an onClick event and not having any luck.
I'm passing the name field (in this case "Testing") to my onClick handler to get the Firestore doc ref and then trying to update that doc's 'likes' field value by 1.
Here is my onClick handler:
const handleLike = name => {
// name is "Testing"
let palette = db.collection('palettes').doc(name)
palette.update({
likes: // what goes here??
})
}
How can I increment the likes field value for the given palette doc?
Maybe this is not the way to go about it but if I have lots of palette docs, I'd like to avoid having to read in the entire collection to update it each time.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.