_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d1901 | train | You can change your observable definition to:
Observable<Object> observable = observable();
observable.flatMapSingle(id -> {
return rxSend(VERTICLE_1_ADDRESS, id).flatMap(i -> {
// Logic dependent on if item was found
// id is visible here
});
}).subscribe();
Then the id will be visible to your second lambda. | unknown | |
d1902 | train | personally i would use yaml. it's on par with json for encoding size, but it can represent some more complex things (e.g. classes, recursive structures) when necessary.
In [1]: import yaml
In [2]: x = [1, 2, 3, 'pants']
In [3]: print(yaml.dump(x))
[1, 2, 3, pants]
In [4]: y = yaml.load('[1, 2, 3, pants]')
In [5]: y
Out[5]: [1, 2, 3, 'pants']
A: Maybe you're not using the right protocol:
>>> import pickle
>>> a = range(1, 100)
>>> len(pickle.dumps(a))
492
>>> len(pickle.dumps(a, pickle.HIGHEST_PROTOCOL))
206
See the documentation for pickle data formats.
A: If you need a space efficient solution you can use Google Protocol buffers.
Protocol buffers - Encoding
Protocol buffers - Python Tutorial
A: Take a look at json, at least the generated dumps are readable with many other languages.
JSON (JavaScript Object Notation) http://json.org is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
A: There are some persistence builtins mentioned in the python documentation but I don't think any of these is remarkable smaller in the produced filesize.
You could alway use the configparser but there you only get string, int, float, bool.
A: "the byte overhead is significant"
Why does this matter? It does the job. If you're running low on disk space, I'd be glad to sell you a 1Tb for $500.
Have you run it? Is performance a problem? Can you demonstrate that the performance of serialization is the problem?
"I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?"
Nothing simpler than repr and eval.
What's wrong with eval?
Is is the "someone could insert malicious code into the file where I serialized my lists" issue?
Who -- specifically -- is going to find and edit this file to put in malicious code? Anything you do to secure this (i.e., encryption) removes "simple" from it.
A: Luckily there is solution which uses COMPRESSION, and solves
the general problem involving any arbitrary Python object
including new classes. Rather than micro-manage mere
tuples sometimes it's better to use a DRY tool.
Your code will be more crisp and readily refactored
in similar future situations.
y_serial.py module :: warehouse Python objects with SQLite
"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."
http://yserial.sourceforge.net
[If you are still concerned, why not stick those tuples in
a dictionary, then apply y_serial to the dictionary.
Probably any overhead will vanish due to the transparent
compression in the background by zlib.]
As to readability, the documentation also gives details on
why cPickle was selected over json. | unknown | |
d1903 | train | I think there is agreement that, for interactive usage, this behavior is not optimal and it is likely going to change to the expected behavior in the REPL, IJulia etcetera soon. You can find the discussion here: https://github.com/JuliaLang/julia/issues/28789
Note, however, that everything works as expected once you wrap it into a local scope, such as a function or a let block for example.
See my answer here: Scope of variables in Julia for some more information/references. | unknown | |
d1904 | train | I found that MenuItemCompat.setOnActionExpandListener(...) is not working if you don't pass:
searchItem
.setShowAsAction(MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
| MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
But this is changing the SearchView and is replacing the DrawerToggle with back arrow.
I wanted to keep the original views and still track the Expanded/Collapsed state and use supported Search View.
Solution:
When android.support.v7.widget.SearchView is changing the view state the LinearLayout view's, with id android.support.v7.appcompat.R.id.search_edit_frame, visibility value is being changed from View.VISIBLE to View.GONE and opposite. So I add ViewTreeObserver to track the visibility change of the search edit frame.
menu_search.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="@string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always"/>
</menu>
In the activity:
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
..........
private View mSearchEditFrame;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = (MenuItem) menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat
.getActionView(searchItem);
searchView.setSubmitButtonEnabled(false);
mSearchEditFrame = searchView
.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
int oldVisibility = -1;
@Override
public void onGlobalLayout() {
int currentVisibility = mSearchEditFrame.getVisibility();
if (currentVisibility != oldVisibility) {
if (currentVisibility == View.VISIBLE) {
Log.v(TAG, "EXPANDED");
} else {
Log.v(TAG, "COLLAPSED");
}
oldVisibility = currentVisibility;
}
}
});
return super.onCreateOptionsMenu(menu);
}
Thanks!
A: You probably missed the fact (like I did) that `MenuItemCompat.OnActionExpandListener' interface has a static implementation, and is not an instance method.
So, if you have a class that implements MenuItemCompat.OnActionExpandListener then in that class you need to install it as the listener like this:
MenuItem menuItem = menu.findItem(R.id.search);
if (menuItem != null) {
MenuItemCompat.setOnActionExpandListener(menuItem,this);
MenuItemCompat.setActionView(menuItem, mSearchView);
}
The same paradigm applies to setActionView ... rather than invoke menuItem.setActionView(this), you pass the menuItem as the first argument to the static version MenuItemCompat.setActionView and follow with the other argument(s).
A: For MenuItemCompat.setOnActionExpandListener to work you should add "collapseActionView" added in the menu item -
for example -
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
And in the onCreateOptionsMenu you can use it this way -
MenuItemCompat.setOnActionExpandListener(menu_search,
new OnActionExpandListener()
{
@Override
public boolean onMenuItemActionCollapse(MenuItem item)
{
// Do something when collapsed
return true; // Return true to collapse action view
}
@Override
public boolean onMenuItemActionExpand(MenuItem item)
{
// Do something when expanded
return true; // Return true to expand action view
}
});
A: Your Listener should be MenuItemCompat.OnActionExpandListener() .
MenuItemCompat.setOnActionExpandListener(searchItem,
new MenuItemCompat.OnActionExpandListener() {
}
A: thanks for your help,
your solution is work for me. and i'd like to vote you up, but i just realized i have only 1 reputation,(;′⌒`)
actually, my solution is similar to your, there is just one different in the menu xml file like this:
<item
android:id="@+id/apps_menu_search"
android:icon="@drawable/ic_action_search"
android:title="@string/apps_menu_search"
android:visible="true"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" /> | unknown | |
d1905 | train | You could overflow the text outside the td but you need to insert a div tag like this
<td><div>your text goes here</div></td>
See this demo | unknown | |
d1906 | train | As mentioned in "Show system files / Show git ignore in osx", use in your Finder ⌘⇧.
That should show you the hidden folder .git/, which include all the history of the repo.
And for a repo of binaries (like jpeg images), and new version of an image might take quite a lot of place (poor diff, poor compression between each version)
I wonder if there's any way I can purge this history from local storage? (I'd like to keep it in the cloud)
You would need to download only the archive of the repo (meaning the content, without the history).
If you don't need to change and push back those modification, the archive would be enough.
If you need the history, a shallow clone (git clone --depth 1) that I detailed here (or here) is best to keep the downloaded data at a minimum.
A: I would try re-indexing your hdd and see if that accurately displays file sizes once its done.
Run the following in osx terminal:
sudo mdutil -E /
Original article:
https://www.maketecheasier.com/fix-wrong-hard-drive-data-usage-calculation-osx/ | unknown | |
d1907 | train | you can use scrollview in code like this ::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="@+id/imv"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="55dip"
/>
<ImageView
android:id="@+id/imagegallery"
android:layout_width="70sp"
android:layout_height="70sp"
android:layout_alignParentRight="true"
android:layout_below="@id/imv"/>
<ProgressBar
android:id="@+id/Bar"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content"
android:layout_above="@id/imagegallery"
android:layout_below="@id/imv"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/textView1"
android:text="Art Gallery"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_below="@id/imv"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textColor="#00C000"
android:textSize="20dip"
android:text=" "
android:layout_width="wrap_content"
android:layout_toLeftOf="@id/imagegallery"
android:layout_alignParentLeft="true"
android:layout_below="@id/textView1"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/textopeningnow"
android:text="Opening Now"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_below="@id/textView2"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/diosas"
android:textSize="20dip"
android:text="Diosas/Godesses"
android:textColor="#00C000"
android:layout_width="wrap_content"
android:layout_below="@id/textopeningnow"
/>
<Button
android:id="@+id/back"
android:layout_height="wrap_content"
android:layout_width="25dip"
android:layout_centerVertical="true"
android:background="@drawable/leftarrow"/>
<Button
android:id="@+id/next"
android:layout_height="wrap_content"
android:layout_width="25dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/rightarrow"/>
<ImageView android:id="@+id/imageLoader"
android:layout_width="wrap_content"
android:layout_height="200dip"
android:layout_toLeftOf="@id/next"
android:layout_toRightOf="@id/back"
android:layout_below="@id/diosas"
/>
<TextView
android:id="@+id/artistname"
android:textColor="#000000"
android:text=" "
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="@id/imageLoader"
android:layout_centerInParent="true"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
A: I'd enclose your image in a separate RelativeLayout, and add the buttons to it. It's way too hard to try to achieve what you want with just a global relative layout. | unknown | |
d1908 | train | To double a number (which is stored in a variable named n here): (* 2 n).
To add one: (1+ n). Note that 1+ is the name of a function. It is the same as (+ n 1).
Now, let's say that you have some scope (e. g. a function body) where you have a variable named n. You now create a new variable d using let:
(let ((d (* n 2)))
…)
This new variable is in scope for the body of the let (indicated by … above).
Now we create another variable d1, which is one more. We need to use let* now, so that the scope of d is not just the body, but also the binding forms of the let*:
(let* ((d (* n 2))
(d1 (+ d 1)))
…)
The function should maybe be called child-indices:
(defun child-indices (n)
(let* ((d (* n 2))
(d1 (+ d 1)))
…))
The bodies of many forms like defun and let are so-called implicit progns, which means that these forms return the value of the last expression in their body. So, whatever forms we put into the place marked … above, the value (or values, but let's keep that aside for now) of the last is the return value of the function.
There are several ways to do a “return this and then that”, but we'll use a list for now:
(defun child-indices (n)
(let* ((d (* n 2))
(d1 (+ d 1)))
(list d d1))) | unknown | |
d1909 | train | *
*GO to your Azure Active Directory
*Click on Groups
*Click “+ New Group”
*Select the group type “Security”
*Enter group name (any name you want)
*Select Membership type “Assigned”
*In the owner select the owner of the application
*In the members select the application that you created/registered in the active directory.
*Now you are able to create your resources directly from your java client. | unknown | |
d1910 | train | Seems like there are no errors in XML fragment you shared. I know the sample you're playing with, the error caused by wrong ID resource definition in ids.xml
<item name="button" type="id">Button</item>
But according to documentaion ID definition takes no value. So the fix is:
<item name="button" type="id" /> | unknown | |
d1911 | train | The comments already have the solutions really... but to wrap some more advice around it:
Your Problem
You're just missing a space between the color and number.
General Advice
*
*Make sure everything is the same case before comparing (e.g. all lower/upper).
*Get rid of white space when handling tokens.
*Keep variables separate; card value and card color are both unique and useful, putting them back in one string makes them less useful and harder to use and can introduce errors like yours.
Recommendation
Modify findCard() to take 2 strings, one with the card value and one with the color. Also, if you're using "red 6" as a key in a map or something, either:
*
*Make sure you build "red 6" from "red" and "6" using a function that you use everywhere you do this. That way you can unit test the function and you're sure that you don't add a space in one spot and forget it in another spot. Generally anywhere where you duplicate code, you might mess up - so don't duplicate.
*Make "card" a class and override equals and hash code to use both of these values when determining equality. Then you can use card as the key in a map fine.
Also, I kind of agree with the person who said that string spit() would be easier (just because you see it more often in code). But both should work if you're comfortable; so do it your way if you're happy :). | unknown | |
d1912 | train | A char can only store 1 character not a set of characters, and by directly comparing the string to a character array won't work because of the null character
This will work , hope it helps
#include <stdio.h>
#include<string.h>
int main()
{
char name[10];
printf("Who are you? \n");
fgets(name,10,stdin);
printf("Good to meet you, %s.\n",name);
if(strcmp(name,"spyro"))
{
printf("Then you are here %s\n",name);
}
return(0);
} | unknown | |
d1913 | train | Add the admin permission to .npm home directory.
sudo chown -R $(whoami) ~/.npm | unknown | |
d1914 | train | Perhaps the clearest way is to start with the lists as CTEs:
with bases as (
select 1 as base from dual union all
select 2 as base from dual union all
select 3 as base from dual
),
lots as (
select 3 as lot from dual union all
select 4 as lot from dual union all
select 20 as lot from dual
)
select b.base, l.lot, count(Order_Base_Number) as Frequency
from bases b cross join lots l left outer join
Orders o
on o.base = b.base and o.lot = l.lot
group by b.base, l.lot
Note that this makes the cross join explicit, purposely not using the , for a Cartesian product.
The first part of this query could also be written as something like the following (assuming that each base and lot has at least one record in the table):
with bases as (
select distinct base
from Orders -- or some other table, perhaps Orders ?
where base in (1, 2, 3)
),
select distinct lot
from Orders -- or some other table, perhaps Lots ?
where lot in (3, 4, 20)
)
. . .
This is more succinct, but might result in a less efficient query.
A: What you need in the innermost subquery is called CROSS JOIN, which gets cartesian products (all possible combinations) of records. That's what you get when you have neither JOIN..ON condition nor WHERE:
SELECT Base.Id as baseid, Lot.Id as lotid FROM Bases, Lots
Now put it into subquery and LEFT JOIN to the rest of your stuff:
SELECT ... FROM
(SELECT Base.Id as baseid, Lot.Id as lotid
FROM Bases, Lots) baseslots
LEFT JOIN Orders ON Order_Base_Number = baseid,
Order_Lot_Number = lotid ....
With this LEFT JOIN, you'll get NULL for nonexistent combinations. Use COALESCE (or something like this) to turn them into 0.
A: I don't have Oracle to test it but this is what I would do:
CREATE TABLE pairs AS
(
SELECT DISTINCT Base.Order_Base_Number, Lot.Order_Lot_Number
FROM ORDERS Base
CROSS JOIN ORDERS Lot
);
CREATE TABLE counts AS
(
SELECT Order_Base_Number, Order_Lot_Number, Count(*) AS C
FROM ORDERS
GROUP BY Order_Base_Number, Order_Lot_Number
);
SELECT P.Order_Base_Number, P.Order_Lot_Number, COALESCE(C.C,0) AS [Count]
FROM Pairs P
LEFT JOIN counts C ON P.Order_Base_Number = C.Order_Base_Number
AND P.Order_Lot_Number = C.Order_Lot_Number | unknown | |
d1915 | train | In PHP use .= to append strings, and not +=.
Why does this output 0? [...] Does PHP not like += with strings?
+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.
More about operators in PHP:
*
*Reference - What does this symbol mean in PHP?
*PHP Manual – Operators
A: PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus a (.) period is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
A: This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>'; | unknown | |
d1916 | train | var obj = new
{
files = new object[]
{
"http://www.example.com/css/styles.css",
new
{
url = "http://www.example.com/cat_picture.jpg",
headers = new Dictionary<string,string>
{
{ "Origin", "cloudflare.com" },
{ "CF-IPCountry","US" },
{ "CF-Device-Type", "desktop"}
}
}
}
};
The dictionary is there because of the awkward property names like CF-IPCountry which make it not possible to use an anonymous type.
To show it working:
var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Formatting.Indented);
gives:
{
"files": [
"http://www.example.com/css/styles.css",
{
"url": "http://www.example.com/cat_picture.jpg",
"headers": {
"Origin": "cloudflare.com",
"CF-IPCountry": "US",
"CF-Device-Type": "desktop"
}
}
]
}
Edit; that's not quite right - the dictionary didn't work, but I don't have time to fix it.
A: Using classes (maybe you could use better class names then mine :) ):
class Root
{
[JsonProperty(PropertyName = "files")]
public List<object> Files { get; set; } = new List<object>();
}
class UrlContainer
{
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "headers")]
public Headers Headers { get; set; }
}
class Headers
{
public string Origin { get; set; }
[JsonProperty(PropertyName = "CF-IPCountry")]
public string CfIpCountry { get; set; }
[JsonProperty(PropertyName = "CF-Device-Type")]
public string CfDeviceType { get; set; }
}
Usage
var root = new Root();
// Add a simple url string
root.Files.Add("http://www.example.com/css/styles.css");
var urlContainer = new UrlContainer() {
Url = "http://www.example.com/cat_picture.jpg",
Headers = new Headers()
{
Origin = "cloudflare.com",
CfIpCountry = "US",
CfDeviceType = "desktop"
}
};
// Adding url with headers
root.Files.Add(urlContainer);
string json = JsonConvert.SerializeObject(root);
Note: I'm using Newtonsoft.Json | unknown | |
d1917 | train | I don't know exactly what this site is doing, but you can suggest that Facebook use a specific image (not necessarily one found on the page) by using the og:image Open Graph tag. For example, something like this would go in the <head> portion of your site:
<meta property="og:image" content="http://www.barakabits.com/wp-content/uploads/2015/01/Moroccos-faces-featured-6.jpg">
As you can see from the site you referenced, you can have multiple og:image tags, and the user will be able to choose which one is displayed in the post.
Here's Facebook's guide to Open Graph tags: https://developers.facebook.com/docs/sharing/best-practices | unknown | |
d1918 | train | Normally, you'd double the backslash:
'\\'
Use os.path.join() to join directory and filename elements, and use string formatting for the rest:
os.path.join(Id, TypeOfMachine, '{}_{}'.format(year, month),
'{}_{}_{}.csv'.format(year, month, day))
and let Python take care of using the correct directory separator for your platform for you. This has the advantage that your code becomes portable; it'll work on an OS other than Windows as well.
By using string formatting, you also take care of any non-string arguments; if year, month and day are integers, for example.
A: You can simply call the character by its ASCII code.
(I'm using Python 3.7).
Example:
In this case, the ASCII code is 92, you can use Python's chr() function to call the character
In this website you can find a list of ASCII codes for more printable characters.
The code used above:
delimiter = chr(92)
FileName = 'Id' + delimiter + 'TypeOfMachine' + delimiter + 'year' + '_' + 'month' + delimiter + 'year' + '_' + 'month' + '_' + 'day' + '.csv'
print(FileName)
Hope it helps.
A: A backslash is commonly used to escape special strings. For example:
>>> print "hi\nbye"
hi
bye
Telling Python not to count slashes as special is usually as easy as using a "raw" string, which can be written as a string literal by preceding the string with the letter 'r'.
>>> print r"hi\nbye"
hi\nbye
Even a raw string, however, cannot end with an odd number of backslashes. This makes string concatenation tough.
>>> print "hi" + r"\" + "bye"
File "<stdin>", line 1
print "hi" + r"\" + "bye"
^
SyntaxError: invalid syntax
There are several ways to work around this. The easiest is using string formatting:
>>> print r'{}\{}'.format('hi', 'bye')
hi\bye
Another way is to use a double-backslash in a regular string to escape the second backslash with the first:
>>> print 'hi' + '\\' + 'bye'
hi\bye
But all of this assumes you're facing a legitimate need to use backslashes. If all you're trying to do is construct Windows path expressions, just use os.path.join.
A: You should use os.path.join to construct the path.
e.g:
import os
path = os.path.join(Id, TypeOfMachine, year + '_' + month, year + '_' + month + '_' + day + '.csv')
or if you insist on using backslashes, you need to escape them: as, so '\\'
A: Without importing os.path module you could simply do:
my_path = '\\'.join([Id,TypeOfMachine, year + '_' + month, year + '_' + month + '_' + day + '.csv'])
A: You can also use normal strings like:
Id + '/' + TypeOfMachine + '/' + year + '_' + month + '/' + year + '_' + month + '_' + day + '.csv' | unknown | |
d1919 | train | Fixed it!
function handler (request) {
var json = new OpenLayers.Format.JSON ();
var response = json.read (request.responseText);
//console.log(response);
var layer_data = response.layers
for (var i in layer_data) {
var layer_name = layer_data[i].title;
//alert(layer_name);
var layer_url = layer_data[i].url;
//alert(layer_url);
var layer_style = layer_data[i].style;
//alert (layer_style);
layer = new OpenLayers.Layer.Vector(layer_name, {
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: layer_url,
format: new OpenLayers.Format.GeoJSON({
})
}),
//...load stylemap
});
//turn layer off
layer.styleMap = mh_style_map;
layer.setVisibility(false);
map.addLayer(layer);
}
//alert (response);
}; | unknown | |
d1920 | train | I observed that you have used wrong variable to replace the html in success,
I have replace PartialView to partialView
var text = 'test';
$.ajax({
url: '@Url.Action("Subcategory", "Category")',
type: 'GET',
dataType: 'JSON',
data: { item: text },
success: function (partialView) {
$('#partialviewpage').html(partialView);
},
error: function (xhr, ajaxOptions, thrownError) {
}
}); | unknown | |
d1921 | train | Your problem arises because urlsCleaned is a pd.DataFrame not a pd.Series, to solve you have to change the line to:
urlsCleaned = NWO_data["urls"]
Note that they look almost the same, but in your case, it creates a pd.DataFrame with one column, and here it creates an pd.Series. | unknown | |
d1922 | train | You can prevent the effects of margin collapsing with:
body { overflow: hidden }
That will make the body margins remain accurate.
A: I had similar problem, got this resolved by the following CSS:
body {
margin: 0 !important;
padding: 0 !important;
}
A: I had same problem. It was resolved by following css line;
h1{margin-top:0px}
My main div contained h1 tag in the beginning.
A: The best way to reset margins for all elements is to use the css asterisk rule.
Add this to the top of your css under the @charset:
* {
margin: 0px;
padding: 0px;
}
This will take away all the preset margins and padding with all elements body,h1,h2,p,etc.
Now you can make the top or header of your page flush with the browser along with any images or text in other divs.
A: I have been having a similar issue. I wanted a percentage height and top-margin for my container div, but the body would take on the margin of the container div.
I think I figured out a solution.
Here is my original (problem) code:
html {
height:100%;
}
body {
height:100%;
margin-top:0%;
padding:0%;
}
#pageContainer {
position:relative;
width:96%; /* 100% - (margin * 2) */
height:96%; /* 100% - (margin * 2) */
margin:2% auto 0% auto;
padding:0%;
}
My solution was to set the height of the body the same as the height of the container.
html {
height:100%;
}
body {
height:96%; /* 100% * (pageContainer*2) */
margin-top:0%;
padding:0%;
}
#pageContainer {
position:relative;
width:96%; /* 100% - (margin * 2) */
height:96%; /* 100% - (margin * 2) */
margin:2% auto 0% auto;
padding:0%;
}
I haven't tested it in every browser, but this seems to work.
A: The same issue has been driving me crazy for several hours. What I found and you may want to check is html encoding. In my html file I declared utf-8 encoding and used Notepad++ to enter html code in utf-8 format. What I DID forget of was UTF-8 BOM and No BOM difference. It seems when utf-8 declared html file is written as UTF-8 BOM there is some invisible extra character at the begining of the file. The character (non-printable I guess) effects in one row of "text" at the top of the rendered page. And you cannot see the difference in source-view of the browser (Chrome in my case). Both nice and spoiled files seem identical to the very character, still one of them renders nicely and the other one shows this freaking upper margin.
To wrap it up the solution is to convert the file to UTF-8 NO BOM and one can do it in i.e. Notepad++.
A: A lot of elements in CSS have default padding and margins set on them. So, when you start building a new site, it's always good to have a reset.css file ready. Add this to make to rub the default values, so you have more control over your web page.
/* CSS reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td {
margin:0;
padding:0;
}
html,body {
margin:0;
padding:0;
}
/* Extra options you might want to consider*/
table {
border-collapse:collapse;
border-spacing:0;
}
fieldset,img {
border:0;
}
input{
border:1px solid #b0b0b0;
padding:3px 5px 4px;
color:#979797;
width:190px;
}
address,caption,cite,code,dfn,th,var {
font-style:normal;
font-weight:normal;
}
ol,ul {
list-style:none;
}
caption,th {
text-align:left;
}
h1,h2,h3,h4,h5,h6 {
font-size:100%;
font-weight:normal;
}
q:before,q:after {
content:'';
}
abbr,acronym {
border:0;
}
I hope this helps all fellow developers this is something that bugged for me a while when I was learning.
A: Is your first element h1 or similar? That element's margin-top could be causing what seems like a margin on body.
A: Here is the code that everyone was asking for -- its at the very beginning of development so there isn't much in it yet, which may be helpful...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- TemplateBeginEditable name="doctitle" -->
<title></title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" --><!-- TemplateEndEditable -->
<link href="../Styles/KB_styles1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="mainContainer">
<div class="header"> </div>
<div class="mainContent"> </div>
<div class="footer"> </div>
</div>
</body>
</html>
Here is the css:
@charset "utf-8";
/* CSS Document */
body{
margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px;
padding: 0;
color: black; font-size: 10pt; font-family: "Trebuchet MS", sans-serif;
background-color: #E2E2E2;}
html{padding: 0; margin: 0;}
/* ---Section Dividers -----------------------------------------------*/
div.mainContainer{
height: auto; width: 68em;
background-color: #FFFFFF;
margin: 0 auto; padding: 0;}
div.header{padding: 0; margin-bottom: 1em;}
div.leftSidebar{
float: left;
width: 22%; height: 40em;
margin: 0;}
div.mainContent{margin-left: 25%;}
div.footer{
clear: both;
padding-bottom: 0em; margin: 0;}
/* Hide from IE5-mac. Only IE-win sees this. \*/
* html div.leftSidebar { margin-right: 5px; }
* html div.mainContent {height: 1%; margin-left: 0;}
/* End hide from IE5/mac */
A: Try margin -10px:
body { margin-top:-10px; }
A: For opera just add this in header
<link rel='stylesheet' media='handheld' href='body.css' />
This makes opera use most of your customised css.
A: It is a <p> element that creates the top margin. You removed all top margins except of that element.
A: same problem, h1 was causing it to have that massive margin-top. after that you can use body{margin: 0;} and its looks good. another way is using *{margin: 0;} but it might mess up margins of other elements for you.
A: I had this exact same problem. For me, this was the only thing that worked:
div.mainContainer { padding-top: 1px; }
It actually works with any number that's not zero. I really have no idea why this took care of it. I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1 margins and paddings to 0 had no effect for me. I also had an h1 at the top of my page
A:
body{
margin:0;
padding:0;
}
<span>Example</span>
A: I tried almost every online technique, but i still got the top space in my website, when ever i open it with opera mini mobile phone browser, so i decided to try fix it on my own, and i got it right!
i realize when even you display a page in a single layout, it fits the website to the screen, and some css functions are disabled, since margin, padding, float and position functions are disabled automatically when you fit to screen, and the body always add inbuilt padding at the top. so i decieded to look for at least one function that works, guess what? "display". let me show you how!
<html>
<head>
<style>
body {
display: inline;
}
#top {
display: inline-block;
}
</style>
</head>
<body>
<div id="top">
<!-- your code goes here! -->
eg: <div id="header"></div>
<div id="container"></div> and so on..
<!-- your code goes here! -->
</div>
</body>
</html>
If you notice, the body{display:inline;} removes the inbuilt padding in the body, but without #top{display:inline-block;}, the div still wont display well, so you must include the <div id="top">
element before any code on your page! so simple.. hope this helps? you can thank me if it works, http://www.facebook.com/exploxi
A: you may also check if:
{float: left;}
and
{clear: both;}
are used correctly in your css.
A: style="text-align:center;margin-top:0;" cz-shortcut-listen="true"
paste this at your body tag!
this will remove the top margin | unknown | |
d1923 | train | On onSwiped method, add-
if (direction == ItemTouchHelper.RIGHT) {
//whatever code you want the swipe to perform
}
then another one for left swipe-
if (direction == ItemTouchHelper.LEFT) {
//whatever code you want the swipe to perform
}
A: Make use of the direction argument to onSwiped(). See the documentation. You can make adjustments depending upon whether you are swiping right or left.
A: For me, direction returns START/END not LEFT/RIGHT, so this is what i have to do.
if(direction == ItemTouchHelper.START) {
// DO Action for Left
} else if(direction == ItemTouchHelper.END) {
// DO Action for Right
} | unknown | |
d1924 | train | If data you want is Property:
var values = typeof(potato)
.GetProperties()
.Select(p=>p.GetValue(query,null))
.ToArray();
If data is Field:
var values = typeof(potato)
.GetFields()
.Select(p=>p.GetValue(query))
.ToArray();
If some property must be returned you can filter PropertyInfoes or FieldInfoes like below:
typeof(potato)
.GetFields()
.Where(p=>...labla...)
.Select...
A: You can get this through reflection
foreach (PropertyInfo propertyInfo in potato.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
string val= propertyInfo.GetValue(potato, null).ToString();
}
} | unknown | |
d1925 | train | myobj(num1, num2)
This attempts to call your myobj object like a functor. Instead you just want to pass myobj:
mymap.insert(pair<string,ap_pair>(name, myobj)); | unknown | |
d1926 | train | Except center layoutUnit, other layout units must have dimensions defined via size option.
Like this:
<p:layout fullPage="true">
<p:layoutUnit position="north" size="50">
<h:outputText value="Top content." />
</p:layoutUnit>
<p:layoutUnit position="south" size="100">
<h:outputText value="Bottom content." />
</p:layoutUnit>
<p:layoutUnit position="west" size="300">
<h:outputText value="Left content" />
</p:layoutUnit>
<p:layoutUnit position="east" size="200">
<h:outputText value="Right Content" />
</p:layoutUnit>
<p:layoutUnit position="center">
<h:outputText value="Center Content" />
</p:layoutUnit>
</p:layout>
A: If you are going with a layout concept in your project, it should handle like this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<f:view contentType="text/html" id="fview">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<f:metadata>
<ui:insert name="metadata" />
</f:metadata>
<meta name="selectedLanguage" content="Lang" lang="#{menuBean.selectedLanguage}"/>
<h:head>
</head>
<h:body behavior: url(PIE/PIE.htc);">
<p:layout fullPage="true" widgetVar="layoutWdgtMain">
<p:layoutUnit id="north" position="north" cellpadding="0" cellspacing="0">
//enter your code
</p:layoutUnit>
<p:layoutUnit id="east" position="east" cellpadding="0" cellspacing="0">
//enter your code
</p:layoutUnit>
<p:layoutUnit id="west" position="west" cellpadding="0" cellspacing="0">
//enter your code
</p:layoutUnit>
<p:layoutUnit id="south" position="south" cellpadding="0" cellspacing="0">
//enter your code
</p:layoutUnit>
</p:layout>
</h:body>
</f:view>
</html> | unknown | |
d1927 | train | Set up debugging on the PHP Side (XDebug works pretty well in most scenarios). Also, for ANY AJAX/web request functionality, I run fiddler (http://www.telerik.com/fiddler) to see what is being returned to the client from the web server (it will give you a complete view of the web request).
Hope this helps! | unknown | |
d1928 | train | You can always queue your ajax calls so they happen 1 at a time. There are jquery plugins to help with this:
http://www.protofunc.com/scripts/jquery/ajaxManager/
To me however, 6 calls does not seem too bad, as long as they dont generate a lot of server activity (hard db queries, file handling, etc...)
A: alternatively, you can start all your queries as soon as the page is requested, and save the results up for the ajax calls. This needs asynchronous execution on the server, and you need to make sure that the ajax response program can wait for the sql completion too.
If you query the same data in several of your 6 queries, this might be worth it. If tables are different for each, this might be really counterproductive (depending on your database engine, and cluster architecture).
However, if database stress and response time is a concern, caching techniques and other optimisations usually work better (memcache by example). But again this depends strongly on your database engine. | unknown | |
d1929 | train | Do it as follows:
import java.util.Arrays;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "i was hoping the number";
String[] valid = new String[] { "nip", "pin" };
if (Arrays.stream(valid).anyMatch(p -> Pattern.compile("\\b" + p + "\\b").matcher(input).find())) {
System.out.println("valid");
}
}
}
Note that \b is used for word boundary which I have added before and after the matching words to create word boundary for them.
Some more tests:
import java.util.Arrays;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String[] testStrings = { "i was hoping the number", "my pin is 123", "the word, turnip ends with nip",
"turnip is a vegetable" };
String[] valid = new String[] { "nip", "pin" };
for (String input : testStrings) {
if (Arrays.stream(valid).anyMatch(p -> Pattern.compile("\\b" + p + "\\b").matcher(input).find())) {
System.out.println(input + " => " + "valid");
} else {
System.out.println(input + " => " + "invalid");
}
}
}
}
Output:
i was hoping the number => invalid
my pin is 123 => valid
the word, turnip ends with nip => valid
turnip is a vegetable => invalid
Solution without using Stream API:
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = "i was hoping the number";
String[] valid = new String[] { "nip", "pin" };
for (String toBeMatched : valid) {
if (Pattern.compile("\\b" + toBeMatched + "\\b").matcher(input).find()) {
System.out.println("valid");
}
}
}
} | unknown | |
d1930 | train | edited
My original answer works, but there's a much better way of doing this, by creating your own build system. This use case is exactly why the feature is there.
Go to Tools → Build System → New Build System… (all the way at the bottom) and enter the contents below. Save as C++ 11 Single File.sublime-build, and it will now be accessible in the build system menu. Select it, hit CtrlB to build, and then hit CtrlShiftB to run the resulting program. Or you can use a Build and Run option and call it by hitting CtrlB, then selecting that option.
{
"cmd": ["g++", "-std=gnu++11", "${file}", "-o", "${file_path}/${file_base_name}"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++",
"variants":
[
{
"name": "Run",
"cmd": ["${file_path}/${file_base_name}"]
},
{
"name": "Build and Run",
"cmd": ["g++ -std=gnu++11 ${file} -o ${file_path}/${file_base_name} && ${file_path}/${file_base_name}"],
"shell": true
}
]
}
If you need to edit it in the future, the file is in the User folder of Packages. The Packages directory is the one opened when selecting Preferences → Browse Packages…:
*
*Linux: ~/.config/sublime-text-3/Packages or ~/.config/sublime-text/Packages
*OS X: ~/Library/Application Support/Sublime Text 3/Packages or ~/Library/Application Support/Sublime Text/Packages
*Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages or C:\Users\YourUserName\AppData\Roaming\Sublime Text\Packages
*Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages InstallationFolder\Sublime Text\Data\Packages
The exact path depends on version and whether or not you upgraded from Sublime Text 3.
A: In my case, the problem is that in Windows, ST3 was calling py instead of python which was the default. If you change python in "cmd": ["python", "-u", "$file"] for your local python interpreter, the new system should work.
{
"cmd": ["python3", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"},
"windows": {
"cmd": ["python", "-u", "$file"],
},
"variants":
[
{
"name": "Syntax Check",
"cmd": ["python3", "-m", "py_compile", "$file"],
"windows": {
"cmd": ["py", "-m", "py_compile", "$file"],
}
}
]
} | unknown | |
d1931 | train | The size in bytes is system dependent and should simply be queried like this:
unsigned int pidLength = sizeof(pid_t);
Edit: If you're worried about the length decimal representation as in printf("%d", myPID);, I suggest querying that, too. For example, the snprintf function returns the number of characters (without null-termination) it would have written if there were enough space. So you can do:
char tmpChar;
int representationLength = snprintf(&tmpChar, 1, "%d", myPID);
if (representationLength == -1) { handle_error(); }
char *finalString = malloc(representationLength + 1);
snprintf(finalString, representationLength + 1, "%d", myPID);
Maybe snprintf(NULL, 0, "%d", myPID) would work to query the length as well, but the Linux snprintf man page says this:
Concerning the return value of snprintf(), SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough.
A: The maximum number of digits in an 32-bit int is 10.
The maximum number of digits in a 64-bit signed int is 19.
The maximum number of digits in a 64-bit unsigned int is 20.
I don't know if AIX uses 32 or 64 bits, signed or unsigned, for its pid_t.
Edit: it's gotta be signed because fork can return -1.
A: Another approach could be to use (int)log10(pid) + 1. Of course, you might need to include space for a terminating null character, but the above should give you the number of characters needed to represent the value as a string. | unknown | |
d1932 | train | I don't think there is such an option. You just have to remove it manually from the admin pages you mostly use | unknown | |
d1933 | train | to be independent of the operating system used(Win,Linux(Ubuntu,..),Mac),Execute this command :
java -cp h2*.jar org.h2.tools.Console
It will open the browser : http://localhost:8082
A: I've generally just used their web interface, found at http://localhost:8082 by default.
Their quickstart guide covers making it available on Windows in great detail, but I recommend simply checking http://localhost:8082 as a first step to see if it's already up and running. | unknown | |
d1934 | train | According to documentation, you can use the rules' priorities to achieve your goal: create one rule to cancel all requests and another rule, with higher priority, to ignore the first rule if the host is google.com. | unknown | |
d1935 | train | Unfortunately, the OptionMenu widget is somewhat poorly implemented. Regardless of your preferences, the optionmenu isn't designed to accept keyword arguments for the first three parameters master, variable, and value. They must be presented in that order as positional arguments.
self.menu_m = tk.OptionMenu(self.frame_1, self.var, *choices) | unknown | |
d1936 | train | You can download source code for clang
svn checkout http://llvm.org/svn/llvm-project/cfe/trunk
The header should be in the include/clang-c folders, you can edit the cmake file and pass in the location of the header in the CPP flags (-I)
cmake file would be here:-
ycm/CMakeFiles/ycm_core.dir/flags.make | unknown | |
d1937 | train | You can rewrite it this way
int main(){
int input, maxDiv = 0;
int div = 2;
scanf("%d", &input);
for(; !maxDiv; div++)
if(!(input%div))
maxDiv = input/div;
printf("%d\n", ( maxDiv == 1 || input < 0 ? 0 : maxDiv ) );
return 0;
}
It is an infinite loop that will exit as soon as maxDiv != 0. The complexity is O(sqrt (n)) as there is always a divisor of n less than or equal to sqrt(n), so the code is bound to exit (even if input is negative).
I forgot, you have to handle the case where input is zero.
A: Maybe you can declare a flag?
#include <stdio.h>
int main() {
int input, maxDiv;
int div = 2;
char found = 0;
scanf("%d", &input);
for ( ; div <= input/2 && !found ; div += 1 ) {
if ( input % div == 0 ) {
maxDiv = input / div;
found = 1;
} else {
maxDiv = 0;
}
}
printf("%d\n", maxDiv);
return 0;
}
A: You can stop the loop when you reach sqrt(input)... it's not that difficult to find a perfectly good integer sqrt function.
There's not a lot of point dividing by all the even numbers after 2. In fact there's not a lot of point dividing by anything except the primes. It's not hard to find the primes up to sqrt(INT_MAX) (46340, for 32-bit integer)... there are tables of primes freely available if you don't want to run a quick sieve to generate same.
And the loop...
maxdiv = 0 ;
i = 0 ;
sq = isqrt(input) ;
while ((maxdiv == 0) && (prime[i] < sq))
{
if ((input % prime[i]) == 0)
maxdiv = input / prime[i] ;
i += 1 ;
} ;
assuming a suitable integer sqrt function and a table of primes... as discussed.
A: Since you are looking for the largest divisor, is there a reason you're not looping backward to 2? If there isn't, then there should be no need for a break statement or any special logic to exit the loop as you should keep looping until div is greater than input / 2, testing every value until you find the largest divisor.
maxDiv = -1;
for (div = input / 2;
div >= 2 && maxDiv == -1;
--div)
{
if (input % div == 0)
maxDiv = div;
}
maxDiv += (maxDiv == -1);
printf ("%d\n", maxDiv);
I added the extra condition of maxDiv being -1, which is like adding a conditional break statement. If it is still -1 by the end of the loop, then it becomes 0 because maxDiv += 1 is like writing maxDiv = -1 + 1, which is 0.
Without any jump statement such as break, this sort of test is what you must do.
Also, regarding your code, if I input 40, the if statement will be triggered when div is 2, and the program will end. If the return 0 is changed to a break, maxDiv will be 2, not 20. Looping backward will find 20 since 40/2=20, and 40%20==0.
A: Let us denote D to the max divisor of a given composite number N > 1.
Then, obviously, the number d = N / D is the min non-trivial divisor of N.
If d would not a primer number, then d would have a non-trivial divisor p < d.
By transitivity, this implies that p is a divisor of N, but this fact would contradict the fact that d is the min divisor of N, since p < d.
*
*So, d must be a prime number.
In particular, it is enouth to search over those numbers which are less than sqrt(N), since, if p is a prime number greater than sqrt(N) which divies N, then N / p <= sqrt(N) (if not, *p * (N / p) > sqrt(N)sqrt(N) == N, wich is absurd).
This shows that it's enough to do the search the least divisor d of N just within the range of primer numbers from 2 to sqrt(N).
For efficiency, the value sqrt(N) must be computed just once before the loop.
Moreover, it is enough a rough approximation of sqrt(N), so we can write:
#include <math.h>
#include <stdio.h>
int main(void)
{
int N;
scanf("%d",&N);
// First, we discard the case in that N is trivial
// 1 is not prime, but indivisible.
// Change this return if your want.
if (N == 1)
return 0;
// Secondly, we discard the case in that N is even.
if (N % 2 == 0)
return N / 2;
// Now, the least prime divisor of N is odd.
// So, we increment the counter by 2 in the loop, by starting in 3.
float sqrtN = fsqrt(N); // square root of N in float precision.
for(d = 3; d <= sqrtN; d += 2)
if (N % d == 0)
return N/d;
// If the loop has reached its end normally,
// it means that N is prime.
return 0;
}
I think that the problem is not well stated, since I consider that a better flag to signalize that N is prime would be a returned value of 1.
There are more efficient algorithms to determine primality, but they are beyond the scope of the present question. | unknown | |
d1938 | train | Pass an Activity to AsyncTask and just use :
ImageView principal = (ImageView) passedActivity.findViewById(R.id.imagen_home_0);
or get inflater from Context like this :
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(R.layout.your_viw_that_contains_that_image, parent, false);
ImageView principal = (ImageView) row.findViewById(R.id.imagen_home_0);
//or by tag
principal = (ImageView) row.findViewWithTag("principal");
Best wishes.
A: You are calling findViewWithTag on noMiembros
which is a new View.
You need to call findViewWithTag on a parent of the ImageView
you are trying to reach.
But if you want to get your ImageView from within an AsyncTask, just call
findViewById(R.id.imagen_home_0) on your Activity.
A: I believe that you are ... mistaking those two tags.
setTag() can attach ANY object to the view, while the XML tag is only a string - I believe the findViewByTag will try to match the tag passed thru XML, not one attached through code - as it could be any object.
Why not just pass the principal imageView to the asyncthread? | unknown | |
d1939 | train | Since you asked for objective-C code, I assume you want to open either the appstore or the app on a certain URL. However, objective-c code is the least of the efforts here since it's mostly configurations that are at work for this.
To open an app you need to provide it a custom URL scheme:
http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
To detect if that app is installed, you can try that URL:
https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/canOpenURL:
And if not, you can navigate to the appstore instead via a different URL:
How can I link to my app in the App Store (iTunes)?
After you have done all that, the only actual code you need takes something of the form:
NSString *customURL = @"yourscheme://";
NSString *storeURL = @"itms://url_to_your_app";
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storeURL]];
}
Opening the app via it's URL can be done from other apps and websites, but will be more difficult to choose whether or not to open the app or store from inside a browser.
A: Apple have documented the process for you. You can just implement it your way.
NSString *iTunesLink = @"https://itunes.apple.com/us/app/apple-store/id375380948?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]]
You can refer to This document for more info | unknown | |
d1940 | train | you can use this:
str = str.replace(/<.*>/g,'');
See an example for match here
var str = "<field name='itemid'>xx</field>";
str = str.replace(/<.*>/g, 'replaced');
console.log(str)
Explanation:
*
*< matches the character < literally
*.* matches any character (except newline)
*
*Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
*> matches the character > literally
*g modifier: global. All matches (don't return on first match)
If you want to be more restrictive you can do this:
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, '');
See an example for match here
var str = '<field name="test">200</field>';
str = str.replace(/<field name\=\"\w*\">\d*<\/field>/g, 'replaced');
console.log(str)
Explanation:
*
*<field name matches the characters
*\= matches the character = literally
*\" matches the character " literally
*\w* match any word character [a-zA-Z0-9_]
*
*Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
*\" matches the character " literally
*> matches the character > literally
*\d* match a digit [0-9]
- Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
*< matches the character < literally
*\/ matches the character / literally
*field> matches the characters field> literally (case sensitive)
*g modifier: global. All matches (don't return on first match)
A: When you replace a tag especially XML tag you must be sure that you capture everything from opening to closing tag. In this case RegExp should look back.
var re = /<(\S+)[^>]*>.*<\/\1>/g;
var m ='some text <ab id="aa">aa <p>qq</p> aa</ab>test test <p>paragraph </p>'.replace(re,'');
console.log(m);//some text test test
\1 matches (\S+)
\S+ one or more non-white-space characters | unknown | |
d1941 | train | I think the cmdlet your looking for here is Get-AzureRmDataFactoryActivityWindow this accepts a run window and will return the result of a time slice either Ready, Waiting, Failed etc.
Example of use:
Get-AzureRmDataFactoryActivityWindow `
-DataFactoryName $ADFName.DataFactoryName `
-ResourceGroupName $ResourceGroup `
| ? {$_.WindowStart -ge $Now} `
| SELECT ActivityName, ActivityType, WindowState, RunStart, InputDatasets, OutputDatasets `
| Sort-Object ActivityName
Use this with the required params to return a list of the information you want. I might then stick it into a SQL table for wider monitoring etc. But you could use an array in PowerShell to get the count value and produce the alert. Next wrap it up in something that polls on the hour maybe.
Here's a link to all ADF PowerShell cmdlets available in the Azure module: https://learn.microsoft.com/en-gb/powershell/module/azurerm.datafactories/?view=azurermps-4.0.0
Hope this helps | unknown | |
d1942 | train | Not all of the Ribbon commands exist in the legacy CommandBars collection.
To get a full listing of the available commands create a blank document in Word and run the code below (from Word).
Sub ListCommands()
Dim cbar As CommandBar
Dim cbarCtrl As CommandBarControl
For Each cbar In Application.CommandBars
For Each cbarCtrl In cbar.Controls
Selection.TypeText cbarCtrl.Caption & vbCr
Next cbarCtrl
Next cbar
End Sub | unknown | |
d1943 | train | This worked for me:
require "watir-webdriver"
browser = Watir::Browser.new
browser.goto "ideone.com"
browser.div(:id => "file_div").textarea.set "1=1"
Are you sure you need to set text in textarea? If you are dealing with wysiwyg editor, you probably need to use send_keys:
browser.pre.send_keys "1=1"
More information: http://watirwebdriver.com/wysiwyg-editors/
A: It is important to send keys on proper element. In my case, after some experimentations, that was:
<div class="redactor_text redactor_optional redactor_redactor redactor_editor" contenteditable="true" dir="ltr" style="min-height: 120px;"></div>
Editor was defined with this html:
<div class="redactor_box"><ul class="redactor_toolbar" id="redactor_toolbar_0"><li><a href="javascript:;" title="Bold" tabindex="-1" class="re-icon re-bold"></a></li><li><a href="javascript:;" title="Italic" tabindex="-1" class="re-icon re-italic"></a></li><li><a href="javascript:;" title="Underline" tabindex="-1" class="re-icon re-underline"></a></li><li><a href="javascript:;" title="Link" tabindex="-1" class="re-icon re-link"></a></li><li><a href="javascript:;" title="Superscript" tabindex="-1" class="re-icon re-superscript fa-redactor-btn"><i class="fa icon-superscript"></i></a></li><li><a href="javascript:;" title="Subscript" tabindex="-1" class="re-icon re-subscript fa-redactor-btn"><i class="fa icon-subscript"></i></a></li></ul><div class="redactor_text redactor_optional redactor_redactor redactor_editor" contenteditable="true" dir="ltr" style="min-height: 120px;"></div><textarea class="text optional redactor" data-limit="450" data-persist="garlic" data-min-height="120" name="lesson[intro]" id="lesson_intro" dir="ltr" style="display: none;"></textarea></div> | unknown | |
d1944 | train | I'm going to use the documentation I posted earlier to show.
public function submitData(Request $request) {
$data = $request->all();
// check for form error and redirect back with error message and form input
$validator = Validator::make($data);
if ($validator->fails()) {
return redirect()
->back()
->withErrors($validator)
->withInput();
}
// submit data and redirect with success message
$this->createEntry($data);
return response()->json([
'success' => true,
'message' => 'Data successfully submitted',
]);
}
JS Submit:
function submit() {
var formData = $('#form').serializeArray();
formData.push({ name: "additional_data", value: additional_data });
$.ajax({
type: "POST",
url: "/submit_form_data",
data: formData,
success: function(data) {
console.log(data);
// response includes redirect url, session data ('success' or 'error' + message), form data (if form error)
}
});
} | unknown | |
d1945 | train | Language and runtime are two different things. They are not really related IMHO.
Therefore, if your existing runtime offers a GC already, there must be a good reason to extend the runtime with another GC. In the good old days when memory allocations in the OS were slow and expensive, apps brought their own heap managers which where more efficient in dealing with small chunks of data. That was one readon for adding another memory management to an existing runtime (or OS). But if you're talking Java, .NET or so - those should be good and efficient enough for most tasks at hand.
However, you may want to create a proper interface/API for memory and object management tasks (and others), so that your language ("guest") runtime could be implemented on to of another host runtime later on.
A: For an interpreter, there should be no problem with using the host GC, IMHO, particularly at first. As always they goal should be to get something working, then make it work right, then make it fast. This is particularly true for Domain Specific Languages (DSL) where the goal is a small language. For these, implementing a full GC would be overkill. | unknown | |
d1946 | train | You have to declare the data types of the columns. | unknown | |
d1947 | train | The below code snippet achieves the necessary logic (sans the React Hooks, API, and other items):
const movies = [{
name: "a",
genre: "comedy",
year: "2019",
},
{
name: "b",
genre: "drama",
year: "2019",
},
{
name: "c",
genre: "suspense",
year: "2020",
},
{
name: "d",
genre: "comedy",
year: "2020",
},
{
name: "e",
genre: "drama",
year: "2021",
},
{
name: "f",
genre: "action",
year: "2021",
},
{
name: "g",
genre: "action",
year: "2022",
}
];
const filterMyMovies = (byField = 'year', value = '2020', myMovies = movies) => (
(myMovies || [])
.filter(mov => !byField || !mov[byField] || mov[byField] === value)
);
console.log('movies in year 2020:\n', filterMyMovies());
console.log('movies in year 2019:\n', filterMyMovies('year', '2019'));
console.log('movies in genre drama:\n', filterMyMovies('genre', 'drama'));
console.log('movies with name d:\n', filterMyMovies('name', 'd'));
console.log('movies with NO FILTER:\n', filterMyMovies(null, null));
Explanation
Fairly-straightforward filtering of an array of objects, with only 1 column & 1 value. May be improvised for multi-column & multi-value filtering.
How to use this
The way to use this within React-Hooks is to invoke the 'filterMyMovies' method with the appropriate parameters when the filter-criteria changes. Suppose, the year is set to 'no-filter', then simply make call to the 'filterMyMovies' method with the first & second params as null.
Suppose we need to filter by year and then by genre as well, try something like this:
filterMyMovies('genre', 'comedy', filterMyMovies('year', '2019'));
This will return 2019 comedy movies. | unknown | |
d1948 | train | under usersActions.js file you are setting users instead of tasks.
case "SET_TASKS":
state = { ...state, users: action.payload }
break;
default:
it should be like:
case "SET_TASKS":
state = { ...state, tasks: action.payload }
break;
default: | unknown | |
d1949 | train | You have to loop over the items of the dictionary.
for key, value in data2['roles'].items():
res= value['name']
print(res)
A: There is nothing wrong with your code, I run it and I didn't get any error.
The problem that I see though is your Json file, some commas shouldn't be there:
{
"count": 6,
"results": [
{
"key": "roles",
"id": "1586230"
},
{
"key": "roles",
"id": "1586951"
},
{
"key": "roles",
"id": "1586932"
} \\ here
],
"roles": {
"1586230": {
"name": "Systems Engineer",
"deleted_at": null,
"created_at": "2022-04-22T03:22:24-07:00",
"updated_at": "2022-04-22T03:22:24-07:00",
"id": "1586230"
},
"1586951": {
"name": "Engineer- Software",
"deleted_at": null,
"created_at": "2022-05-05T01:51:29-07:00",
"updated_at": "2022-05-05T01:51:29-07:00",
"id": "1586951"
},
"1586932": {
"name": "Engineer- SW",
"deleted_at": null,
"created_at": "2022-05-05T01:38:37-07:00",
"updated_at": "2022-05-05T01:38:37-07:00",
"id": "1586932"
} \\ here
},
"meta": {
"count": 6,
"page_count": 5,
"page_number": 1,
"page_size": 20
}
after that any parsing function will do the job. | unknown | |
d1950 | train | It is quite common in Wicket to replace only portions of a page using Ajax. See these examples.
Wicket is also easily used in combination with jQuery and other JavaScript frameworks.
A: So called single page applications (a single page who's components get constantly replaced and/or updated via ajax) are the way almost every Wicket Apllication I wrote up till now turned out. Most of the Wicket Applications I saw out there relied on a very small number of (or just one) page(s).
The real big advantage of Wicket above jQuery in these use cases is the way in which Wicket offers a non-javascript fallback (then relying on page refreshes) with very little additional work (replacing AjaxLinks by AjaxFallbackLinks and adding an if-statement to check which refresh was triggered. | unknown | |
d1951 | train | You can use the apply method
def age_total(x):
if x < 2:
return * 1.2
elif x > 8:
return x * 1.1
else:
return x * 0.9
df['Total']= df['age'].apply(age_total) | unknown | |
d1952 | train | You should make your Item implement Parcelable. Try this site to make your Item Parcelable
A:
Item is neither Parcelable nor Serializable . And i would not like to
make any changes in that.
then you can't. I would strongly recommend you to look into the Parcelable interface, avoiding tricks like making the field public static
A: As others have said, you can't do it properly without implementing parcelable - which sometimes isn't possible.
You're only other option is to architect a way in which you can put your list in a static context so it's accessible from wherever.
You could create a singleton SparseArray and related integer, and pass around the integer between activities describing the position in the SparseArray. You'd just have to ensure that you incremented your integer and removed the item from the SparseArray once you'd grabbed it. Off the top of my head -
private class ComplexObjectPassing {
private static SparseArray<Object> sArray = new SparseArray<Object>();
private static int count = 0;
public static int putObject(Object obj) {
count++;
sArray.put(count, obj);
}
public static Object getObject(int index) {
Object obj = sArray.get(index);
sArray.put(index, null);
return obj;
}
}
Obviously, this would end with a huge memory leak when you passed things and they weren't pulled out by the new activity. All of the alternatives are going to have downsides and need to be carefully managed to reduce inevitable problems. | unknown | |
d1953 | train | Well, there does not seem to be a direct attribute/method to change the max limit but what you can do is set a custom value in the 'list_per_page' attribute of the ModelAdmin class admin.py like below:
class MyAppAdmin(admin.ModelAdmin):
list_per_page = 500
class Meta:
model = MyApp
The default value of list_per_page is 100 hence now after modifying it you can directly select all 500(in your case) at once per page and perform the requisite operation. | unknown | |
d1954 | train | If your grid is regular (i.e. similar to the output of meshgrid), you could also use image, imagesc or, if the imageprocessing toolbox is available, also imshow together with a matching colorscale.
imagesc(Z) | unknown | |
d1955 | train | NSJSONSerialization in Objective-c
TRY 1: If Json return Array
-(void)getdata:(NSString *)send
{
NSURL *url = [[NSURL alloc]initWithString:send];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
}
TRY 2: If Json return Dictinary
-(void)getdata:(NSString *)send
{
NSURL *url = [[NSURL alloc]initWithString:send];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",res);
}
To call Method:
NSString *send = [NSString stringWithFormat:@"http://182.18.182.91/RaosMobileService/Service1.svc/GetStudentAttendance_ByMonth/%@/%@/1/%d/2017"];
[self getdata:send]; | unknown | |
d1956 | train | A member variable in a class has a life-span corresponding to the life-span of the class's instances, unless declared static.
struct Foo {
int x;
static int y;
};
This Foo, and therefore its x, has program life-span:
static Foo foo;
This one is auto:
int main() { Foo foo; }
This one is dynamically allocated and lives until the Foo is delete'd:
int main() { Foo *foo = new Foo; }
In each case, the y has program life-span. | unknown | |
d1957 | train | It is possible, of course. Have a look at interfacing. For the iOS app I would use the Multi-OS engine. Use the normal gdx-setup jar file to create moe module. | unknown | |
d1958 | train | You could try Apache Sanselan for the dimension and Droid for the identification. | unknown | |
d1959 | train | On the button press event can you just load both?
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + url1+ "','_blank')", true);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + url2+ "','_blank')", true); | unknown | |
d1960 | train | You could use a VBA macro similar to the following:
Sub SubjectCheckerMessageRule(newMail As Outlook.mailItem)
' "script" routine to be called for incoming mail messages
' This subroutine has to be linked to this mail type using Outlook's rule assistant
Dim EntryID As String
Dim StoreID As Variant
Dim mi As Outlook.mailItem
Dim s As String
Dim x As Double
Const Prefix = "Resistance,"
Const Threshold = 40.0 ' or is it 45.0
' http://www.vboffice.net/en/developers/security-model-part-1/
' In 2003, not 2007 or later
' we have to access the new mail via an application reference
' to avoid security warnings
'
EntryID = newMail.EntryID
StoreID = newMail.Parent.StoreID
Set mi = Application.Session.GetItemFromID(EntryID, StoreID)
If InStr(mi.Subject, Prefix) = 1 Then
s = Mid(mi.Subject, Len(Prefix) + 1)
If IsNumeric(s) Then
x = CDbl(s)
If x <= Threshold Then
MsgBox x & " <= " & Threshold, vbInformation, "Attention!"
End If
End If
End If
End Sub
Use Outlook's Rule Assistant to define this macro as Script for the incoming mails of interest. Define keywords for the subject like "Resistance," to make sure that the macro is only called for the relevant mails. Add some error checking. | unknown | |
d1961 | train | Assuming:
var myObj = [{"a": "1", "b": "2", "c": "3"}];
Then, you can do this:
var result = []; // output array
for(key in myObj[0]){ // loop through the object
if(myObj[0].hasOwnProperty(key)){ // if the current key isn't a prototype property
var temp = {}; // create a temp object
temp[key] = myObj[0][key]; // Assign the value to the temp object
result.push(temp); // And add the object to the output array
}
}
console.log(result);
// [{"a": "1"}, {"b": "2"}, {"c": "3"}]
A: You can grab the object keys and loop over the objects with map:
var newArr = Object.keys(arr[0]).map(function (key) {
var obj = {};
obj[key] = arr[0][key];
return obj;
});
DEMO | unknown | |
d1962 | train | Javadoc: https://javadl.oracle.com/webapps/download/AutoDL?BundleId=245778_df5ad55fdd604472a86a45a217032c7d
The source should be part of the JDK, search for src.zip in your JDK directory.
How to attach JDK source code to IntelliJ IDEA
A: I didn't know that patch releases don't change the public API, so both Thomas Behr's comment and sinclair's answer are valid.
Only thing to add is that the javadoc zip should be included in IntelliJ IDA via File -> Project Structure -> Platform Settings -> SDKs -> Documentation Paths (instead of Sourcepath). | unknown | |
d1963 | train | first check if the methods and the classes you are going to use are public, then you can add the projects, with the methods you need to call, as dependency in the pom.xml file. | unknown | |
d1964 | train | In C++, there's no direct type which exactly represents a 2D "vector"/"matrix"/"tensor".
What you can create, is a vector of vectors. You'd write that as std::vector<std::vector<int>> - each element of the outer vector is itself a vector. But there's an important difference here: each of the inner vectors has its own length, and those could be different.
vector has a constructor taking a second argument, the initial value. You can use that here to initialize the inner vectors:
std::vector<std::vector<int>> v(6, std::vector<int>(2)); | unknown | |
d1965 | train | 8(%esp) is the first number, under the framework of x86.
enter 40 2 or 60 3 or 80 4 should work.
Equivalent to the following logic
#include <stdio.h>
#include <stdlib.h>
void explode_bomb()
{
printf("explode bomb.\n");
exit(1);
}
unsigned func4(int val, unsigned num)
{
int ret;
if (val <= 0)
return 0;
if (num == 1)
return 1;
ret = func4(val - 1, num);
ret += num;
val -= 2;
ret += func4(val, num);
return ret;
}
void phase_4(const char *input)
{
unsigned num1, num2;
if (sscanf(input, "%u %u", &num1, &num2) != 2)
explode_bomb();
if (num2 - 2 > 2)
explode_bomb();
if (func4(6, num2) != num1)
explode_bomb();
}
int main()
{
phase_4("40 2");
phase_4("60 3");
phase_4("80 4");
printf("success.\n");
return 0;
} | unknown | |
d1966 | train | The coordinates/sizes passed to glReadPixels() are in window coordinates. The window coordinate system has its origin in the lower left corner of the window, with a unit of pixels.
This is not to be confused with the NDC (normalized device coordinates) system used for vertex coordinates, which has its origin in the center of the window, and has a range of [-1.0, 1.0] in both the x- and y-directions.
So in your example:
GLES20.glReadPixels(0, 0, 1, 1,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
you are reading one pixel in the lower left corner of the rendering surface. To read a pixel in the center, you need:
GLES20.glReadPixels(width / 2, height / 2, 1, 1,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
where width and height are the dimensions of the rendering surface in pixels. | unknown | |
d1967 | train | You can use removeEventListener() function. documentation
example:
let wheelHandler = function(e) {
toggleListener(wheelHandler, false)
const isScrollingDown = Math.sign(e.wheelDeltaY);
// call some function once, don't listen for wheel event anymore
// then listen for event again when done
toggleListener(wheelHandler, true)
};
let toggleListener = function(listener, add) {
if (add) {
container.addEventListener("wheel", wheelHandler)
} else {
container.removeEventListener("wheel", wheelHandler)
}
}
toggleListener(wheelHandler, true);
A: wait 1 second after first wheel:
function handleWheel(e){
console.log(Math.random())
document.getElementById("container").removeEventListener("wheel", handleWheel)
setTimeout(()=>{
document.getElementById("container").addEventListener("wheel", handleWheel);
},1000); // return event after 1 second
}
document.getElementById("container").addEventListener("wheel", handleWheel)
<div id="container" >wheel</div>
A: you can define loading variable and check each time before run function
var loading = false
container.addEventListener("wheel", (e) => {
const isScrollingDown = Math.sign(e.wheelDeltaY);
if(!loading){
loading = true;
// call some function once, don't listen for wheel event anymore
// then listen for event again when done
// after done
loading = false
}
} | unknown | |
d1968 | train | The underlying issue is that the output of print for a time series object is quite heavily processed by .preformat.ts. If you want to convert it to a data frame that is visually similar to the print results this should do:
df <- data.frame(.preformat.ts(datasets::AirPassengers), stringsAsFactors = FALSE)
Note that this will produce characters (as that is how .preformat.ts works), so be careful with the use (not sure what is the purpose of the conversion?). | unknown | |
d1969 | train | Change from onmouseout="Start.pause;"> to onmouseout="Start.pause();">. You missed the parenthesis in the pause function | unknown | |
d1970 | train | I recommend you double check your PATH variable.
As per:
"If your installation is unsuccessful due to the find command not being recognized, ensure your PATH environment variable is set to include the folder containing find. Usually, this is C:\WINDOWS\system32;"
I noticed that you added the logs :), I would like to mention that sometimes there are some issues with special characters in the admin user name(~),so just a quick test, could you please try to use another user without any special character in the name?
Another option is installing manually Python 2.7 and set an environment variable with "CLOUDSDK_PYTHON" with a direct path to python.exe.
For example:
C:\HERE\python.exe
Finally, I found this Stackoverflow post that could help you. | unknown | |
d1971 | train | try
select
case when cs(User-Agent) like "%android%" then "Android"
when cs(User-Agent) like "%black%" then "Blackberry"
when cs(User-Agent) like "%windows%" then "Windows"
when cs(User-Agent) like "%iphone%" then "iPhone"
else "Other" end as Browser,
count(*) as TotalHits
from
YourTable.logFile
group by
Browser
order by
TotalHits desc
The group by and order by respect the ordinal column position instead of re-copying the entire case/when and count(*)... Since there's only two columns, no problem... | unknown | |
d1972 | train | I have just figured out how to do it! I'm going to post here what I did so maybe it will result helpful for some people:
It's just simple as invocating it using a variable.
Button code:
var button = Ext.create('Ext.Button', {
text : 'Button',
renderTo : Ext.getBody(),
listeners: {
click: function() {
// this == the button, as we are in the local scope
this.setText('I was clicked!');
},
mouseover: function() {
// set a new config which says we moused over, if not already set
if (!this.mousedOver) {
this.mousedOver = true;
alert('You moused over a button!\n\nI wont do this again.');
}
}
}
});
In your viewport you just have to add it as an item:
...
items: [
{
items: button //button is the variable that we defined when we created the button
}
]
...
Final result:
I hope this will help someone who is having the same question as me :) | unknown | |
d1973 | train | You can use SandCastle. It is now maintained as part of SandCastle Help File Builder or SHFB.
http://shfb.codeplex.com/
SandCastle depends on Microsoft Help Workshop, which you have to download separately.
If you want to just create your own help system and not product API documentation, then just use the HTML Help Workshop on its own. It very simple, to use. Just create HTML pages for each help section and compile. Read the documentation.
HTML Help is also available as part of the Visual Studio SDK.
Reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms670169(v=vs.85).aspx
Download:
http://www.microsoft.com/en-us/download/details.aspx?id=21138
Important:
As of March 2012 there is no HTML Help Workshop 1.4. VS 2010 doesn't use MS Help2 format so there is no Help2 compiler available for it. Starting with VS 2010, the new MS Help Viewer format is used.
Reference:
http://msdn.microsoft.com/en-us/library/vstudio/hh492077.aspx
MS Help Viewer SDK for Visual Studio:
http://msdn.microsoft.com/en-us/library/dd627473.aspx
Hope that helps.
I would suggest you to use SandCastle (SHFB), because you get best of all worlds. You can create compiled HLP2 files, Help Viewer Content and also a simple online HTML help. | unknown | |
d1974 | train | /usr/local/bin would be the usual choice for user or third-party executables. That way it won't get wiped out when you update the OS.
See also: Where do you keep your own scripts on OSX? - the question is about scripts rather than binaries, but the same logic applies. | unknown | |
d1975 | train | This is not working. The major problem is that I don't understand how to relate the CanExecute value to the Button.
Bind its Command property to the same command:
<Button Content="Button" Command="{x:Static local:CustomCommands.ReceivedFocus}" />
The Button should then be enabled or disabled based on the value that you set the CanExecute property to in your CanActivate event handler.
You probably also want to listen to the SelectionChanged event. This works as expected:
<StackPanel>
<StackPanel.CommandBindings>
<CommandBinding
Command="{x:Static local:CustomCommands.ReceivedFocus}"
CanExecute="CanActivate"
Executed="ChangeSelection">
</CommandBinding>
</StackPanel.CommandBindings>
<ListBox x:Name="lstInactive">
<ListBoxItem>first</ListBoxItem>
<ListBoxItem>second</ListBoxItem>
<ListBoxItem>third</ListBoxItem>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{x:Static local:CustomCommands.ReceivedFocus}">
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
<Button Content="Button" Command="{x:Static local:CustomCommands.ReceivedFocus}" />
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CanActivate(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = lstInactive.SelectedIndex >= 0;
}
private void ChangeSelection(object sender, ExecutedRoutedEventArgs e)
{
}
} | unknown | |
d1976 | train | I use it like this,
$ionicLoading.show();
$ionicPlatform.ready(function() {
/* insert your code here */
$ionicLoading.hide().then(function(){
console.log("The loading indicator is now hidden");
});
$state.go("tab.dash");
}); | unknown | |
d1977 | train | webadmin doesn't really report counts, indeed the highest ID in use is reported. Since multiple properties are stored internally in the same block you'll see misleading numbers there. To validate:
MATCH (n) where has(n.woka_title) and has (n.woka_id) RETURN count(n) == 19798966
should return true. | unknown | |
d1978 | train | ok c.JSON(http.StatusOK, myArray) worked. But I cannot see the Id field in the response. Any reason why? Is it because of 'int64' dataType? | unknown | |
d1979 | train | The following example code extracts all the words (English alphabet only) from every line and process them (counts the number of words, and retrieve instances of each unique word).
import re
MESSAGE = 'Please input a new line: '
TEST_LINE = '''
Well, my heart went "boom"
When I crossed that room
And I held her hand in mine
Whoah, we danced through the night
And we held each other tight
And before too long I fell in love with her
Now I'll never dance with another
(Whooh)
Since I saw her standing there
Oh since I saw her standing there well well
Oh since I saw her standing there
'''
prog = re.compile(r'\w+')
class UniqueWordCounter():
def __init__(self):
self.data = {}
def add(self, word):
if word:
count = self.data.get(word)
if count:
count += 1
else:
count = 1
self.data[word] = count
# instances of each unique word
set_of_words = UniqueWordCounter()
# counts the number of words
count_of_words = 0
def handle_line(line):
line = line.lower()
words = map(lambda mo: mo.group(0), prog.finditer(line))
for word in words:
global count_of_words
count_of_words += 1
set_of_words.add(word)
def run():
line = input(MESSAGE)
if not line:
line = TEST_LINE
while line:
'''
Loop continues as long as `line` is not empty
'''
handle_line(line)
line = input(MESSAGE)
count_of_unique_words = len(set_of_words.data.keys())
unique_percentage = count_of_unique_words / count_of_words
print('-------------------------')
print('This song has {} words.'.format(count_of_words))
print('{} of which are unique.'.format(count_of_unique_words))
print('This song is {:.2%} unique words.'.format(unique_percentage))
items = sorted(set_of_words.data.items(), key = lambda tup: tup[1], reverse=True)
items = ["('{}', {})".format(k, v) for k, v in items]
print('\n'.join(items[:3]))
print('...')
run()
If you want to handle lyrics in other languages, you should check out this link. | unknown | |
d1980 | train | There is no way to extend views that way in Rails. You can however, accomplish this by using partials. In your engine, write a partial view file users/_show.html.erb and then render it in your app's view:
# app/views/users/show
# will look for a partial called "_show.html.erb" in the engine's and app's view paths.
render partial: 'show'
It's just as easy as your suggestion.
This gem tries to implement partial extension of views, but it works similarly to what I just described: https://github.com/amatsuda/motorhead#partially-extending-views-in-the-main-app | unknown | |
d1981 | train | It's failing because you are casting your JSON to [NSDictionary]. When you get multiple objects, you get an array of dictionaries, but when you get a single object, you get a single dictionary.
You should try to cast to NSDictionary if casting to [NSDictionary] fails.
If both fail then you should throw the error. | unknown | |
d1982 | train | Try this
func toFloat(data []byte) (float, error) {
return strconv.ParseFloat(strings.ReplaceAll(string(data), ",", ""), 64)
}
Split your original byte array by space, then pass it to this function. It will return either the float you need or error | unknown | |
d1983 | train | Yes, you can use SPC f f, enter the name of the new file and then select the line starting with [?] (which is the default if no other file matches).
Note you can also use this to create files in non-existing subfolders, like SPC f f my/sub/folder/file.txt RET.
A: If you are using the standard vim like keybindings,
:e /path/to/file
works opens a file ( which doesn't have to exist before )
:x
saves the file and closes the buffer and
:w
saves without closing. | unknown | |
d1984 | train | This can be done without recursion if you want
[0..20]
|> Seq.mapi (fun i elem -> (i/size),elem)
|> Seq.groupBy (fun (a,_) -> a)
|> Seq.map (fun (_,se) -> se |> Seq.map (snd));;
val it : seq<seq<int>> =
seq
[seq [0; 1; 2; 3; ...]; seq [5; 6; 7; 8; ...]; seq [10; 11; 12; 13; ...];
seq [15; 16; 17; 18; ...]; ...]
Depending on how you think this may be easier to understand. Tomas' solution is probably more idiomatic F# though
A: Hurray, we can use List.chunkBySize, Seq.chunkBySize and Array.chunkBySize in F# 4, as mentioned by Brad Collins and Scott Wlaschin.
A: Implementing this function using the seq<_> type idiomatically is difficult - the type is inherently mutable, so there is no simple nice functional way. Your version is quite inefficient, because it uses Skip repeatedly on the sequence. A better imperative option would be to use GetEnumerator and just iterate over elements using IEnumerator. You can find various imperative options in this snippet: http://fssnip.net/1o
If you're learning F#, then it is better to try writing the function using F# list type. This way, you can use idiomatic functional style. Then you can write batchesOf using pattern matching with recursion and accumulator argument like this:
let batchesOf size input =
// Inner function that does the actual work.
// 'input' is the remaining part of the list, 'num' is the number of elements
// in a current batch, which is stored in 'batch'. Finally, 'acc' is a list of
// batches (in a reverse order)
let rec loop input num batch acc =
match input with
| [] ->
// We've reached the end - add current batch to the list of all
// batches if it is not empty and return batch (in the right order)
if batch <> [] then (List.rev batch)::acc else acc
|> List.rev
| x::xs when num = size - 1 ->
// We've reached the end of the batch - add the last element
// and add batch to the list of batches.
loop xs 0 [] ((List.rev (x::batch))::acc)
| x::xs ->
// Take one element from the input and add it to the current batch
loop xs (num + 1) (x::batch) acc
loop input 0 [] []
As a footnote, the imperative version can be made a bit nicer using computation expression for working with IEnumerator, but that's not standard and it is quite advanced trick (for example, see http://fssnip.net/37).
A: A friend asked me this a while back. Here's a recycled answer. This works and is pure:
let batchesOf n =
Seq.mapi (fun i v -> i / n, v) >>
Seq.groupBy fst >>
Seq.map snd >>
Seq.map (Seq.map snd)
Or an impure version:
let batchesOf n =
let i = ref -1
Seq.groupBy (fun _ -> i := !i + 1; !i / n) >> Seq.map snd
These produce a seq<seq<'a>>. If you really must have an 'a list list as in your sample then just add ... |> Seq.map (List.ofSeq) |> List.ofSeq as in:
> [1..17] |> batchesOf 5 |> Seq.map (List.ofSeq) |> List.ofSeq;;
val it : int list list = [[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
Hope that helps!
A: This isn't perhaps idiomatic but it works:
let batchesOf n l =
let _, _, temp', res' = List.fold (fun (i, n, temp, res) hd ->
if i < n then
(i + 1, n, hd :: temp, res)
else
(1, i, [hd], (List.rev temp) :: res))
(0, n, [], []) l
(List.rev temp') :: res' |> List.rev
A: Here's a simple implementation for sequences:
let chunks size (items:seq<_>) =
use e = items.GetEnumerator()
let rec loop i acc =
seq {
if i = size then
yield (List.rev acc)
yield! loop 0 []
elif e.MoveNext() then
yield! loop (i+1) (e.Current::acc)
else
yield (List.rev acc)
}
if size = 0 then invalidArg "size" "must be greater than zero"
if Seq.isEmpty items then Seq.empty else loop 0 []
let s = Seq.init 10 id
chunks 3 s
//output: seq [[0; 1; 2]; [3; 4; 5]; [6; 7; 8]; [9]]
A: My method involves converting the list to an array and recursively chunking the array:
let batchesOf (sz:int) lt =
let arr = List.toArray lt
let rec bite curr =
if (curr + sz - 1 ) >= arr.Length then
[Array.toList arr.[ curr .. (arr.Length - 1)]]
else
let curr1 = curr + sz
(Array.toList (arr.[curr .. (curr + sz - 1)])) :: (bite curr1)
bite 0
batchesOf 5 [1 .. 17]
[[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [11; 12; 13; 14; 15]; [16; 17]]
A: I found this to be a quite terse solution:
let partition n (stream:seq<_>) = seq {
let enum = stream.GetEnumerator()
let rec collect n partition =
if n = 1 || not (enum.MoveNext()) then
partition
else
collect (n-1) (partition @ [enum.Current])
while enum.MoveNext() do
yield collect n [enum.Current]
}
It works on a sequence and produces a sequence. The output sequence consists of lists of n elements from the input sequence.
A: You can solve your task with analog of Clojure partition library function below:
let partition n step coll =
let rec split ss =
seq {
yield(ss |> Seq.truncate n)
if Seq.length(ss |> Seq.truncate (step+1)) > step then
yield! split <| (ss |> Seq.skip step)
}
split coll
Being used as partition 5 5 it will provide you with sought batchesOf 5 functionality:
[1..17] |> partition 5 5;;
val it : seq<seq<int>> =
seq
[seq [1; 2; 3; 4; ...]; seq [6; 7; 8; 9; ...]; seq [11; 12; 13; 14; ...];
seq [16; 17]]
As a premium by playing with n and step you can use it for slicing overlapping batches aka sliding windows, and even apply to infinite sequences, like below:
Seq.initInfinite(fun x -> x) |> partition 4 1;;
val it : seq<seq<int>> =
seq
[seq [0; 1; 2; 3]; seq [1; 2; 3; 4]; seq [2; 3; 4; 5]; seq [3; 4; 5; 6];
...]
Consider it as a prototype only as it does many redundant evaluations on the source sequence and not likely fit for production purposes.
A: This version passes all my tests I could think of including ones for lazy evaluation and single sequence evaluation:
let batchIn batchLength sequence =
let padding = seq { for i in 1 .. batchLength -> None }
let wrapped = sequence |> Seq.map Some
Seq.concat [wrapped; padding]
|> Seq.windowed batchLength
|> Seq.mapi (fun i el -> (i, el))
|> Seq.filter (fun t -> fst t % batchLength = 0)
|> Seq.map snd
|> Seq.map (Seq.choose id)
|> Seq.filter (fun el -> not (Seq.isEmpty el))
I am still quite new to F# so if I'm missing anything - please do correct me, it will be greatly appreciated. | unknown | |
d1985 | train | Solved.
Global variable 'auth2' is automatically initialised each time the page is loaded and can be used to sign users in.
The script is called as:
<script src="https://apis.google.com/js/api:client.js?onload=onLoadCallback" async defer></script>
<script>
var auth2;
var googleUser = {};
var auth3;
window.onLoadCallback = function(){
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
client_id: '**********.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
scope: 'profile email'
});
auth3 = true;
startApp();
})
}
var startApp = function() {
element = document.getElementById('g_login');
auth2.attachClickHandler(element, {},
function(googleUser) {
console.log("4");
document.getElementById('name').innerText = "Signed in: " +
googleUser.getBasicProfile().getName();
angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
}, function(error) {
console.log("5");
alert(JSON.stringify(error, undefined, 2));
});
};
if (auth3)
startApp();
</script> | unknown | |
d1986 | train | Not sure why you have braces after idvid but it should just be
"http://www.hitbox.tv/#!/embedvideo/" + idvid + "?autoplay=true";
To get the media_id of the first object in the data array:
var idvid = data.video[0].media_id;
A: I called the URL and got it using this
data.video[0].media_id
so (dropping the () from the var too as suggested by Andy):
success: function(data) {
$("#latest").attr("src","http://www.hitbox.tv/#!/embedvideo/" +
data.video[0].media_id +
"?autoplay=true");
}
var data = {
"request": {
"this": "\/media\/video\/chairstream\/list"
},
"media_type": "video",
"video": [{
"media_user_name": "chairstream",
"media_id": "783994",
"media_file": "2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938",
"media_user_id": "871797",
"media_profiles": "[{\"url\":\"\\\/chairstream\\\/2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938\\\/chairstream\\\/index.m3u8\",\"height\":\"800\",\"bitrate\":0}]",
"media_type_id": "2",
"media_is_live": "1",
"media_live_delay": "0",
"media_date_added": "2015-11-27 23:16:04",
"media_live_since": null,
"media_transcoding": null,
"media_chat_enabled": "1",
"media_countries": null,
"media_hosted_id": null,
"media_mature": null,
"media_hidden": null,
"media_offline_id": null,
"user_banned": null,
"media_name": "2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938",
"media_display_name": "chairstream",
"media_status": "Chairstream.com - Nov 27th #5",
"media_title": "Chairstream.com - Nov 27th #5",
"media_description": "",
"media_description_md": null,
"media_tags": "",
"media_duration": "6262.0000",
"media_bg_image": null,
"media_views": "9",
"media_views_daily": "2",
"media_views_weekly": "9",
"media_views_monthly": "9",
"category_id": null,
"category_name": null,
"category_name_short": null,
"category_seo_key": null,
"category_viewers": null,
"category_media_count": null,
"category_channels": null,
"category_logo_small": null,
"category_logo_large": null,
"category_updated": null,
"team_name": null,
"media_start_in_sec": "0",
"media_duration_format": "01:44:22",
"media_thumbnail": "\/static\/img\/media\/videos\/2c7\/2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938_mid_000.jpg",
"media_thumbnail_large": "\/static\/img\/media\/videos\/2c7\/2c767c827c6c84a4714b9379983de69449c5a1c1-5658c80c2b938_large_000.jpg",
"channel": {
"followers": "0",
"user_id": "871797",
"user_name": "chairstream",
"user_status": "1",
"user_logo": "\/static\/img\/channel\/chairstream_5602c1d59d02e_large.png",
"user_cover": "\/static\/img\/channel\/cover_53e89056cf3ef.jpg",
"user_logo_small": "\/static\/img\/channel\/chairstream_5602c1d59d02e_small.png",
"user_partner": null,
"partner_type": null,
"user_beta_profile": "0",
"media_is_live": "0",
"media_live_since": "2015-11-30 12:35:33",
"user_media_id": "206125",
"twitter_account": null,
"twitter_enabled": null,
"livestream_count": "1"
}
}]
}
console.log(data.video[0].media_id) | unknown | |
d1987 | train | You are wrong with the path name. Look at the below code.
import { Component } from '@angular/core';
import { Http } from '@angular/http';
//modified the below lines
import { ReleasesComponent } from './app/releases/releases.component';
import { ReleasesService } from './app/releases/releases.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
directives: [ReleasesComponent],
providers: [Http, ReleasesService]
})
export class AppComponent { name = 'My name'; }
Also replace these in all the import statements where ever ReleasesComponent and ReleasesService is needed.
Alternatively, you can also use
import { ReleasesComponent } from './../app/releases/releases.component';
import { ReleasesService } from './../app/releases/releases.service';
A: Seems NgModule reference is missing. Import NgModule and FormModue in app.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; | unknown | |
d1988 | train | You can't put GlSurfaceView into CordovaWebView, but you can place in next/top of to each other.
Create Relative view and put both of them into it. | unknown | |
d1989 | train | If I understand your question, this should do it.
SELECT DISTINCT(referer), COUNT(referer) AS frequency
FROM url_log
GROUP BY referer
ORDER BY frequency DESC;
A: for selecting each different value of a column use this query
SELECT DISTINCT(column) AS columnname_key FROM table ;
to count duplicate use this code
SELECT Count(*) duplicatetable
FROM
(
select columname_to_check_dulicate_values, Count(*)
from tablename
group by name
having Count(*) > 1
) x | unknown | |
d1990 | train | com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
put a break point in and run the debugger. Something is null, and I'm guessing it's the list. It's on like 46.
Btw, I'm gold random player. Used to be high diamond Toss. Good luck with the project.
A: Your ListView is null that means that either don't have a ListView with that id in your layout or android didn't generate the proper id for the list and you have an old one that is incorrect.
Try to refresh the project, delete the R class from the folder gen so that the ID are generated again, restart the IDE. | unknown | |
d1991 | train | Checking every shape in the stage is the only way to check intersections.
If you need some optimizations you can try debouncing or throttle strategies.
E.g. check interactions every 100ms instead of every mousemove or touchmove events. | unknown | |
d1992 | train | I would advise wrapping each portion in its own form:
<?php
$id = $fgmembersite->UserID();
echo "$id";
$db_host = 'localhost';
$db_name= 'site';
$db_table= 'action';
$db_user = 'root';
$db_pass = '';
$con = mysql_connect($db_host,$db_user,$db_pass) or die("خطا در اتصال به پايگاه داده");
$selected=mysql_select_db($db_name, $con) or die("خطا در انتخاب پايگاه داده");
mysql_query("SET CHARACTER SET utf8");
$dbresult=mysql_query("SELECT tablesite.name,
tablesite.family,
tablesite.username,
tablesite.phone_number,
tablesite.email,
action.service_provider_comment,
action.price,
action.date,
job_list.job_name,
relationofaction.ind
FROM $db_table
INNER JOIN job_list
ON job_list.job_id=action.job_id
INNER JOIN relationofaction
ON relationofaction.ind=action.ind
INNER JOIN tablesite
ON tablesite.id_user=action.service_provider_id
AND action.customer_id='$id'", $con);
$i = 1;
while($amch=mysql_fetch_assoc($dbresult)){
echo "<form id='form_$i' method='post' action='{$_SERVER['PHP_SELF']}' accept-charset='UTF-8'>\r\n";
echo '<div dir="rtl">';
echo "نام خدمت دهنده: "."   ".$amch["name"]." ".$amch["family"]."   "."شماره تماس: ".$amch["phone_number"]."   "."ایمیل: ".$amch["email"].'<br>'
."شغل انجام شده: ".$amch["job_name"].'<br>'
."تاریخ انجام عملیات: ".$amch["date"].'<br>'
."هزینه ی کار: ".$amch["price"]." تومان".'<br>'
.$amch["service_provider_comment"].'<hr/>';
echo '<label for="explain">اگر توضیحاتی برای ارائه در این باره دارید، ارائه دهید</label> <br />';
echo '<textarea name="explain" id="explain" cols="" rows="" style="width:300 ;height:300"></textarea>'.'<br/>';
echo '<label for="rate">امتیاز این عملیات را ثبت نمایید: </label> <br />';
echo '<select name="vote">';
echo ' <option value="عالی">عالی</option>';
echo ' <option value="عالی">خوب</option>';
echo ' <option value="عالی">متوسط</option>';
echo ' <option value="عالی">بد</option>';
echo '</select>';
echo '<br/>';
echo '<input type="submit" name="submit" value="ارسال نظر شما"/>';
echo '<hr/>';
echo '<hr/>';
echo '</div>';
echo "</form>\r\n";
$i++;
}
?>
You will find a number of little fixes in this code. This will result in a number of forms, each with a unique ID, posting to the same place.
A: With respect to @Twisty answer, I would like to come with my final solution to your submission problem.
First of all we need to define which raw to be updated, therefore you need to tell your update statement which ind to be updated.
To do that we need to pass ind in out submission form to out update statement, we added a hidden input field and pass out ind value like this.
<input type="hidden" name="ind" value="' . $amch["ind"] . '">;
Next we need to fetch the value and update our data by adding following:
($_POST['ind'])
So the final solution will look like this:
echo '</select>';
echo '<input type="hidden" name="ind" value="' . $amch["ind"] . '">'; //new line
echo '<br/>';
echo '<input type="submit" name="submit" value="ارسال نظر شما"/>';
echo '<hr/>';
echo '<hr/>';
and in your update statement:
$ins = "UPDATE $db_table
SET
customer_comment='" . mysql_escape_string($_POST['explain']) . "',
vote='" . mysql_escape_string($_POST['vote']) . "'
WHERE ind=".($_POST['ind']); // to define the ind value
And wala, it works.
NOTE:
Just be a ware of, I used the updated code of @Twisty and the final solution on it. | unknown | |
d1993 | train | caniuse.com explains that:
The High Efficiency Video Coding (HEVC) compression standard is a video compression format intended to succeed H.264
and further reveals that browser support for HEVC is currently very poor.
@Gyan comments that:
Your source video is HDR. You'll have to tonemap it to SDR.
Now I assume @Gyan knows it HDR based on the fact that its using HEVC. This article explains HDR (High Dynamic Range) and talks in detail how it impacts brightness, color and contrast.
Finally, this article explains that HDR looks bad - e.g. brightness, contrast and color issues - on devices that do not support HDR. Thankfully it also gives an ffmpeg fix by using this filter:
-vf zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p
Adding this flag to my existing ffmpeg command did the HDR to SDR (Standard Dynamic Range) conversion / tonemap, making it work on Chrome and fixing my problem.
NOTE: Detecting HDR is an issue in its own right so I won't cover that here but please refer to this link | unknown | |
d1994 | train | facebooklikes: Well, developer.facebook has limitation. So you probably need to hire an expert in programming. | unknown | |
d1995 | train | Try using
.visamastercard, .shipna {
display: inline-block;
}
There will be a space between the icon as long as the img tags aren't immediately adjacent to each other (i.e., there's a newline or space between the img tags). | unknown | |
d1996 | train | From the source of your page it can be seen that your problem start with:
<html> lang="en">
you need to change that to:
<html lang="en"> | unknown | |
d1997 | train | I have added a button to the frame and called the method which you wrote and it worked fine for me.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class TableSetEx
{
static JTable pref_table;
public static void main(String[] args) {
pref_table = new javax.swing.JTable();
pref_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"MONDAY", null, null, null, null},
{"TUESDAY", null, null, null, null},
{"WEDNESDAY", null, null, null, null},
{"THURSDAY", null, null, null, null},
{"FRIDAY", null, null, null, null},
{"SATURDAY", null, null, null, null}
},
new String [] {
"DAY", "9 A.M-11 A.M", "11 A.M-1 P.M", "1 P.M-3 P.M", "3 P.M-5 P.M"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
JButton button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Some hardceded cell.
set_tab_val(true,2,3);
}
});
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(pref_table), BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void set_tab_val(boolean x,int r,int c)
{
pref_table.setValueAt(true,r,c);
}
} | unknown | |
d1998 | train | Thanks to @user16320675's comment, I'm answering my own question. The reason is that the number 988530483551494912L has precision beyond the limit of the double type's precision, and Double.toString() (and similarly %f) will, as per documentation, only use the minimum number of significant digits required to distinguish a double number from adjacent numbers. Adjacent numbers are those that have the smallest representable difference from the original, on either side of it.
This can be demonstrated using Math.nextAfter to show the adjacent numbers:
import static java.lang.Math.nextAfter;
double x = (double)988530483551494912;
System.out.println(nextAfter(x, Double.MIN_VALUE)); ==> 9.8853048355149478E17
System.out.println(x); ==> 9.8853048355149491E17
System.out.println(nextAfter(x, Double.MAX_VALUE)); ==> 9.8853048355149504E17
So, as we can see, there is no point in adding any more significant figures because this string representation already has enough digits to distinguish the number from adjacent values.
However, a question still remains: it shows 17 significant figures, but 16 would be sufficient. I'm not sure why it issues an extra final digit. | unknown | |
d1999 | train | I'm not sure if this is what you are asking, but I interpreted this as list the files in a given directory, and then check if the input is in the file.
import os
string = input("Please type the input ")
directory = "c://files//python"
for file in os.listdir(directory):
if file.endswith(".txt"):
filecontent = open(file, "r")
if string in filecontent.read():
print("The file that matches the input was found at" + file)
Line 2: Set the string to whatever the input is
Line 3: Use double slashes to avoid escape characters http://learnpythonthehardway.org/book/ex10.html
Line 4: Goes through every file in the directory. listdir returns a list with all the file names
Line 5: Can change this to .jpg, .png, etc
Line 6: Opens the file contents
Line 7: Reads the file's contents into a string, then check if the input is in said string | unknown | |
d2000 | train | In order to be able to chain methods, those methods need to return the original Helper instance. Try returning $this from inside the methods. Like RomanPerekhrest commented however, I dont think the methods you listed here are suitable for chaining. You would be better off with adding another method to your class that combines the two you stated here.
I'm not exactly sure what you are trying to do, but something along the lines of below might be what you are looking for:
public function redirect($page){
if($this->is_active_page($page)){
$this->go_to_dashboard();
}
}
Lastly, you could think about reducing the scope of your is_active_page and go_to_dashboard functions, if they no longer need to be called from outside the Helper class. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.