_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d8101 | train | While you use areas, just add area="...." to nodes under them.
...
<mvcSiteMapNode title="Groups" route="AccessControl_default" area="AccessControl" controller="Personnel" action="Groups" key="groups"/>
... | unknown | |
d8102 | train | I ended up with this:
// This contains a white-list of allowed query parameters. This is useful to
// ensure people don't try to use &r=234234 to bust your caches.
def allowedParameters(params: String*): Directive0 = parameterSeq.flatMap {
case xs =>
val illegal = xs.collect {
case (k, _) if !params.contains(k) => k
}
if (illegal.nonEmpty)
reject(ValidationRejection("Illegal query parameters: " + illegal.mkString("", ", ", "\nAllowed ones are: ") + params.mkString(", ")))
else
pass
}
For usage, have a look at the unit tests:
val allowedRoute = {
allowedParameters("foo", "bar") {
complete("OK")
}
}
"Allowed Parameter Directive" should "reject parameters not in its whitelist" in {
Get("/?foo&bar&quux") ~> allowedRoute ~> check {
handled should equal(false)
rejection should be(ValidationRejection("Illegal query parameters: quux\nAllowed ones are: foo, bar"))
}
}
it should "allow properly sorted parameters through" in {
Get("/?bar&foo") ~> allowedRoute ~> check {
handled should equal(true)
responseAs[String] should equal("OK")
}
}
A: Actually, you have a good solution, i can only suggest a small refactoring:
def only(params: String*): Directive0 = {
def check: Map[String, String] => Boolean = _.keySet diff params.toSet isEmpty
parameterMap.require(check, rejection)
}
You can write it as a one-liner, but it would be just longer
A: With a route like this:
val myRoute = {
...
pathPrefix("test") {
parameter("good") {
good =>
complete("GOOD")
}
} ~
...
}
Spray will require first parameter to be good and to have value, i.e. ?good=value. No other parameters that have values are allowed. | unknown | |
d8103 | train | Plain Prolog is probably not the best choice here. Such problems are most easily modelled using 0/1 Integer Programming, and solved with an IP or Finite-Domain solver, which several enhanced Prologs provide. Here is a solution in ECLiPSe (disclaimer: I'm a co-developer). The soft constraints are handled via an objective function.
:- lib(ic).
:- lib(ic_global_gac).
:- lib(branch_and_bound).
schedule(Points, As, Bs) :-
As = [_ASu,_AMo, ATu,_AWe, ATh,_AFr,_ASa],
Bs = [_BSu,_BMo,_BTu, BWe,_BTh,_BFr,_BSa],
As :: 0..1,
Bs :: 0..1,
( foreach(A,As), foreach(B,Bs) do A+B #= 1 ), % Rule 1
ATu = 1, % Rule 2
sequence(0, 2, 3, As), % 0..2 out of 3, Rule 3
sequence(0, 2, 3, Bs),
Points #= 2*ATh + 5*(1-BWe), % Soft
Cost #= -Points,
append(As, Bs, ABs),
minimize(labeling(ABs), Cost).
?- schedule(P, As, Bs).
P = 5
As = [0, 0, 1, 1, 0, 0, 1]
Bs = [1, 1, 0, 0, 1, 1, 0]
Yes (0.03s cpu)
A: In Prolog, for simple problems, we can try to apply a simple 'pattern', plain old generate and test, interesting for its simplicity. We 'just' provide appropriate domain generator and test.
generate(D0, D) :-
length(D0, DL),
length(D, DL),
maplist(dom_element, D).
dom_element(a).
dom_element(b).
test(D, Score, D) :-
D = [_Sunday, _Monday, Tuesday, Wednesday, Thursday, _Friday, _Saturday],
% 1. In a single day, either A or B (but not both) must be working
% Here True by construction
% 2. A must work on Tuesday
Tuesday = a,
% 3. no one can work continuously for more than 2 days
no_more_than_2(D),
% soft 1. A prefers to work on Thursday (add 2 points if A works on Thursday )
( Thursday = a -> S1 is 2 ; S1 is 0 ),
% soft 2. B dislike to work on Wednesday (add 5 points if B doesn't work on Wednesday)
( Wednesday \= b -> S2 is 5 ; S2 is 0 ),
Score is S1 + S2.
% edit: jshimpfs suggestion, beside being much better, highlights a bug
no_more_than_2(D) :-
nth0(I, D, E),
length(D, L),
J is (I+1) mod L,
nth0(J, D, E),
K is (J+1) mod L,
nth0(K, D, E),
!, fail.
no_more_than_2(_).
solve(D0, Best) :-
D0 = [sun,mon,tue,wed,thu,fri,sat],
setof(Score/Sol, D^(generate(D0, D), test(D, Score, Sol)), All),
last(All, Best).
test:
?- solve(_,L).
L = 5/[b, b, a, a, b, b, a]. | unknown | |
d8104 | train | Essentially, you need to sort through your queried data, saving each unique product with a list of all its versions. Then you would manually create the columns for your DataGridView as I'll describe below.
To mock out this scenario I created the following object class:
// The type of binding object for your dgview source.
public class Product
{
public Product()
{
this.Version = new List<double>();
}
public int ID { get; set; }
public string Name { get; set; }
public List<double> Version { get; set; }
}
In your query returning all the objects, I would do something like this:
public BindingList<Product> YourQueryCall()
{
BindingList<Product> products = new BindingList<Product>();
/*
* Your code to query the db.
*/
while reader.Read()
{
Product existingProduct = new Product();
int id = // value from the reader
string name = // value from the reader
double version = // value from the reader
try
{
existingProduct = products.Single(p => p.ID == id && p.Name == name);
existingProduct.Version.Add(version);
}
catch // No product yet exists for this id and name.
{
existingProduct.ID = id;
existingProduct.Name = name;
existingProduct.Version.Add(version);
products.Add(existingProduct);
}
}
return products;
}
That will store only unique products and their lists of versions. And in the form, to show each row's unique list of versions in a ComboBoxColumn:
public Form1()
{
InitializeComponent();
this.Products = YourQueryCall();
this.FillDGView();
}
public BindingList<Product> Products { get; set; }
public void FillDGView()
{
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.Name = "Product ID";
col1.ValueType = typeof(int);
dataGridView1.Columns.Add(col1);
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.Name = "Product Name";
col2.ValueType = typeof(string);
dataGridView1.Columns.Add(col2);
DataGridViewComboBoxColumn col3 = new DataGridViewComboBoxColumn();
col3.Name = "Version";
col3.ValueType = typeof(double);
dataGridView1.Columns.Add(col3);
for (int i = 0; i < this.Products.Count; i++)
{
DataGridViewRow row = (DataGridViewRow)(dataGridView1.Rows[0].Clone());
DataGridViewTextBoxCell textCell = (DataGridViewTextBoxCell)(row.Cells[0]);
textCell.ValueType = typeof(int);
textCell.Value = this.Products[i].ID;
textCell = (DataGridViewTextBoxCell)(row.Cells[1]);
textCell.ValueType = typeof(string);
textCell.Value = this.Products[i].Name;
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)(row.Cells[2]);
comboCell.ValueType = typeof(double);
comboCell.DataSource = this.Products[i].Version;
comboCell.Value = this.Products[i].Version[0];
dataGridView1.Rows.Add(row);
}
}
Hope this helps! | unknown | |
d8105 | train | Check out the source code and look for the blockquote tag.
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eee;
}
There's lots more. CTRL + F will help you. | unknown | |
d8106 | train | Just as a guess since you haven't posed the error, you're not returning the correct json, paticularly in the case of the 404, I'm not really familiar with the way your doing this, but usually you would just return a list of Persons
I'm not even sure why you would want to 404 just because the department doesn't have personal, instead of just returning an Empty List.
Id first verify by changing you're code to look something like this:
public async Task<List<Person>> GetDepartmentMembers([FromRoute] int id)
{
return await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync();
}
If that works it's would appear to be how you're handing your NotFound responses, then you can modify your code to use a global error handler.
Usually I create a custom exception e.g InvalidId to handle my 404's etc
public async Task<List<Person>> GetDepartmentMembers([FromRoute] int id)
{
var members = await _context.Person.Include(x => x.PersonNavigation).Where(x => x.DepartmentId == id).ToListAsync();
if (members == null) {
throw new InvalidId();
}
return members;
}
Then you need to create a global error handler to handle your invalid id exception | unknown | |
d8107 | train | There's nothing wrong with your declarations. The code should compile and link as is, assuming you add explicit int as the return type of your main. The only explanation for the linker error I can come up with is that you are forgetting to supply all required object files to the linker.
The answers that attempt to explain this issue through the fact that in C++ const objects have internal linkage are misleading and irrelevant. The above object foo is not a const object. | unknown | |
d8108 | train | WHERE VisitRefNo=VisitRefNo"; should be WHERE VisitRefNo=@VisitRefNo";.
A: WHERE VisitRefNo=VisitRefNo
Should be
WHERE VisitRefNo=@VisitRefNo | unknown | |
d8109 | train | Your rule is less specific than the previous one so it is getting overridden.
You have to change it to:
.pic .overlay:hover { border: none; }
The concept
Specificity is the means by which a browser decides which
property values are the most relevant to an element and gets to be
applied. Specificity is only based on the matching rules which are
composed of selectors of different sorts.
How is it calculated?
The specificity is calculated on the
concatenation of the count of each selectors type. It is not a weight
that is applied to the corresponding matching expression.
In case of specificity equality, the latest declaration found in the
CSS is applied to the element.
Reference: Specificity
A: As long as overlay always comes after the first image, you can use :first-child to pick only the first image:
.pic img:first-child:hover {
border: 1px black solid;
}
It's supported in everything (excluding IE6, but I don't count that as a thing.)
A: You can also use the :not selector:
.pic img:not(.overlay):hover {
border: 1px black solid;
}
This way you won't have to worry about the order of the images and also don't have to worry about specificity by including another reset style. | unknown | |
d8110 | train | You need to make use of controlled state to achieve similar result. Take a look at the following example:
example.js
import React, { useState } from "react";
import { Label, Menu, Tab } from "semantic-ui-react";
const panes = [
{
menuItem: { key: "users", icon: "users", content: "Users" },
render: () => <Tab.Pane>Tab 1 Content</Tab.Pane>
},
{
menuItem: (
<Menu.Item key="messages">
Messages<Label>15</Label>
</Menu.Item>
),
render: () => <Tab.Pane>Tab 2 Content</Tab.Pane>
},
{
menuItem: <Menu.Item key="open">Open</Menu.Item>
}
];
const TabExampleCustomMenuItem = () => {
const [activeIndex, setActiveIndex] = useState(0);
return (
<Tab
panes={panes}
activeIndex={activeIndex}
onTabChange={(e, data) => {
if (data.activeIndex === 2) {
alert(`You've clicked on the "Open" tab!`);
return;
}
setActiveIndex(data.activeIndex);
}}
/>
);
};
export default TabExampleCustomMenuItem; | unknown | |
d8111 | train | This is happening because blur happens before click, in your code
$(this).parents("tr").remove();
is executing before the click happens, so there's actually nothing to click on (and bubble up to trigger the .live() event). In your case, I would remove the add option from the currently being added row. | unknown | |
d8112 | train | data_.emplace_back(std::forward<T>(t));
will add elements to the vector. But if the vector runs out of space it will allocate a larger chunk of memory and copy or, if possible, move the existing objects into the new storage.
You need to be much more clever to cache all the objects, reserve enough space for them and only at the end emplace them all. | unknown | |
d8113 | train | Here is a way to do it:
*
*for both A and B directories, list the files under each directory, without the extension.
*compare both lists, show only the file that does not appear in both.
Code:
#!/bin/bash
>a.list
>b.list
for file in A/*
do
basename "${file%.*}" >>a.list
done
for file in B/*
do
basename "${file%.*}" >>b.list
done
comm -23 <(sort a.list) <(sort b.list) >delete.list
while IFS= read -r line; do
rm -v A/"$line"\.*
done < "delete.list"
# cleanup
rm -f a.list b.list delete.list
*
*"${file%.*}" removes the extension
*basename removes the path
*comm -23 ... shows only the lines that appear only in a.list
EDIT May 10th: my initial code listed the file, but did not delete it. Now it does.
A: Try this Shellcheck-clean Bash program:
#! /bin/bash -p
folder_a=PATH_TO_FOLDER_A
folder_b=PATH_TO_FOLDER_B
shopt -s nullglob
for ppath in "$folder_a"/*.profile; do
pfile=${ppath##*/}
dfile=${pfile%.profile}.dssp
dpath=$folder_b/$dfile
[[ -f $dpath ]] || echo rm -v -- "$ppath"
done
*
*It currently just prints what it would do. Remove the echo once you are sure that it will do what you want.
*shopt -s nullglob makes globs expand to nothing when nothing matches (otherwise they expand to the glob pattern itself, which is almost never useful in programs).
*See Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?)) for information about the string manipulation mechanisms used (e.g. ${ppath##*/}).
A: With find:
find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \
'! [ -f "folder B/$(basename -s .fasta.profile "$1").dssp" ]' _ {} \; -print
Replace -print by -delete when you will be convinced that it does what you want.
Or, maybe a bit faster:
find 'folder A' -type f -name '*.fasta.profile' -exec sh -c \
'for f in "$@"; do [ -f "folder B/$(basename -s .fasta.profile "$f").dssp" ] || echo rm "$f"; done' _ {} +
Remove echo when you will be convinced that it does what you want.
A: Python version:
EDIT: now suports multiple extensions
#!/usr/bin/python3
import glob, os
def removeext(filename):
index = filename.find(".")
return(filename[:index])
setA = set(map(removeext,os.listdir('A')))
print("Files in directory A: " + str(setA))
setB = set(map(removeext,os.listdir('B')))
print("Files in directory B: " + str(setB))
setDiff = setA.difference(setB)
print("Files only in directory A: " + str(setDiff))
for filename in setDiff:
file_path = "A/" + filename + ".*"
for file in glob.glob(file_path):
print("file=" + file)
os.remove(file)
Does pretty much the same as my bash version above.
*
*list files in A
*list files in B
*get the list of differences
*delete the differences from A
Test output, done on Linux Mint, bash 4.4.20
mint:~/SO$ l
drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 A/
drwxr-xr-x 2 Nic3500 Nic3500 4096 May 10 10:36 B/
mint:~/SO$ l A
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:36 file4.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile
mint:~/SO$ l B
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file1.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file3.dssp
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:05 file.dssp
mint:~/SO$ ./so.py
Files in directory A: {'file1', 'file', 'file3', 'file2', 'file4'}
Files in directory B: {'file1', 'file', 'file3', 'file2'}
Files only in directory A: {'file4'}
file=A/file4.fasta.profile
mint:~/SO$ l A
total 0
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file1.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file2.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:14 file3.fasta.profile
-rw-r--r-- 1 Nic3500 Nic3500 0 May 10 10:06 file.fasta.profile | unknown | |
d8114 | train | Apparently, the "Safe HTML policy" on Exchange can lead to some URIs with "non-standard" schemes being just treated as plain text.
If this is the case and you can't control the policy on the server, the only option is to wrap in a HTTP redirect. :( | unknown | |
d8115 | train | As mentioned in comment:
1] Don't use string concatenation for sql query, use parameterized queries. Check the below code for use of sqlcommand with use of parameters.
2] I've clubbed both the queries using subquery so you only need to connect to database once. [This will work only if there is 1 row returned from the subquery which it should in this case as you are using ID as reference, else use IN operator]
3] Mapping DropDownList2.DataSource = dta; is not sufficient, you need to map DataTextField and DataValueField too to inform exactly which column will be mapped, I've used column ref by index but you can give name too. According to me that's the reason that it's showing System.Data.DataViewRow in dropdown instead of the values.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s1 = DropDownList1.SelectedValue.ToString();
string perfectid = string.Empty;
con.Open();
SqlCommand cmd = new SqlCommand("select song_name from songs where id=(select [Id] from [Table] where movie_name=@moviename",con);
cmd.Parameters.AddWithValue("@moviewname", s1);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dta = new DataTable();
sda.Fill(dta);
con.Close();
DropDownList2.DataSource = dta;
DropDownList2.DataTextField = dta.Columns[0].ColumnName;
DropDownList2.DataValueField = dta.Columns[0].ColumnName;
DropDownList2.DataBind();
} | unknown | |
d8116 | train | This was a mistake we made when adding support for the PNG eXIf chunk. This will be resolved in ImageMagick 7.0.7-35. If you upgrade your libpng library you can also fix the build. You will need a version of libpng that has PNG_READ_eXIf_SUPPORTED defined.
p.s. Next time it will be better to create an issue here: https://github.com/ImageMagick/ImageMagick/issues. You will get a much faster response. | unknown | |
d8117 | train | You're appending to the <td>, instead, append the cell and the next <td>'s to the row:
var sizes = [
[52, 16, 140],
[54, 16, 145]
];
var table = $('#size-rows');
var row, cell;
for (var i = 0; i < sizes.length; i++) {
row = $('<tr />');
table.append(row);
cell = $('<td>Default TD</td>');
row.append(cell);
for (var j = 0; j < sizes[i].length; j++) {
row.append('<td>' + sizes[i][j] + '</td>');
}
}
td {
border: 1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="size-rows"> </tbody>
</table>
A: here is a solution using the map function.
var sizes= [
[52, 16, 140],
[54, 16, 145]
];
$('#size-rows').append(
sizes.map(
x => `<tr>
<td>Default TD</td>${x.map(y => `<td>${y}</td>`)}
</tr>`
)
);
td{
border:1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="size-rows"> </tbody>
</table> | unknown | |
d8118 | train | Add these dependencies to your project:
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
First change your Main activity must be extended from AppCompatActivity.
Than change your main activity's layout like below:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinatorlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".Main">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbarlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
layout="@layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabIndicatorHeight="4dp"
app:tabMode="fixed"
app:tabIndicatorColor="@android:color/white"
android:background="@color/AppPrimary"/>
</android.support.design.widget.AppBarLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".dashboard.DashboardActivity"
tools:showIn="@layout/activity_dashboard">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
And here's a toolbar layout example. You can customize however you want.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar_main"
style="@style/Widget.MyApp.Toolbar.Solid"
android:layout_width="match_parent"
android:layout_height="@dimen/abc_action_bar_default_height_material"
android:background="@color/AppPrimary"
app:contentInsetEnd="16dp"
app:contentInsetStart="16dp" />
Than you need to create fragments which you'll use in your tabs instead of activities which you use for tabs. In this case this'll your Status Activity if i'm not wrong.
Define a StatusFragment like below:
public class StatusFragment extends Fragment
{
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// this is your Status fragment. You can do stuff which you did in Status activity
}
}
Than you need to define a tabs adapter which you'll bind with your tabs and convert your TabHost to Fragment/Fragment manager type. Titles string array contains strings which you'll show in your tabs indicator. Such as "Status, My Assume Tab, My awesome tab 2
public class DashboardTabsAdapter extends FragmentPagerAdapter {
private String[] mTitles;
public DashboardTabsAdapter(FragmentManager fm, String[] titles) {
super(fm);
this.mTitles = titles;
}
@Override
public Fragment getItem(int position) {
return new StatusFragment();
// You can define some other fragments if you want to do different types of operations in your tabs and switch this position and return that kind of fragment.
}
@Override
public int getCount() {
return mTitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles[position];
}
}
And finally in your Main activity find your view pager, tabs create a new adapter and bind them.
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
final DashboardTabsAdapter dashboardTabsAdapter = new DashboardTabsAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.tab_titles));
mViewPagerMain = (ViewPager) findViewById(R.id.viewpager_main);
mViewPagerMain.setOffscreenPageLimit(3);
mViewPagerMain.setAdapter(dashboardTabsAdapter);
tabLayout.setupWithViewPager(mViewPagerMain);
Edit: You'll no longer need TabHost and TabActivity any more. Your tab grup activity will be your ViewPager which handles screen changes and lifecycle of fragments inside. If you need to get this activity from fragments you can use getActivity() method and cast it to your activity and use it's public methods.
A: First you need to add Design Support Library and AppCompatLibrary into your Project
Add this code into your app gradle
compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.android.support:design:24.0.0'
layout for activity_main.xml (like main.xml in your code)
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/appbar_padding_top"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
In above layout ViewPager will provides horizontal layout to display tabs. You can display more screens in a single screen using tabs. You can swipe the tabs quickly as you can.
Root Fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/root_frame" >
View for First Fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#ff0"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:text="@string/first_fragment" />
<Button
android:id="@+id/btn"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:text="@string/to_second_fragment"/>
</RelativeLayout>
View for Second and Individual(s) Fragment.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin">
<TextView
android:id="@+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Now add a MainActivity(like Main Activity in yours code) under which all this thing will handle.
public class MainActivity extends AppCompatActivity {
private TabGroupAdapter mTabGroupAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
fragmentList.add(new RootFragment());
fragmentList.add(new IndividualFragment1());
fragmentList.add(new IndividualFragment2());
ArrayList<String> name = new ArrayList<String>() {
{
add("Root Tab");
add("Second Tab");
add("Third Tab");
}
};
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mTabGroupAdapter = new TabGroupAdapter(getSupportFragmentManager(),name, fragmentList,);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mTabGroupAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
}
There is one FragmentPagerAdapter defined as mTabGroupAdapter inside MainActivity that will add a different tabs inside a single Layout.
First we bind the mTabGroupAdapter to mViewPager.
TabLayout will act like a TabHost under which Tab will be added by FragmentPagerAdapter.
mViewPager is bind to the Tablayout.
Under MainActivity TabLayout will display the name of Tabs.
TabGroupAdapter
public class TabGroupAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
private ArrayList<String> fragment_name;
public TabGroupAdapter(FragmentManager fm, ArrayList<String> name, ArrayList<Fragment> list) {
super(fm);
this.fragmentList = list;
this.fragment_name = name;
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return fragment_name.get(position);
}
}
In TabGroupAdapter you would pass a List of fragments(or single fragment) and list of fragments name(or single name) as arguments in the Constructor.
IndividualFragment(s) will act like a individual Tab instead of Activity.
RootFragment will be acting as a container for other fragments( First Fragment and Second Fragment)
Root Fragment
public class RootFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.root_frame, new FirstFragment());
fragmentTransaction.commit();
return view;
}
}
First Fragment
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_fragment, container, false);
Button btn = (Button) view.findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//use the "root frame" defined in
//"root_fragment.xml" as the reference to replace fragment
fragmentTransaction.replace(R.id.root_frame, new SecondFragment());
/*
* allow to add the fragment
* to the stack and return to it later, by pressing back
*/
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
Second Fragment
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
Individual(s) Fragment
public class IndividualFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
public class IndividualFragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
In OnCreateView method you would set a layout of a Tab .
You won't have to use the getTabHost() method.
Let me know if you persist any problem.
Whenever you want to dynamically change or update the Tabs in View Pager just add or remove item from fragmentList and call this method mTabGroupAdapter.notifyDataSetChanged(); inside MainActivity. | unknown | |
d8119 | train | Parameters shall be coming before image:tag in CLI | unknown | |
d8120 | train | from the book you mentioned in the comments. . just after this code ... the statement in the book is :
Whew! Aren't you glad you don't ahve to do that every time you use a variable ??
what you need is below :
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.print( "Hello. What is your name? " );
String name = keyboard.next();
System.out.print( "Hi, " + name+ "! How old are you? " );
int age = keyboard.nextInt();
System.out.println("So you're " + age + ", eh? That's not so old.");
System.out.print( "How much do you weigh, " + name + "? " );
double weight = keyboard.nextDouble();
System.out.println( weight + "! Better keep that quiet!!" );
System.out.print("Finally, what's your income, " + name + "? " );
double income = keyboard.nextDouble();
System.out.print( "Hopefully that is " + income + " per hour" );
System.out.println( " and not per year!" );
System.out.print( "Well, thanks for answering my rude questions, " );
System.out.println( name + "." );
} | unknown | |
d8121 | train | The answer turned out to be pretty simple. I was close with this attempt:
Html.DropDownListFor((m) => temp2, EnumHelper.GetSelectList(temp2.GetType()))
I just needed to override the GetSelectList:
Html.DropDownListFor((m) => temp2, EnumHelper.GetSelectList(temp2.GetType(), (Enum)temp2))
A: Here is my enum extensions I usually use. Hope it can help.
public enum Gender
{
[EnumDescription("Not selected")]
NotSelected,
[EnumDescription("Male")]
Male,
[EnumDescription("Female")]
Female
}
In your view (you can omit "data-bind" Knockout binding)
@Html.DropDownList(
"gender",
SelectListExt.ToSelectList(typeof(Gender)),
new
{
data_bind = "value: Gender",
})
Select list helper class:
public static class SelectListExt
{
public static SelectList ToSelectList(Type enumType)
{
return ToSelectList(enumType, String.Empty);
}
public static SelectList ToSelectList(Type enumType, string selectedItem)
{
List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in Enum.GetValues(enumType))
{
FieldInfo fi = enumType.GetField(item.ToString());
var attribute = fi.GetCustomAttributes(typeof(EnumDescription), true).FirstOrDefault();
var title = attribute == null ? item.ToString() : ((EnumDescription)attribute).Text;
// uncomment to skip enums without attributes
//if (attribute == null)
// continue;
var listItem = new SelectListItem
{
Value = ((int)item).ToString(),
Text = title,
Selected = selectedItem == ((int)item).ToString()
};
items.Add(listItem);
}
return new SelectList(items, "Value", "Text", selectedItem);
}
}
And the attribute itself:
public class EnumDescription : Attribute
{
public string Text { get; private set; }
public EnumDescription(string text)
{
this.Text = text;
}
}
You can also use my extension class to convert enums to their string descriptions:
public static class EnumExtensions
{
public static string ToDescription(this Enum enumeration)
{
Type type = enumeration.GetType();
MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
if (null != memInfo && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumDescription), false);
if (null != attrs && attrs.Length > 0)
return ((EnumDescription)attrs[0]).Text;
}
else
{
return "0";
}
return enumeration.ToString();
}
}
This code is not perfect, but it works for me. Feel free to refactor and post updates! | unknown | |
d8122 | train | localStorage is a Dictionary. It stores Key/Value pairs. Both Key and Value are string.
As Dictionary keys must be unique, values as Test and test are not the same, and therefore must be saved into Dictionary as 2 separate entries.
Also, localStorage has no functionality to get all added Keys or Values, unlike C# or Java. Don't know exact reason for this functionality being missed. It can be due to security, so that rogue JavaScript has no ability to interrogate the storage, or just to keep it simple.
The only way to get value by case insensitive Key, is to store them case insensitive.
You can use either toUpper or toLower on Key before adding it to localStorage. However, Microsoft says converting to upper case is safest: https://learn.microsoft.com/en-gb/visualstudio/code-quality/ca1308-normalize-strings-to-uppercase?view=vs-2015 | unknown | |
d8123 | train | If you add Environment Variable in job properties?
In this case, if you set a variable, you will can call a cuostom routine that calculated the split value. | unknown | |
d8124 | train | This works:
(this as ExtensionAware).extensions.extraProperties.set("heapEnabled", true)
I believe Heap is looking into making it so the cast isn't necessary.
A: extra.set("heapEnabled", false)
A: I was able to make it work using withGroovyBuilder like:
android {
defaultConfig {
withGroovyBuilder {
"ext" {
setProperty("heapEnabled", LhConfig.isAnalyticEnabled(project))
}
}
I still dont understand where is the issue :( | unknown | |
d8125 | train | I have "solved" the problem by changing the last few lines to:
final Authentication result = super.authenticate(auth);
UserDetails userDetails = userDetailsService.loadUserByUsername(auth.getName());
return new UsernamePasswordAuthenticationToken(userDetails,
result.getCredentials(), userDetails.getAuthorities());
...where userDetailsService points to a simple implementation of the Spring Security UserDetailsService which returns a Spring Security UserDetails object, like so:
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username);
if(user == null) throw new UsernameNotFoundException(username);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(), user.getEnabled(), user.getNonExpired(),
user.getCredentialsNonExpired(), user.getNonLocked(), grantedAuthorities);
}
This works elsewhere in my application so I figured it might work here as well. I believe I could have left the final argument as result.getAuthorities(). I think I can also refactor so I'm not hitting the database twice, but for now I'm just glad that it works.
I'm not 100% sure why my relatively simple User model would not return the username as the Principal name, it may be that there is some more work which should be done to my User object to explicitly mark the username String as the principal name.
If anyone is interested in any further updates, or can provide any more information for anyone else experiencing uncertainty on this issue, please leave a comment or provide another (likely better) answer. | unknown | |
d8126 | train | If I understand your need, you wish to set a mergefield and replace this mergefield with a table?
If it that, you can use HTML text styling. You design your docx template like this :
${htmlTable}
You mark that htmlTable field uses HTML syntax :
FieldsMetadata metadata = report.createFieldsMetadata();
metadata.addFieldAsTextStyling("htmlTable", SyntaxKind.Html);
You put in the context, the HTML table :
context.put("htmlTable", "<table><tr><td>A</td><td>B</td></tr></table>");
But today, it's very basic, you cannot manage border, width, height, etc for HTML table. See issue 302 | unknown | |
d8127 | train | --Syntax: IS_SRVROLEMEMBER ( 'role' [ , 'login' ] )
--Return value as NULL indicates role or login is not valid, or you do not have permission to view the role membership
--Return value as 0 indicates login is not a member of role.
--Return value as 1 indicates login is a member of role.
--I think you are using rong value for role paramenter.(Use role value from below)
--sysadmin,bcreator,bulkadmin,diskadmin,public,processadmin
USE [MYDatabase];
DECLARE @database_principals_name NVARCHAR(100) = 'db_owner'
DECLARE @RoleName NVARCHAR(100) = 'sysadmin' -- User Defined DB ROle
IF EXISTS (Select name from sys.database_principals where name = @database_principals_name)
BEGIN
select IS_SRVROLEMEMBER ('sysadmin')
--Output: NULL
END
A: It has to be IS_ROLEMEMBER(@RoleName, @AddUser) as it is checking for the database role instead of IS_SRVROLEMEMBER (@RoleName, @AddUser). | unknown | |
d8128 | train | You can use checked property from the DOM object.
For exmaple
$("#itemtable").on('click', '.btnSelect', function() {
if(this.checked){
// get the current row
alert("i am inside dddd");
var currentRow = $(this).closest("tr");
var col1 = currentRow.find("td:eq(0)").text(); // get SI no from checkbox
var col2 = currentRow.find("td:eq(1)").text(); // get item name
var col3 = currentRow.find("td:eq(2)").text(); // get item code
var col4 = currentRow.find("td:eq(3)").text(); // get supplier
var col5 = currentRow.find("td:eq(4)").text(); // get received qty
var col6 = $(currentRow).find("td:eq(5) input[type='text']").val(); // get accepted qty
var col7 = $(currentRow).find("td:eq(6) input[type='text']").val(); // get rejected qty
var col8 = $(currentRow).find("td:eq(7) input[type='text']").val(); // get remarks
var data = col1 + "\n" + col2 + "\n" + col3 + "\n" + col4 + "\n" + col5 + "\n" + col6 + "\n" + col7 + "\n" + col8;
alert(data);
}
});
I have made an exmaple on jsfiddle:
https://jsfiddle.net/fcaj5g52/1/
A:
$(document).ready(function() {
$("#saverecord").click(function(event) {
//$("#itemtable").on('click', '.btnSelect', function() {
// get the current row
var currentRow = $(".btnSelect:checked").closest("tr");
console.log(currentRow.index())
var col1 = currentRow.find("td:eq(0)").text(); // get SI no from checkbox
var col2 = currentRow.find("td:eq(1)").text(); // get item name
var col3 = currentRow.find("td:eq(2)").text(); // get item code
var col4 = currentRow.find("td:eq(3)").text(); // get supplier
var col5 = currentRow.find("td:eq(4)").text(); // get received qty
var col6 = currentRow.find("td:eq(5)").text()
var col7 = currentRow.find("td:eq(6)").text()
var col8 = currentRow.find("td:eq(7)").text()
var data = col1 + "\n" + col2 + "\n" + col3 + "\n" + col4 + "\n" + col5 + "\n" + col6 + "\n" + col7 + "\n" + col8;
console.log(data);
});
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tablediv">
<table cellspacing="0" id="itemtable" align="center">
<tr>
<td><input type="checkbox" class="btnSelect" id="chk" name="chk" /></td>
<th scope="col"> SIno</th>
<th scope="col">Item name</th>
<th scope="col">Item code</th>
<th scope="col">Supplier</th>
<th scope="col">Received qty</th>
<th scope="col">Accepted qty</th>
<th scope="col">Rejected qty</th>
<th scope="col">Remarks</th>
</tr>
<tr>
<td><input type="checkbox" class="btnSelect" id="chk" name="chk" /></td>
<td> 1 </td>
<td> biscuit </td>
<td>e123</td>
<td>abc company</td>
<td>23</td>
<td>20</td>
<td>3</td>
<td>waste</td>
</tr>
<tr>
<td><input type="checkbox" class="btnSelect" id="chk" name="chk" /></td>
<td> 2 </td>
<td> chocolate </td>
<td>e526</td>
<td>xyz company</td>
<td>25</td>
<td>20</td>
<td>5</td>
<td>waste</td>
</tr>
</table>
<input type="button" value="Save the record" id="saverecord" class="button0">
</div>
DOnt use this context because your click event is the save button
A: Reason of this - you need to use change event when you work with checkboxes, because they have state, like this:
$(document).on('change', '.btnSelect', function() {
I use $(document) in my test because you did not post rest of you code.
A: just check a condition that the check box is checked or not
var isChecked= document.getElementById("btnSelect").checked;
if(isChecked){
// write your code here
} | unknown | |
d8129 | train | If you are talking about having the option to store in hdfs(run map reduce) in future and then perform indexing with solr, then I think, you can follow the below steps
For real time streaming(for eg twitter), you need to store them in db at real time. One option is to send them to kakfka and utilize storm. From there you can store in hdfs and in solr in parellel. They have concept of bolts which will perform the same. Once is hdfs, you can use map reduce. Once in Solr, you an perform search. If you want both data to be in synch, you can try some event processing which listens to data insertion into HDFS(or its stack) and perform indexing in Solr. Please go through kafka, storm documentation to have basic idea. Alternatives can be Flume, or Spark. Not sure about those. | unknown | |
d8130 | train | So found I can use the secrets, to set an env, however only for workflows, not for the action, for some reason.
env:
IS_STEP_DEBUG: ${{ secrets.ACTIONS_STEP_DEBUG }} | unknown | |
d8131 | train | Redirection of connections along the lines that you want requires support from the (application) protocol. TCP/IP does not support it. AFAIK, SOCKS does not support it either. Unless the Minecraft application protocol (and by implication, Minecraft clients and servers) include support for redirection, you are out of luck.
(FWIW - that's how HTTP redirection works. HTTP has a "protocol element" that allows the server to tell the client to redirect, and where to redirect to. The client then resends the original request to a new address.)
But that doesn't mean that you can't deal with the pests. It just means that the redirection approach is not viable. Try a custom proxy or an IP filter / redirector instead.
A: You are trying to save the server's resources on the cost of increase Traffic.
I am not sure with the answer but may be by looking into the concept of LBS(Load Balancing Server) you may find the answer.
LBS is purely defined and controlled by us so you can manage the resources of two servers using one load balancing server. | unknown | |
d8132 | train | I think you are re-inventing the wheel. Consider using OpenFire or Tigase which are Java-based and very proven in this IM server space. All the boiler-plate can be leveraged. You tasks would be to add custom behaviors by writing plug-ins. | unknown | |
d8133 | train | I. [1-9][0-9]* if the number should be greater than zero (any series of digits starting with a nonzero digit). if it should be zero or more: (0|[1-9][0-9]*) (zero or a nonzero number). If it can be negative: (0|-?[1-9][0-9]*) (zero or a nonzero number that can have a minus before it.)
II. a regex like I. followed by: (\.[0-9]{1,2})? that means, optionally a dot followed by one or two digits.
A: Only whole numbers:
/^\d+$/
# explanation
\d match a digit
+ one or more times
Numbers with at most 2 decimal places:
/^\d+(?:\.\d{1,2})?$/
# explanation
\d match a digit...
+ one or more times
( begin group...
?: but do not capture anything
\. match literal dot
\d match a digit...
{1,2} one or two times
) end group
? make the entire group optional
Notes:
*
*The slashes denote start and end of pattern
*^ and $ are start and end of string anchors. Without these, it will look for matches anywhere in the string. So /\d+/ matches '398501', but it also matches 'abc123'. The anchors ensures the entire string matches the given pattern.
*If you want to allow negative numbers, add a -? before the first \d. Again, ? denotes "zero or one time."
Usage example:
var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/);
console.log(rx.test('abc')); // false
console.log(rx.test('309')); // true
console.log(rx.test('30.9')); // true
console.log(rx.test('30.85')); // true
console.log(rx.test('30.8573')); // false
A: Whole numbers only
/\d+/
One or two decimal places:
/\d(\.\d{1,2})?/ | unknown | |
d8134 | train | Your specific example is perfectly fine with ELEMENTAL
module myTypes
implicit none
public :: Coordinates
type Coordinates
real :: x,y
contains
procedure :: swap ! Error here
end type
contains
elemental subroutine swap(this)
class (Coordinates), intent(inout) :: this
this%x = this%x + this%y
this%y = -(this%y - this%x)
this%x = this%x - this%y
end subroutine
end module
use myTypes
type(Coordinates) :: arr(10)
arr = Coordinates(1.,2.)
call arr%swap
end
Your subroutine is pure. If it cannot be, consider using impure elemental. | unknown | |
d8135 | train | Assuming you really have a numpy array (not a list of list), you can use astype(str):
values = np.array([[ 116.17265886, 39.92265886, 116.1761427 , 39.92536232],
[ 116.20749721, 39.90373467, 116.21098105, 39.90643813],
[ 116.21794872, 39.90373467, 116.22143255, 39.90643813]])
out = values.astype(str)
output:
array([['116.17265886', '39.92265886', '116.1761427', '39.92536232'],
['116.20749721', '39.90373467', '116.21098105', '39.90643813'],
['116.21794872', '39.90373467', '116.22143255', '39.90643813']],
dtype='<U32')
A: If it's not a numpy array and it is a list of a list of values the following code should work:
for index in range(len(values)):
values[index] = [str(num) for num in values[index]]
print(values)
For each list it returns a list of each of the values changed to a string, this returns the following.
[['116.17265886', '39.92265886', '116.1761427', '39.92536232'],
['116.20749721', '39.90373467', '116.21098105', '39.90643813'],
['116.21794872', '39.90373467', '116.22143255', '39.90643813']] | unknown | |
d8136 | train | Maybe something like this would help? I briefly considered merging the objects into one big set of objects that had all the information, which would make it easier to format. However, I decided instead to re-lookup the information on each loop. This should be a good start, I hope it helps!
var product = [
{'name':'пряник', 'price':10},
{'name':'кофе', 'price':2},
{'name':'мороженное', 'price':4},
{'name':'макароны', 'price':5},
{'name':'персик', 'price':6},
{'name':'ананас', 'price':15},
];
var purse = [
{'name':'Катя', 'cash':100},
{'name':'Даня', 'cash':200},
{'name':'Ваня', 'cash':400},
{'name':'Саня', 'cash':500},
{'name':'Маня', 'cash':600},
{'name':'Кира', 'cash':150},
];
var purchases = [
{'name':'Катя', 'item':'пряник'},
{'name':'Даня', 'item':'макароны'},
{'name':'Даня', 'item':'кофе'},
{'name':'Даня', 'item':'кофе'},
{'name':'Маня', 'item':'ананас'},
{'name':'Катя', 'item':'мороженное','credit': 20},
];
function displayInfo(name, walletVal) {
const displayArea = document.querySelector("#display");
const spendSummary = document.createElement("div");
spendSummary.classList.add("spendSummary");
const nameEle = document.createElement("div");
nameEle.classList.add("name");
nameEle.innerText = name;
spendSummary.appendChild(nameEle);
const walletEle = document.createElement("div");
walletEle.classList.add("wallet");
walletEle.innerText = walletVal;
spendSummary.appendChild(walletEle);
displayArea.appendChild(spendSummary);
}
const names = [...new Set(purchases.map(e => e.name))];
for (const name of names) {
const filteredPurchases = purchases.filter(e => e.name == name);
const costs = filteredPurchases.map(
({item: itemName}) =>
product.find(item => item.name == itemName).price
);
const creditsArr = filteredPurchases.filter(e => e.credit)
.map(e => e.credit);
const totalCredit = creditsArr.reduce((a,b) => a + b, 0);
const totalCost = costs.reduce((a,b) => a + b, 0);
const cash = purse.find(e => e.name == name).cash;
const currentWallet = cash + totalCredit - totalCost;
displayInfo(name, currentWallet);
}
#display {
display: flex;
justify-content: space-around;
font-family: arial;
}
.spendSummary {
display: flex;
flex-direction: column;
align-items: center;
}
.name {
box-shadow: 0 2px 2px -2px black;
}
<div id="display">
</div> | unknown | |
d8137 | train | You can simply use mixins: you define in the mixin the function isValidEmail and then you import the mixin in the components you need.
https://v2.vuejs.org/v2/guide/mixins.html - Vue v2
https://v3.vuejs.org/guide/mixins.html - Vue v3
For example, instead creating a component Validators.vue as you did in your example, you can create a mixin named Validators.js as per below:
export default {
methods: {
isValidEmail(someEmail) {
//Omitted
}
}
}
Then you can import the mixin in the components you need:
<template>
<div>{{isValidEmail('[email protected]')}}</div>
</template>
<script>
import MixinValidator from 'Validators.js'
export default {
name: 'CompA',
mixins: [ MixinValidator ],
}
</script>
In this way, the component CompA will inherit all the functions, data and computed property defined in the mixin. | unknown | |
d8138 | train | Change your code to only execute if imagenes is an array. Personally I would rethink how you are structuring your initial state. Instead of it being an empty array, perhaps make it an object with all of those properties having default values.
<div className="carousel-item">
{ Array.isArray(imagenes) && imagenes.map((p) => (
<img src={p} className="d-block w-100" alt={nombre} />
))}
</div> | unknown | |
d8139 | train | SET @query = @query + ' and s.Location_ID in ('+@LocationIDs+')';
My question is: how does one replace that line of code and replace it
with a table valued parameter in such a way that the concatenation
would still work?
Suppose your LocationIdArray has this definition:
create type LocationIdArray as table (LocationId int);
Then your IN should look like this:
and s.Location_ID in (select LocationId from @LocationIDs)
This won't work within your exec because @LocationID is in the outer scope respect to exec, you can pass it as a parameter in sp_executesql but the best you can do is to rewrite your dynamic query to static one as there is no reason to use dynamic code here. | unknown | |
d8140 | train | The below aggregate can be used to find out the "id"s which have exactly 3 unique categories:
db.collectionName.aggregate([
{$match : {classification : {$exists : true}}},
{$unwind: "$classification"},
{$group: { _id: "$id", uniqueCategories: {$addToSet: "$classification.category"}}},
{$project: {_id : 1, numberOfCategories: {$size: "$uniqueCategories"}} },
{$match: {numberOfCategories: 3} }
])
Explanation: We start with matching documents which have the classification element. Then we $unwind it so as to deconstruct the embedded array into separate documents. Then it is grouped by id, and using $addToSet the categories are collected into an array - this takes care of eliminating any dupes. Then we project its $size and match on 'equal to 3'.
This aggregate will yield documents with the _id set to the id field of the documents in your collection that have 3 unique categories, which you can use to get to the documents. If your collection size is quite large, you should consider adding another $match stage in the beginning to restrict the dataset. As it stands now, it will be doing a collection scan. | unknown | |
d8141 | train | As of Angular 1.2 you can use ng-start/ng-end to create nested trees/iterate over nested lists.
<md-list flex>
<md-list-item style="margin-left: 10px;"ng-repeat-start="item in nestedList">{{item.id}}</md-list-item>
<md-list-item style="margin-left: 50px;" ng-repeat-end ng-repeat="child in item.children">{{child.id}}</md-list-item>
</md-list>
http://codepen.io/jdeyrup/pen/JRPNyW
A: Unfortunately, as to the last releases of angular material, there is no such directive to make a tree menu like that, you should combine different directive such as the sidebar and the vertical menu.
I used the sidebar in my project:
<section class="wrapper" layout="row" flex>
<md-sidenav class="md-sidenav-left md-whiteframe-z3 background-red" md-component-id="left" md-is-locked-open="$mdMedia('gt-md')">
<md-toolbar>
<img class="logo" src="images/logo.png" />
</md-toolbar>
<md-content ng-controller="LeftCtrl">
<menu></menu>
<md-button ng-click="close()" class="md-primary" hide-gt-md>
Close Sidenav Left
</md-button>
</md-content>
<div flex></div>
<div class="copy">Copyright © 2015</div>
</md-sidenav>
<md-content class="wrapper" flex>
<div class="wrapper ngview-wrapper" layout="column" layout-fill layout-align="top center" ng-view></div>
<div flex></div>
</md-content>
</section>
You won't need the part that handle opening and closing of the sidebar.
Inside the menu directive you will be able to put everything you want as menu | unknown | |
d8142 | train | Actually, it does behave as expected. groupBy returns a map. When you map over a map, you construct a new map, where, of course, each key is unique. Here, you'd have the key 1 twice…
You should then call toList before calling map, not after. | unknown | |
d8143 | train | If you need to get data more frequently than the default available in Windows Phone, you should think about using push notifications. This won't be suitable for a full data push, but if you use it correctly, you can get a user experience that you can live with.
One common approach to this is to set up your server to send a notification to the device when there is something new to report instead of pushing a "nothing has changed" message every 10 minutes or so. If you push out a tile update notification to say, for example, "You have x unread items", the user may then click on the tile for your app and you can poll the server for new items on launch/resume. If you want a more intrusive option, you can send a toast notification as well, but in most cases the tile update will be sufficient.
This method has a few advantages.
*
*You won't be burning through battery power polling every 10 minutes while the user is asleep
*Your server will have significantly less load since it is not having to process full data requests every 10 minutes per client.
*This fits in with the design philosophy of Phone apps - you are surfacing the required data to the user, while at the same time preserving battery life.
A: Do I understand correctly that your primary goal is to keep some host session alive by having the phone make a query periodically? If so...
I would not recommend this approach: 1) you cannot count on the phone having network connectivity when it tries to send its query. If the user puts the phone away in a pocket or purse, the odds worsen. 2) it's probably bad from a security perspective, and wasteful from a host resources perspective.
You might instead add logic to your app to resume a timed-out host session as seamlessly as possible. This would add real utility value to the mobile app value proposition over raw HTTP access to the same host. | unknown | |
d8144 | train | You could combine apply() with irr().
What you try to find is the interest rate, where the NPV is 0. However, as you only have positive revenues and no initial investment (neg. sign), it can not be. Please check out the formula used in the docs. You might want to also consider the expenses?
I've edited your example to demonstrate a working solution.
Update: I added large initial payments and passed the delta between expenses and revenue to irr().
import numpy_financial as npf
import pandas as pd
data = [{'Month': '2020-01-01', 'Expense':100000, 'Revenue':5000, 'Building':'Stadium'},
{'Month': '2020-02-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
{'Month': '2020-03-01', 'Expense':7000, 'Revenue':5000, 'Building':'Stadium'},
{'Month': '2020-04-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
{'Month': '2020-01-01', 'Expense':500000, 'Revenue':6000, 'Building':'Casino'},
{'Month': '2020-02-01', 'Expense':5000, 'Revenue':4000, 'Building':'Casino'},
{'Month': '2020-03-01', 'Expense':5000, 'Revenue':9000, 'Building':'Casino'},
{'Month': '2020-04-01', 'Expense':6000, 'Revenue':10000, 'Building':'Casino'}]
df = pd.DataFrame(data)
irr = df.groupby('Building')[['Revenue','Expense']].apply(lambda x: npf.irr(x['Revenue'] - x['Expense']))
print(irr)
Output:
Building
Casino -0.786486
Stadium -0.809623
dtype: float64
A: While I am no expert on Financial Analysis, I believe this question requires more explanation and assessment than what has been presented. So, with all due respect to @KarelZ's response which in fact produces an answer for the stated data, I think from a financial analysis standpoint it is not of much value.
As defined Internal Rate of Return (IRR) is a metric used in financial analysis to estimate the profitability of potential investments. IRR is a discount rate that makes the net present value (NPV) of all cash flows equal to zero in a discounted cash flow analysis. The inherent assumptions in this definition are (1) there exists an initial investment and (2) there is a cashflow stream resulting from the investment.
As defined Net Present Value (NPV) is the present value of the cash flows at a specified rate of return of your project compared to your initial investment. In practical terms, it's a method of calculating your return on investment, or ROI, for a project or expenditure. While NPV doesn't necessarily imply an initial investment, it does imply that for the calculation to be useful, the true cashflow should be evaluated which implies taking into account the expenses as well as the revenue to be meaningful.
In order to compute a valid IRR we need to incorporate the initial investment in the structures and compute the IRR based on differences between Expenses and Revenue. With this in mind, I have modified the original dataset by adding a row to each structure showing the initial investment as an Expense. See below:
# Intitialise data of lists
data = [{'Month': '2019-12-01', 'Expense':100000, 'Revenue':0, 'Building':'Stadium'},
{'Month': '2020-01-01', 'Expense':1000, 'Revenue':5000, 'Building':'Stadium'},
{'Month': '2020-02-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
{'Month': '2020-03-01', 'Expense':7000, 'Revenue':5000, 'Building':'Stadium'},
{'Month': '2020-04-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
{'Month': '2019-12-01', 'Expense':150000, 'Revenue':0, 'Building':'Casino'},
{'Month': '2020-01-01', 'Expense':5000, 'Revenue':6000, 'Building':'Casino'},
{'Month': '2020-02-01', 'Expense':5000, 'Revenue':4000, 'Building':'Casino'},
{'Month': '2020-03-01', 'Expense':5000, 'Revenue':9000, 'Building':'Casino'},
{'Month': '2020-04-01', 'Expense':6000, 'Revenue':10000, 'Building':'Casino'}]
df = pd.DataFrame(data)
This produces the dataframe shown below:
Month Expense Revenue Building
0 2019-12-01 100000 0 Stadium
1 2020-01-01 1000 5000 Stadium
2 2020-02-01 3000 4000 Stadium
3 2020-03-01 7000 5000 Stadium
4 2020-04-01 3000 4000 Stadium
5 2019-12-01 150000 0 Casino
6 2020-01-01 5000 6000 Casino
7 2020-02-01 5000 4000 Casino
8 2020-03-01 5000 9000 Casino
9 2020-04-01 6000 10000 Casino
To this dataframe I added a CashFlow Column consisting of the difference between expense and revenue as follows:
def computeCashFlow(e, r):
return r-e
df['CashFlow'] = df.apply(lambda row: computeCashFlow(row.Expense, row.Revenue), axis= 1)
Which results in the addition of the CashFlow shown below:
Month Expense Revenue Building CashFlow
0 2019-12-01 100000 0 Stadium -100000
1 2020-01-01 1000 5000 Stadium 4000
2 2020-02-01 3000 4000 Stadium 1000
3 2020-03-01 7000 5000 Stadium -2000
4 2020-04-01 3000 4000 Stadium 1000
5 2019-12-01 150000 0 Casino -150000
6 2020-01-01 5000 6000 Casino 1000
7 2020-02-01 5000 4000 Casino -1000
8 2020-03-01 5000 9000 Casino 4000
9 2020-04-01 6000 10000 Casino 4000
Using the CashFlow Column you can then compute IRR and NPR as follows:
df.groupby("Building")["CashFlow"].apply(lambda x: npf.npv(rate=0.1, values=x))
Building
Casino -144180.042347
Stadium -96356.806229
Name: CashFlow, dtype: float64
df.groupby('Building')['CashFlow'].apply(lambda x: npf.irr(x))
Building
Casino -0.559380
Stadium -0.720914
Name: CashFlow, dtype: float64
Giving realistic results for NPV and IRR taking into account the original investments | unknown | |
d8145 | train | Does this do what you need?
try
{
var file = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (file.Length == 0)
{
// do header stuff
}
// do the rest
}
catch (IOException ex)
{
// handle io ex.
}
A: Try something like this:
if (!File.Exists(path))
{
file = File.Open(path, FileMode.CreateNew);
isNew = true;
return;
}
// otherwise append to existing file
file = File.Open(path, FileMode.Append);
isNew = false; | unknown | |
d8146 | train | Specify an appropriate User-Agent by using GlideUrl:
GlideUrl glideUrl = new GlideUrl("https://www.geonames.org/flags/x/ad.gif", new LazyHeaders.Builder()
.addHeader("User-Agent", "Mozilla/5.0")
.build());
Glide.with(this)
.load(glideUrl)
.into(imageViewFlag_info);
A: Try this tutorial to setup GlideApp: https://futurestud.io/tutorials/glide-getting-started
Then write this line of code and it should work on your use case
GlideApp.with(imageView).asGif().load("URL").into(imageView); | unknown | |
d8147 | train | The site you mentioned links to Unicode in RTF:
If the character is between 255 and 32,768, express it as \uc1\unumber*. For example, , character number 21,487, is \uc1\u21487* in RTF.
If the character is between 32,768 and 65,535, subtract 65,536 from it, and use the resulting negative number. For example, is character 36,947, so we subtract 65,536 to get -28,589 and we have \uc1\u-28589* in RTF.
If the character is over 65,535, then we can’t express it in RTF
Looks like RTF doesn't know UTF-8 at all, only Unicode in general. Other answers for Java and C# just use the \u directly.
A: I read in many places that RTF doesn't have a UTF-8 standard solution.
So, I created my own converter after scanning half the internet. If you have a standard/better solution, please let me know!
So after studying this book and I created a converter based on these character mappings. Great resources.
This solved my question. Re-using other solutions is what I would like to do for this kind of features, but I was not able to find one, alas.
The converter could be something like:
public static String convertHtmlToRtf(String html) {
String tmp = html.replaceAll("\\R", " ")
.replaceAll("\\\\", "\\\\\\\\")
.replaceAll("\\{", "\\\\{")
.replaceAll("}", "\\\\}");
tmp = tmp.replaceAll("<a\\s+target=\"_blank\"\\s+href=[\"']([^\"']+?)[\"']\\s*>([^<]+?)</a>",
"{\\\\field{\\\\*\\\\fldinst HYPERLINK \"$1\"}{\\\\fldrslt \\\\plain \\\\f2\\\\b\\\\fs20\\\\cf2 $2}}");
tmp = tmp.replaceAll("<a\\s+href=[\"']([^\"']+?)[\"']\\s*>([^<]+?)</a>",
"{\\\\field{\\\\*\\\\fldinst HYPERLINK \"$1\"}{\\\\fldrslt \\\\plain \\\\f2\\\\b\\\\fs20\\\\cf2 $2}}");
tmp = tmp.replaceAll("<h3>", "\\\\line{\\\\b\\\\fs30{");
tmp = tmp.replaceAll("</h3>", "}}\\\\line\\\\line ");
tmp = tmp.replaceAll("<b>", "{\\\\b{");
tmp = tmp.replaceAll("</b>", "}}");
tmp = tmp.replaceAll("<strong>", "{\\\\b{");
tmp = tmp.replaceAll("</strong>", "}}");
tmp = tmp.replaceAll("<i>", "{\\\\i{");
tmp = tmp.replaceAll("</i>", "}}");
tmp = tmp.replaceAll("&", "&");
tmp = tmp.replaceAll(""", "\"");
tmp = tmp.replaceAll("©", "{\\\\'a9}");
tmp = tmp.replaceAll("<", "<");
tmp = tmp.replaceAll(">", ">");
tmp = tmp.replaceAll("<br/?><br/?>", "{\\\\pard \\\\par}\\\\line ");
tmp = tmp.replaceAll("<br/?>", "\\\\line ");
tmp = tmp.replaceAll("<BR>", "\\\\line ");
tmp = tmp.replaceAll("<p[^>]*?>", "{\\\\pard ");
tmp = tmp.replaceAll("</p>", " \\\\par}\\\\line ");
tmp = convertSpecialCharsToRtfCodes(tmp);
return "{\\rtf1\\ansi\\ansicpg0\\uc0\\deff0\\deflang0\\deflangfe0\\fs20{\\fonttbl{\\f0\\fnil Tahoma;}{\\f1\\fnil Tahoma;}{\\f2\\fnil\\fcharset0 Tahoma;}}{\\colortbl;\\red0\\green0\\blue0;\\red0\\green0\\blue255;\\red0\\green255\\blue0;\\red255\\green0\\blue0;}" + tmp + "}";
}
private static String convertSpecialCharsToRtfCodes(String input) {
char[] chars = input.toCharArray();
StringBuffer sb = new StringBuffer();
int length = chars.length;
for (int i = 0; i < length; i++) {
switch (chars[i]) {
case '’':
sb.append("{\\'92}");
break;
case '`':
sb.append("{\\'60}");
break;
case '€':
sb.append("{\\'80}");
break;
case '…':
sb.append("{\\'85}");
break;
case '‘':
sb.append("{\\'91}");
break;
case '̕':
sb.append("{\\'92}");
break;
case '“':
sb.append("{\\'93}");
break;
case '”':
sb.append("{\\'94}");
break;
case '•':
sb.append("{\\'95}");
break;
case '–':
case '‒':
sb.append("{\\'96}");
break;
case '—':
sb.append("{\\'97}");
break;
case '©':
sb.append("{\\'a9}");
break;
case '«':
sb.append("{\\'ab}");
break;
case '±':
sb.append("{\\'b1}");
break;
case '„':
sb.append("\"");
break;
case '´':
sb.append("{\\'b4}");
break;
case '¸':
sb.append("{\\'b8}");
break;
case '»':
sb.append("{\\'bb}");
break;
case '½':
sb.append("{\\'bd}");
break;
case 'Ä':
sb.append("{\\'c4}");
break;
case 'È':
sb.append("{\\'c8}");
break;
case 'É':
sb.append("{\\'c9}");
break;
case 'Ë':
sb.append("{\\'cb}");
break;
case 'Ï':
sb.append("{\\'cf}");
break;
case 'Í':
sb.append("{\\'cd}");
break;
case 'Ó':
sb.append("{\\'d3}");
break;
case 'Ö':
sb.append("{\\'d6}");
break;
case 'Ü':
sb.append("{\\'dc}");
break;
case 'Ú':
sb.append("{\\'da}");
break;
case 'ß':
case 'β':
sb.append("{\\'df}");
break;
case 'à':
sb.append("{\\'e0}");
break;
case 'á':
sb.append("{\\'e1}");
break;
case 'ä':
sb.append("{\\'e4}");
break;
case 'è':
sb.append("{\\'e8}");
break;
case 'é':
sb.append("{\\'e9}");
break;
case 'ê':
sb.append("{\\'ea}");
break;
case 'ë':
sb.append("{\\'eb}");
break;
case 'ï':
sb.append("{\\'ef}");
break;
case 'í':
sb.append("{\\'ed}");
break;
case 'ò':
sb.append("{\\'f2}");
break;
case 'ó':
sb.append("{\\'f3}");
break;
case 'ö':
sb.append("{\\'f6}");
break;
case 'ú':
sb.append("{\\'fa}");
break;
case 'ü':
sb.append("{\\'fc}");
break;
default:
if( chars[i] != ' ' && isSpaceChar( chars[i])) {
System.out.print( ".");
//sb.append("{\\~}");
sb.append(" ");
} else if( chars[i] == 8218) {
System.out.println("Strange comma ... ");
sb.append(",");
} else if( chars[i] > 132) {
System.err.println( "Special code that is not translated in RTF: '" + chars[i] + "', nummer=" + (int) chars[i]);
sb.append(chars[i]);
} else {
sb.append(chars[i]);
}
}
}
return sb.toString();
} | unknown | |
d8148 | train | Ok, I've solved my problem.
My solution is to override admin/edit_inline.html template with these code:
<td class="original">
{% if inline_admin_form.original or inline_admin_form.show_url %}
<p>
{% if inline_admin_form.original %}
<a href="{% url 'admin:MyApp_product_change' inline_admin_form.original.product.id %}">
{{ inline_admin_form.original }}
</a>
{% endif %}
</p>
{% endif %}
and set the template attribute of my ModelAdmin class to corresponding url of new template.
admin.py
class MyModelInline(admin.TabularInline):
template = "admin/myapp/mymodel/edit_inline/tabular.html"
Please comment for any better solutions! Bye ;) | unknown | |
d8149 | train | Kindly select the JSON from Postman whenever you want to send the JSON data. currently, you're sending data as a text. | unknown | |
d8150 | train | You need to create a TreeStore in order to store data for a tree, and some component that can display a tree, for example a TreePanel. Try the following code, it is for Ext JS 7.3.0 Classic Material, but can be adopted to other versions:
Ext.define('myTreeStore', {
extend: 'Ext.data.TreeStore',
root: {
expanded: true
},
proxy: {
type: 'memory',
reader: {
type: 'json'
}
},
data: {
children: [{
text: 'Main 1',
leaf: true
}, {
text: 'Main 2',
children: [{
text: 'Sub 21',
leaf: true
},{
text: 'Sub 22',
leaf: true
}]
}, {
text: 'Main 3',
leaf: true
}]
}
})
Ext.application({
name: 'Fiddle',
launch: function () {
const treeStore = Ext.create('myTreeStore');
Ext.create('Ext.tree.Panel', {
rootVisible: false,
renderTo: Ext.getBody(),
title: 'Tree Example',
width: 400,
store: treeStore,
});
}
}); | unknown | |
d8151 | train | You should save any unsaved changes as soon as your app enters the background. Your app could be terminated at any point in the background without ever receiving any notifications of any kind. If your data isn't saved, it will be lost when the user restarts the app.
With regard to memory warnings, these are more likely to happen in the foreground. Once your app is in the background, it is suspended and won't get any notifications. If your app is running under iOS 5 or earlier then a memory warning could result in a view controller's viewWillUnload method being called. When that view controller needs to be displayed again, its viewDidLoad will be called again. Under iOS 6, this doesn't happen anymore. viewWillUnload is deprecated. | unknown | |
d8152 | train | This should do what you want using GROUP_CONCAT():
SELECT idedro, group_concat(color)
FROM megadb
WHERE catteniskiipotnici=1
GROUP BY idedro
ORDER BY idedro ASC
SQL Fiddle
MySQL 5.6 Schema Setup:
CREATE TABLE megadb
(`idedro` int, `color` varchar(5), `catteniskiipotnici` int)
;
INSERT INTO megadb
(`idedro`, `color`, `catteniskiipotnici`)
VALUES
(1, 'blue', 1),
(2, 'blue', 1),
(2, 'red', 1),
(3, 'blue', 1),
(3, 'red', 1),
(3, 'white', 1),
(4, 'blue', 0)
;
Query 1:
SELECT idedro, group_concat(color)
FROM megadb
WHERE catteniskiipotnici=1
GROUP BY idedro
ORDER BY idedro ASC
Results:
| idedro | group_concat(color) |
|--------|---------------------|
| 1 | blue |
| 2 | blue,red |
| 3 | blue,red,white | | unknown | |
d8153 | train | Something like this : (http://www.waymarking.com/images/cat_icons/elevationSigns.gif)
actually 24x24
A: look at this
alt text http://www.vectorportal.com/symbols/img/opengutter.gif
alt text http://t1.gstatic.com/images?q=tbn:7DqRw9FL5c9IfM%3Ahttp://media.peeron.com/ldraw/images/19/3044b.png
alt text http://t3.gstatic.com/images?q=tbn:jfs_Abjx3BnXEM:http://media.peeron.com/ldraw/images/272/50746.pngalt text http://t3.gstatic.com/images?q=tbn:L8injTgVVHLlIM%3Ahttp://media.peeron.com/ldraw/images/27/61409.png
alt text http://t1.gstatic.com/images?q=tbn:WXHlgHgon09alM:http://upload.wikimedia.org/wikipedia/commons/thumb/1/1f/Japanese_Road_sign_(Descent).svg/470px-Japanese_Road_sign_(Descent).svg.png
See also http://mutcd.fhwa.dot.gov/services/publications/fhwaop02084/index.htm
Don't forget about copyrighted © images
A: Create an icon form templates using axialis icon workshop. It is really convenient to use. As I remember there was a template. If no you can ealily import a image and edit or draw a one.
A: I don't think that's a sensible use of an icon; they're OK as visual cues to find something quickly once you've learned to recognize one, but as you have noticed, they suck at conveying actual information. Abbreviated text ("El.") would be more useful if you really lack the space for a full-length text label.
A: If it's for a plane:
alt text http://www.pekkagaiser.de/stuff/Plane.gif
Would need some re-working to look good on 22x22, though.
Plane stolen from here.
A: bullet_arrow_top from here any good:
http://www.famfamfam.com/lab/icons/silk/previews/index_abc.png
Download the set here:
http://www.famfamfam.com/lab/icons/silk/ | unknown | |
d8154 | train | It appears that this issue is fixed in Spring boot 2.0.2. So if you run into this issue upgrading might fix it (not to imply that upgrading is always a simple effort) | unknown | |
d8155 | train | To create a new form appLaunch you can use:
var appLaunch = new App();
appLaunch.Show(this);
this.Hide();
Then add this code on FormClosed event of appLaunch
private void appLaunch_FormClosed(Object sender, FormClosedEventArgs e) {
this.Owner.Show();
}
A: The hide() function just temporarily removes the form from the display.
The close() function removed the form from memory.
So if you want to go back to form1 after showing form2, just don't close form1. You could hide it, but you wouldn't have to. Just hide form2 when you're wanting to return to form1. | unknown | |
d8156 | train | I did this :)
[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];
A: Use AFHTTPClient or subclass it!
You can set default headers with -setDefaultHeader:value: like this :
[self setDefaultHeader:@"X-USER-TOKEN" value:userToken];
You can check the documentation
A: If you have a layer of abstraction, let's say APIManager,
then you should do the following inside a particular method
[[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:@"X-Register"];
A: NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue: @"X-USER-TOKEN" forHTTPHeaderField:@"< clientToken >"];
[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...] | unknown | |
d8157 | train | Hi Tamara yes I think this is a bug of the Selectize.js.
I alter the following destroy method in selectize.js
destroy: function() {
var self = this;
var selectedValue = self.$input.val();
var eventNS = self.eventNS;
var revertSettings = self.revertSettings;
self.trigger('destroy');
self.off();
self.$wrapper.remove();
self.$dropdown.remove();
self.$input
.html('')
.append(revertSettings.$children)
.removeAttr('tabindex')
.removeClass('selectized')
.attr({tabindex: revertSettings.tabindex})
.show();
self.$control_input.removeData('grow');
self.$input.removeData('selectize');
$(window).off(eventNS);
$(document).off(eventNS);
$(document.body).off(eventNS);
delete self.$input[0].selectize;
self.$input.val(selectedValue);
},
Here you can download my selectize.js file. | unknown | |
d8158 | train | 1- Create a winforms application
2- Set output type as a Console Applcation by Project/Properties/Application/Output Type
Now You have a windows application together with a console | unknown | |
d8159 | train | Because you have supplied an app.py file, it will be run to start your application. This will use the builtin Flask development server with the way the code is setup. In doing that though, you need to tell the Flask development server which port to listen on, you can't use the default port that the Flask development server users. The port is available in the OPENSHIFT_PYTHON_PORT environment variable. See:
*
*https://developers.openshift.com/managing-your-applications/environment-variables.html#informational-variables
You may also need to use OPENSHIFT_PYTHON_IP environment variable and tell the Flask development server what host interface to bind to if by default it only listens on localhost.
An alternative to all that is to rename your app.py file to wsgi.py and add:
application = app
after the Flask application object is created. By making that change then OpenShift will host the application with Apache/mod_wsgi instead and it will worry about how to host it. | unknown | |
d8160 | train | You can run brew install [email protected] && brew tap ..., but you can’t combine brew install [email protected] and brew tap ... into one brew command.
However, running brew install on a formula from a tap you don’t have automatically taps the latter:
brew install org/tap/thing
Is equivalent to:
brew tap org/tap
brew install org/tap/thing
Where org/tap is the GitHub repository https://github.com/org/tap.
This means that if you want to install [email protected] as well as some other formula from that tap, you can run a command like this:
brew install [email protected] org/firsttimesetup/xyz
Which is equivalent to:
brew tap org/firsttimesetup
brew install [email protected] org/firsttimesetup/xyz | unknown | |
d8161 | train | Unfortunately this seems to be business as usual with gmail. Their spam filter seems entirely arbitrary and uncontrollable by recipients - for example adding addresses to your address book, marking messages as "not spam", or repeatedly moving messages from spam to your inbox does not help, and nor does following their guidelines, which include implementing measures such as SPF, DKIM and DMARC, just as you've done. On my own gmail account, I often find messages sent to myself end up in spam!
Their postmaster tools are also broken - this is supposed to provide a feedback mechanism that allows server admins to see why IPs or domains are being blocked or spam filtered, however, it doesn't work properly, and it's very common to see domains & IPs marked as "bad" despite having zero spam reports. There is also no support available for postmaster tools, so you can't even report such problems. It might be worth trying anyway just see what they think of you.
In short, you are entirely at google's mercy - even if you're doing everything that they ask, your messages may still get spam filtered, and you have no recourse. | unknown | |
d8162 | train | I don't believe that IBM's documentation says this explicitly, but I don't think @GetField works in column value formulas. The doc says that it works in the "current document", and there is no current document when the formula is executing in a view.
Assuming you know what the maximum number for N is, the way to do this is with a simple list:
ChecklistContact_1 : ChecklistContact_2 : ChecklistContact_3 : ... : ChecklistContact_N
If N is large, this will be a lot of typing, but you'll only have to do it once and copying and pasting and editing the numbers will make it go pretty quickly.
A: It might sound inelegant but, if you can, create a new computed field with your column formula in your form and then use that new field in your column. Also, from a performance standpoint you will be better off.
A: Maybe use your loop to create the list of fieldnames as Richard suggested, then display tNames | unknown | |
d8163 | train | It is the cosine distance, not the cosine similarity. A basic requirement for a function d(u, v) to be a distance is that d(u, u) = 0.
See the definition of the formula in the docstring of scipy.spatial.distance.cosine, and notice that the formula begins 1 - (...). Your expectation of the function is probably based on the quantity in (...), but that expression is the cosine similarity. | unknown | |
d8164 | train | Remove the renderTo from it, add region: 'center', remove height and remove width. The Region can't adjust when you define this. You are also writing reion: 'west'. | unknown | |
d8165 | train | One architecture tip -- use a simple executable and a scheduled task rather than write a service. You don't need to worry about memory leakage over months then.
You could probably implement this without writing any code -- you can script ftp.exe pretty effectively. I'd just script it to push all the files, and then, presuming FTP.EXE exited with 0, to clean out the uploads folder and rinse and repeat. | unknown | |
d8166 | train | How about something like:
var newFiles = from f in files
join c in companies on f.CompanyId equals c.CompanyId
select new File
{
prop1 = f.prop1,
//Assign all your other properties
Company = c
}; | unknown | |
d8167 | train | You're stepping into a whole field of interesting approaches to this problem. Terms to Google are binary space partitioning, quadtrees, ... and of course nearest neighbour search.
A relatively simple but effective approach when the dots are far more spread than what their "visible range" is:
*
*Select a value "grid size".
*Create a map from grid coordinates to a list/set of entities
*For each food source: put them in the map at their grid coordinates
*For each dot: put them in the map at their grid coordinates and also in the neighbour grid "cells". The size of the neighbourhood depends on the grid size and the dot's sight value
*For each entry in the map which contains at least one dot: Either do this algorithm recursively with a smaller grid size or use the brute force approach: check each dot in that grid cell against each food source in that grid cell.
This is a linear algorithm, compared with the quadratic brute force approach.
Calculation of grid coordinates: grid_x = int(x / grid_size) ... same for other coordinate.
Neighbourhood: steps = ceil(sight_value / grid_size) .. the neighbourhood is a square with side length 2×steps + 1 centred at the dot's grid coordinates
A: I believe your approach is incorrect. This can be mathematically verified. What you can do instead is calculate the magnitude of the vector joining the dot with the food source by means of Pythagoras theorem, and ensure that this magnitude is less than the observation limit. This deals exclusively with determining relative distance, as defined by the Cartesian co-ordinate system, and the standard unit of measurement. In relation to efficiency concerns, the first order of business is to determine if the approach to be taken is in computational terms in actuality less efficient, as measured by time, even though the logical component responsible for certain calculations are, in virtue of this alternative implementation, less time consuming. Of coarse, the ideal is one in which the time taken is decreased, and not merely numerically contained by means of refactoring.
Now, if it is the case that the position of a dot can be specified as any two numbers one may choose, this of course implies a frame of reference called the basis, and also one local to the dot in question. With respect to both, one can quantify position, and other such characteristics and properties. As a consequence of this observation, it would seem that you need n*2 data structures, where n is the amount of dots in the environment, that
contain the sorted values relative to each dot, and quite frankly it is unclear whether or not this approach would even work or is optimal. You state the design and programmatic constraint that the solution shall not compute the distances from each dot to each food source. But to achieve this, one must implement other such procedures, in order that we derive the correct results. These comments are made in relation to my discussion on efficiency. Therefore, you may be better of simply calculating the distance in each case. This is somewhat elegant. | unknown | |
d8168 | train | The log that tells the story is: "/management/info has an empty filter list" because it is explicitly marked as ignored (/info is always supposed to be available). Try one of the other actuator endpoints and see if those behave as you expect. If you really need to secure the info endpoint you can set endpoints.info.sensitive=true (I think). | unknown | |
d8169 | train | configure is an instance method of the Authentication class.
Either make configure static, or export an instance of Authentication. | unknown | |
d8170 | train | The theme editor is intended to be used as a customization tool for the site administrator, not for the theme developer.
A theme may provide configuration for the theme editor - what colors can be changed, etc.
For the deep customization of how the site looks you can create you own theme with your own CSS code.
Check out this guide on how to create your custom theme - http://docs.cs-cart.com/4.3.x/designer_guide/theme_tutorial/index.html
Also there is an official Bootstrap 3 theme for CS-Cart which can be easily customized - https://github.com/cscart/cscart-boilerplate#the-cs-cart-boilerplate-theme
A: You are not limited, you have all the tools that you need to develop as you desire, the responsive theme is the base because this theme was tested enough so far and have good feedback and for somebody to start from scratch will take to much time and until you finish CS-Cart will do a big change and you will need to do another work ;)
Please check https://www.ambientlounge.ie and let me know if you find any limitations here :D
A: It's very easy modift cs-cart theme, cs-cart theme base on bootstrap and and smarty engine, firt you need looking for "index.tpl", "common/script.tpl", "common/style.tpl", "view/block_manager/render/grid.tpl || container.tpl || block.tpl || location.tpl. and you will understand cs-cart theme structure
You need to know smarty engine syntax here http://www.smarty.net/documentation
and cs-cart developer doc here http://docs.cs-cart.com/4.3.x/#designer-guide | unknown | |
d8171 | train | #navigation ul li ul {
position:absolute;
min-width:100%;
height:40px;
margin:0px;
padding:0px;
left:0px;
top:40px;
}
#navigation ul li ul li {
float:left;
height:40px;
display:block;
padding-left:15px;
padding-right:15px;
}
You have to set the min-width of the submenus ul tag to 100% or same width as the page. Then its left:0px; Then the top is 40px or same as the parent menu height. | unknown | |
d8172 | train | The way I see it, there is only "no semantic difference" if you assume that the singleton is implemented using a static reference to the single instance. The thing is, static is just one way to implement a singleton — it's an implementation detail. You can implement singletons other ways, too.
A: There is no difference really (besides initialization blocks mentioned already). But on the other hand you are not really gaining anything also. You still need to take thread safety into consideration and you still need to make sure you have only one instance of your singleton at a time. The only difference would be if you wanted to publish that member via a public static method. But why on earth would you want to do that - I have no idea.
For me personally it would also be a bit of a "code smell". I mean someone made a singleton and still declared its member as static? What does it tell me? Is there something I don't know? Or maybe there's something wrong with the implementation and it has to be static (but why?!). But I'm a bit paranoid. From what I am also aware of there are no performance reasons why this would be a good option.
A: I'm not sure what you are looking for, so I'll write something and see what you have to say.
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private double weight; // in pounds
private Elvis() { weight = 300.; } // inaccessible
public static Elvis getInstance() { return INSTANCE; }
public double getWeight() { return weight; }
public void setWeight(double weight) { this.weight = weight; }
}
Since there is only one Elvis, you could have made weight a static variable (with static getter and setter). If you make all variables static, then there is no point in defining a singleton INSTANCE since you just have a class with only static variables and methods:
public class Elvis {
private static double weight; // in pounds
static { weight = 300.; } // Could just have set the weight directly above,
// but a static block might be useful for more complex examples.
public static double getWeight() { return weight; }
public static void setWeight(double weight) { this.weight = weight; }
}
I guess this should be avoided since it looks more like a header file in C than OO.
Some might have recognized the Elvis reference from J. Bloch "Effective Java". The recommendation in that book is to implement the singleton pattern with an enum with one member:
public enum Elvis {
INSTANCE;
private double weight = 300.;
public double getWeight() { return weight; }
public void setWeight(double weight) { this.weight = weigth; }
}
Note that it looks somewhat non-standard here with the varying weight since you usually expect enum instances to be immutable.
A: There are differences, though.
For instance, you can't use a static block to initialize the former.
A: Probably it is better to implement it in the singleton, since that way you can override the singleton for tests and similar. Also, you keep your static state in a single place. | unknown | |
d8173 | train | Maya won't ship with pyqt and you need to build your own version of pyqt for maya with mayapy. You local install of pyqt won't get loaded to maya so need to compile your version yourself. This link will give a insight of that http://justinfx.com/2011/11/09/installing-pyqt4-for-maya-2012-osx/. Although maya 2017 shipping with PySide2 and you can always use Pyside rather than pyqt.
like
from PySide2 import QtWidgets
Hope this helps.
A: If you want your scripts and UIs to work on either Maya 2016 or 2017 and above, I would suggest using the Qt.py package from Marcus Ottoson.
You can find it here.
You can just install it somewhere on your computer and add its path to the 'path' variable in your environment variables, you can then just do:
from Qt import QtWidgets, QtCore, QtGui
You can then write your UIs as you would in PySide2, and they will work on all versions of Maya because Qt.py is just a wrapper choosing the proper binding available on your machine, whether it is Pyside, Pyside2, Qt5, Qt4. | unknown | |
d8174 | train | It looks like you just forgot a set of parentheses for your "win.fill()" function. Instead of:
win.fill(255, 255, 255)
the program needs:
win.fill((255, 255, 255))
That function is actually wanting a single three-color tuple value.
When I made that change, the window appeared.
Hope that helps.
Regards. | unknown | |
d8175 | train | 1- Drag a scrollView behind it and hook it's leading , trailing , top and bottom to superView
2- Copy that view you want to make it scroll-bale , paste it inside the scrollview with L,T,T,B constraints to the scrollView and Equal width to top outer view
BTW: You can also use embed from
Editor -> EmbedIn -> scrollView
Note: this won't break inner constraints of the view , but you will lose only the constraints of the view itself | unknown | |
d8176 | train | If you are using Classifier, the dataset need to return in the format x0, x1, ... xk, y where x0, x1, ... xk will be fed into the predictor (in this case it is AutoEncoder class), and its output value y_pred and actual y is used for loss calculation specified by lossfun.
In your case the answer y is also same with input. I think you can write following to return x and y which is actually same:
def get_example(self, i):
return self.Images[i], self.Images[i] | unknown | |
d8177 | train | When you create the file foo.py, you create a python module. When you do import foo, Python evaluates that file and places any variables, functions and classes it defines into a module object, which it assigns to the name foo.
# foo.py
x = 1
def foo():
print 'foo'
>>> import foo
>>> type(foo)
<type 'module'>
>>> foo.x
1
>>> foo.foo()
foo
When you create the directory bar with an __init__.py file, you create a python package. When you do import bar, Python evaluates the __init__.py file and places any variables, functions and classes it defines into a module object, which it assigns to the name bar.
# bar/__init__.py
y = 2
def bar():
print 'bar'
>>> import bar
>>> type(bar)
<type 'module'>
>>> bar.y
2
>>> bar.bar()
bar
When you create python modules inside a python package (that is, files ending with .py inside directory containing __init__.py), you must import these modules via this package:
>>> # place foo.py in bar/
>>> import foo
Traceback (most recent call last):
...
ImportError: No module named foo
>>> import bar.foo
>>> bar.foo.x
1
>>> bar.foo.foo()
foo
Now, assuming your project structure is:
main.py
DataFunctions/
__init__.py
CashAMDSale.py
def AMDSale(): ...
GetValidAMD.py
def ValidAMD(GetValidAMD): ...
your main script can import DataFunctions.CashAMDSale and use DataFunctions.CashAMDSale.AMDSale(), and import DataFunctions.GetValidAMD and use DataFunctions.GetValidAMD.ValidAMD().
A: DataFunctions is a folder, which means it is a package and must contain an __init__.py file for python to recognise it as such.
when you import * from a package, you do not automatically import all it's modules. This is documented in the docs
so for your code to work, you either need to explicitly import the modules you need:
import DataFunctions.GetValidAMD
or you need to add the following to the __init__.py of DataFunctions:
__all__ = ["GetValidAMD"]
then you can import * from the package and everything listen in __all__ will be imported
A: Check out this.
It's the same problem. You are importing DataFunctions which is a module. I expct there to be a class called DataFunctions in that module which needs to be imported with
from DataFunctions import DataFunctions
...
AMDInstance = DataFunctions.GetValidAMD() | unknown | |
d8178 | train | For anyone who hits this issue, I did the following...
Future<List<Attendee>> callLogin() async {
return http.get(
"http://www.somesite.com")
.then((response) {
try {
List<Attendee> l = new List();
// final Map<String, dynamic> responseJson = // REPLACED
final dynamic responseJson = // <<== REMOVED CAST to Map<String, dynamic>
//
json.decode(response.body)['attendees'];
responseJson.forEach((f) => l.add(new Attendee.fromJson(f)));
return l;
} catch (e) {
print(e); // Just print the error, for SO
}
});
Normally I don't attempt to answer my own questions. And, in this case I still do not have a true answer why Flutter acts differently than running the code from the Dart main. I am running them both from Android Studio. So, I would assume that Dart, in both cases would be the same version. But, that is where I am looking next. I will post if I have more information. | unknown | |
d8179 | train | Use this:
StringBuilder u = new StringBuilder();
u.append("geo:0,0?q=");
u.append("Pizza, Texas");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(u.toString()));
startActivity(mapIntent);
Or copy paste the maps.google.com url in this snippet to goto the browser:
Intent browseIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( YOUR-URL-HERE ));
startActivity(browseIntent);
A: do like this
private WebView _webView;
_webView = (WebView)_yourrelativelayourSrc.findViewById(R.id.layout_webview);
_webView.getSettings().setJavaScriptEnabled(true);
_webView.getSettings().setBuiltInZoomControls(true);
_webView.getSettings().setSupportZoom(true);
_webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
((Activity) activity).setProgress(progress * 1000);
}
});
// to handle its own URL requests :
_webView.setWebViewClient(new MyWebViewClient());
_webView.loadUrl("http://maps.google.com/maps?q=Pizza,texas&ui=maps");
A: private static final String latitude = "12.292037";
private static final String longitude = "76.641601";
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com/maps?q="+latitude+","+longitude); | unknown | |
d8180 | train | Since this question got no attention I wanted to post my solution in case others run across this.
So, I ended up not using this gem and just writing the methods myself. The reason being that this gem was written specifically for Ruby, not for Rails. Other users got the same error as I did and the only resolution was to hack actual code in the gem if you were using this on a Rails site.
So, the solution, at least for now would be to not use this gem for Rails, only for purely Ruby. The author I believe states this plainly but something I overlooked.
Thanks! | unknown | |
d8181 | train | I assume you know about android data binding and you're just asking how to do it for this specific case. If not, here is the android data binding guide.
You will need a way to observe the boolean value so the UI can remain updated. The easiest way is to make it an ObservableBoolean field of your model object:
public class ViewModel {
public final ObservableBoolean isWifiConnected = new ObservableBoolean();
// other things you want to bind to your layout...
}
When you create the binding, you must also assign the model:
public void onCreate(Bundle icicle) {
ActivityMainBinding binding =
DataBindingUtil.setContentView(this, R.layout.activity_main);
this.model = new ViewModel();
binding.setModel(this.model);
}
And when you receive the broadcast, you update the model:
wifiScanReceiver = new BroadcastReceiver() {
//...
model.isWifiConnected.set(newValue);
//...
};
And your layout would be something like this:
<layout ...>
<data>
<variable name="model" type="com.example.ViewModel"/>
</data>
<!-- rest of layout -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@{model.isWifiConnected ? @drawable/xxx : @drawable/yyy}"/>
</layout>
You could also avoid the model class if you keep track of the binding and set the variable directly on it. In that case, you'd have a variable:
<variable name="isWifiConnected" type="boolean"/>
And your broadcast receiver would set the value:
binding.setIsWifiConnected(newValue); | unknown | |
d8182 | train | You have assigned a integer value to that variable.
Using type() will tell you what data type you have.
I.E: type(two_days_in_a_row) --> returns int
A: Don't confuse, Check below data types in python
two_days_in_a_row = 0
type(two_days_in_a_row): int
two_days_in_a_row = []
type(two_days_in_a_row): list
two_days_in_a_row = None
type(two_days_in_a_row): NoneType
two_days_in_a_row = ""
type(two_days_in_a_row): str
two_days_in_a_row = {}
type(two_days_in_a_row): dict
two_days_in_a_row = ()
type(two_days_in_a_row): tuple
two_days_in_a_row = 0.0
type(two_days_in_a_row): float
two_days_in_a_row = 2+3j
type(two_days_in_a_row): complex
two_days_in_a_row = True
type(two_days_in_a_row): bool | unknown | |
d8183 | train | get help from ?clusplot.default(), you can get more information,
you just need add a synatx in your command like this :
clusplot(data, myclus$cluster, color=TRUE, shade=TRUE, labels=2, lines=0, plotchar=FALSE),
the points will be represented as same shapes on your plot ! | unknown | |
d8184 | train | I think you can open you html file in Chrome. Then print it to pdf format. Then it will works.
That is when you print it, you choose "save as pdf" rather than your printer. | unknown | |
d8185 | train | u'blablabla' is Unicode. You can convert it into string using str(unicode)
Example:
a = [[u'qweqwe'],[u'asdasd']]
str(a[0][0]) will be string qweqwe.
Now you can write it into file as usual.
Try this example for clarity:
a = [[u'qweqwe'],[u'asdasd']]
print type(a[0][0])
print type(str(a[0][0]))
Output:
<type 'unicode'>
<type 'str'>
A: Firstly, Given that you have a list of lists, I am going to assume that you are going to convert the given list from unicode to an UTF8 string. For this lets have a function convertList which takes a list of lists as an input
So your initial value for l would be
[[u'Sentence 1 blabla.'],
[u'Sentence 2 blabla.'],
...]
Notice that this is a list of lists. Now for each list item, loop through the items within that list and convert them all to UTF8.
def convertList(l):
newlist = []
for x in l:
templ = [item.encode('UTF8') for item in x]
newlist.append(templ)
return newlist
l = [[u'Sentence 1 blabla.'], [u'Sentence 2 blabla.']]
l = convertList(l) # This updates the object you have
# Now do the filewrite operations here.
f = open('myfile.txt','w')
for iList in l:
for items in iList:
f.write(items+'\n')
f.close()
This will write to the file myfile.txt as follows
Sentence 1 blabla.
Sentence 2 blabla. | unknown | |
d8186 | train | *
*You can check the Azure DevOps server growth using continuous monitoring by application insights
*You can set the alert rules using the below sample CLI script
To modify alert rule settings:
In the left pane of the release pipeline page, select Configure Application Insights Alerts.
$subscription = az account show --query "id";$subscription.Trim("`"");$resource="/subscriptions/$subscription/resourcegroups/"+"$(Parameters.AppInsightsResourceGroupName)"+"/providers/microsoft.insights/components/" + "$(Parameters.ApplicationInsightsResourceName)";
az monitor metrics alert create -n 'Availability_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'avg availabilityResults/availabilityPercentage < 99' --description "created from Azure DevOps";
az monitor metrics alert create -n 'FailedRequests_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'count requests/failed > 5' --description "created from Azure DevOps";
az monitor metrics alert create -n 'ServerResponseTime_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'avg requests/duration > 5' --description "created from Azure DevOps";
az monitor metrics alert create -n 'ServerExceptions_$(Release.DefinitionName)' -g $(Parameters.AppInsightsResourceGroupName) --scopes $resource --condition 'count exceptions/server > 5' --description "created from Azure DevOps";
*
*You can modify the script and add additional rules, and you can even modify alert conditions. or you can even remove alert rules which you don't require | unknown | |
d8187 | train | The previous answer contains several little mistakes
tiles.xml
<definition name="main" template="/WEB-INF/jsp/template.jsp">
<put-attribute name="titleKey" value="main.title" />
<put-attribute name="body" value="/WEB-INF/jsp/main.jsp" />
</definition>
jsp (/WEB-INF/jsp/template.jsp)
<c:set var="titleKey"><tiles:getAsString name="titleKey"/></c:set>
<title><spring:message code="${titleKey}"></spring:message> </title>
A: Did you ever tried to put the message key in you tiles variable and use it as key for the spring message tag.
Something like that:
<definition name="welcome.page" extends="main.page">
<put-attribute name="titleKey" value="page.main.title"/>
<put-attribute name="body" value="/pages/welcome.jsp"/>
</definition>
jsp:
<set var"titleKey"><tiles:getAsString name="titleKey"/></set>
<title><spring:message code=${titleKey} /></title> | unknown | |
d8188 | train | Once a thread issues a blocking system call (any request to IO) it is suspended, and only marked as "Ready" (not yet running) when that system call completes.
So yes it will be preempted immediately. | unknown | |
d8189 | train | At first create a Batchfile with the following content:
@echo off
set newpath=H:/testing
set filename=%*
move %filename% %newpath%
set txtfilename=%filename:~0,-3%txt
echo.content of textfile >%txtfilename%
where insteadof the H:/testing you put the new path of your files,
and instead of the "content of textfile" you write what shall be in the textfiles created at the old location of the files.
it does not matter where you create the batch file, because in the next step you go to the search bar and type in shell:sendto and open the folder,
where you create a shortcut to your batchfile.
You can now send files to your batchfile over the "send to" menue,
and the batch file copies the file to the specified path and leaves a text file with the desired content where the moved file once was.
Edit: if you want to use it on files with varying number of characters in the ending, the code has to be modified to
@echo off
setlocal enabledelayedexpansion
set newpath=H:/testing
set filename=%*
move %filename% %newpath%
set ending=%filename:*.=%
set txtfilename=!filename:%ending%=!.txt
echo.content of textfile >%txtfilename%
but in this case you can't have dots or file-endings in the names of your folders or leaving the textfile wont work properly. | unknown | |
d8190 | train | I'm assuming, you are asking for source dataset. For Sink dataset as well, it will follow same steps but you will have to do the same things in "Sink" tab.
Here, I'm doing it for "Source".
*
*Take array as parameter (outside of all activities that means it is a pipeline parameter).
*Choose "Add dynamic content"
*Choose pipeline array parameter "test_param", for which "ForEach" activity will run and click finish.
*Add New source dataset "test_Parquet" using "+" symbol.
*Go to Source dataset "test_Parquet" -> Parameters and add new parameter,<here I've added "param" with datatype String>
*After adding that, return to "Copy activity" and you will see "param (your parameter)" under "DataSet Properties":
*Click on "add dynamic content" and add "pipeline array parameter element" to the dataset parameter value.
*Click on "ForEach iterator -> current item" and click Finish.
This process will add the pipeline array parameter elements to Copy Activity source dataset. | unknown | |
d8191 | train | User setup for Windows
Announced last release, the user setup package for Windows is now available on stable. Installing the user setup does not require Administrator privileges as the location will be under your user Local AppData (LOCALAPPDATA) folder. User setup also provides a smoother background update experience.
Download User Setup
If you are a current user of the system-wide Windows setup, you will be prompted to install user setup, which we recommend using from now on. Don't worry, all your settings and extensions will be kept during the transition. During installation, you will also be prompted to uninstall the system-wide setup.
Reference: https://code.visualstudio.com/updates/v1_26#_user-setup-for-windows
A: I installed the user version side-by-side with the system version with no problems. The basic differences between the two is that the system version installs on the file system like every other app. The user install is basically a click-once (or web installer) version that installs in the User folder of the machine.
The settings made to VS Code in the system version save for Everybody on the computer and the user version the settings are only for the user. I find that the behavior of the user version is a bit annoying for me because I have reasons to want to open multiple copies of VS Code at the same time and the user version only allows one instance. Otherwise, there's not really anything different between the two as far as I can tell.
A: Many companies (like mine) dont allow Admin privileges, I think that's the main point so you can still install VSC with the user installer
A: After user version of Visual Studio Code is downloaded, make cmd in the download folder and run a command below, replacing the correct version in the VS ode installation file name:
runas /trustlevel:0x20000 ./VSCodeUserSetup-x64-1.74.3.exe
start the command below in order to check which trust levels are supported:
runas /showtrustlevels | unknown | |
d8192 | train | That is not the way how Ext.define should look like. Either configure the window directly (inline) or use initComponent. Inline configuration:
Ext.define('mine.nameCreationPopup',{
extend: 'Ext.Window',
alias: 'widget.nameCreationPopup',
title: 'aTitle',
width: 700,
height: 300, //ignored from now on
layout: 'fit',
bodyStyle: 'padding:5px;',
modal: true,
resizable: false
});
initComponent:
Ext.define('mine.nameCreationPopup',{
extend: 'Ext.Window',
alias: 'widget.nameCreationPopup',
initComponent:function() {
Ext.applyIf(this, {
title: 'aTitle',
width: 700,
height: 300, //ignored from now on
layout: 'fit',
bodyStyle: 'padding:5px;',
modal: true,
resizable: false
});
this.callParent(arguments);
}
}); | unknown | |
d8193 | train | You can use a python library called scipy which has functions that can produce graphs | unknown | |
d8194 | train | Your GetItems looks fine to me. You could also do:
public IQueryable<Item> GetItems(int folderID)
{
return this.Context.FolderItems
.Where(fi => fi.ID == folderID)
.Select(fi => fi.Items);
}
Both should return the same thing.
A: You can have the parent entity contain the child entities. There are 2 things you have to do to do this:
1) Update your domain query to include the folder items and items:
return from x in Context.FolderItems
.Include("FolderItem")
.Include("FolderItem.Item")
where x.ID == folderID
select x
2) Update the metadata file so that the RIA service knows to return the associations to the client:
[MetadataTypeAttribute(typeof(FolderMetadata))]
public partial class Folder
{
internal sealed class FolderMetadata
{
...
[Include]
public FolderItem FolderItem;
}
} | unknown | |
d8195 | train | I had to create a credential file for Analytics API too and faced the same lack of informations.
I had no choice and used the new google Cloud Dashboard, you have to create an application, select the API you want, then Google provide you a valid credentials file.
My file looked like this :
{
"type": "service_account",
"project_id": "***",
"private_key_id": "***",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANB***xmw0Fcs=\n-----END PRIVATE KEY-----\n",
"client_email": "***",
"client_id": "***",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "***"
}
That's why i'm pretty sure you have to do the same with translate API, first declaration "type": "service_account", match with the error you get. | unknown | |
d8196 | train | You can use table() to get the absolute frequencies and then use prop.table() to get the probabilities. If you are only interested in a specific value like "M", you can just index that value.
# sample data
studenti <- data.frame(sesso = sample(c("M", "F", NA), 100, replace = TRUE))
# all probabilties
prop.table(table(studenti$sesso))
#>
#> F M
#> 0.530303 0.469697
# specfic probability
prop.table(table(studenti$sesso))["M"]
#> M
#> 0.469697
Created on 2021-10-06 by the reprex package (v2.0.1)
A: You could create a function
#Function
propCond=function(VAR,MODALITY){
PROP=sum(VAR==MODALITY,na.rm=TRUE)/sum(!is.na(VAR),na.rm=TRUE)
return(PROP)
}
#Result
propCond(c("a","a","b"),"a") | unknown | |
d8197 | train | This is a bit of speculation based on the information you have provided:
You probably don't have the <context:property-placeholder.. in your Root Web Application context - the one loaded by ContextLoaderListener, instead you may be having it in the web context(loaded by Dispatcher servlet). Can you please confirm this.
Update: Based on the comment, the issue seems to have been that the <context:propert-placeholder.. was defined in the Root Web application context, but being referred to in a component from Web Context.
The fix is to move the propertyplaceholder to the web context (one defined through MessageDispatcherServlet) in this case.
A: EDIT :
Did you try using setter method with #{expirationOffset} ??
i.e. :
private String propertyValue;
@Value("#{expirationOffset}")
public void setPropertyValue(String property) {
propertyValue = property;
}
Another Option :
Add Properties bean instead of PropertyPlaceConfigurer like this :
<util:properties id="myProps" location="file:///C:/temp/application.properties" />
OR
<util:properties id="myProps" location="classpath:application.properties" />
And Replace Setter with a slight modification as
private String propertyValue;
@Value("#{myProps.expirationOffset}")
public void setPropertyValue(String property) {
propertyValue = property;
}
You'll have to add xmlns:util="http://www.springframework.org/schema/util" to xmlns decalrations and correcsponding http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd to xsi:schemalocation in your context configuration xml.
This should definitely work.!
Hope it Helps. :) | unknown | |
d8198 | train | You should return only the hours you need and then loop for the dropdownlist creation:
DATEPART(hh,yourdate) will return the hours for your datetime value:
<cfquery name="doctorHours" datasource="#ds#">
SELECT doctorID,DATEPART(hh,openTime) As OpenHours, DATEPART(hh,closetime) As CloseHours
FROM doctorHours
WHERE day = #CountVar#
AND doctorID='#docID#'
</cfquery>
ValueList will transform your query results into a list:
<cfset openTimesList = ValueList(doctorHours.OpenHours) />
<cfset closeTimesList = ValueList(doctorHours.CloseHours ) />
ListContains will return the index of the value within your list:
<select id="openHours#CountVar#" name="openHours#CountVar#">
<cfloop from="0" to="23" index="OpenHours">
<option value="#openHours#"
<cfif ListContains(openTimesList,OpenHours) NEQ 0 >
selected="selected"
</cfif>
>#OpenHours#</option>
</cfloop>
</select>
You can use the same strategy for the closeTimesList.
A: Hmmm....the number of values displayed in the code above will be equivelant to the number of records returned by the query X 23. If you're query returns 2 records you will see 46 options and so on. It seems like you believe the query has only 1 record. I would suggest perhaps it has more.
Try LIMIT 1 or TOP 1 in your query - or use Maxrows (as suggested in the comments)... but make sure you know what you are including and what you are excluding. You need to know why your query is not what you expect :) | unknown | |
d8199 | train | The poster that voted to close this question was not correct and didn't provide help towards a solution. The duplicate thread only provided part of the solution, which is not useful in this case.
In the end I resolved it the following way:
hexerre = re.sub("(.{80})", "\1\n\t\t\t\t\t\t\t", hexer, 0)
By adding the tabs into the regex expression I was able to get the indentation needed. | unknown | |
d8200 | train | Make sure that your android version supports OpenGL ES 2.0 rendering on it's background state. Because whenever you press the home key app enters background state and gives background thread for your application, that may cause crashes. Mostly in iOS and android it is best to identify the app state and pause the rendering in background state. Refer further in this link Run Android OpenGL in Background as Rendering Resource for App?
A: I found out that I needed to override the 'onSurfaceDestroyed( SurfaceHandle handle) method in the class that extends GLSurfaceView and clean up my resources.
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
super.surfaceDestroyed(holder);
ResourceManager.getInstance().cleanUp();
} | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.