text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
DatagridView Highlight Event - WINFORM C#
I have a combobox which is connected to the database so I populate the value of my combobox based on what's in my database. my combobox is another FORM from the datagrid. So here's I want to achieve.
form1 = datagrid (based on the database)
form2 = combobox (based on the database)
I want that If I highlight a certain row (My selection mode = fullrowselect) and press a button the comboBox will automatically point to that row.
for ex.
datagrid
name: Joe (highlighted)
*user clicks the button whch in my case is edit
*load edit form
comboBox.SelectedIndex is = highlighted row (which the user clicks)
I can show you my code if it helps. thanks :))
THANKS! :))
A:
You can try to set in the following ways, you can pass the value Joe to the other form via a parameter in the constructor. This could be then used to select you required value in the ComboBox
comboBox2.SelectedIndex = comboBox2.Items.IndexOf("Joe");
comboBox2.SelectedText = "Three"; // or SelectedValue depending on how you are binding
EDIT
Avoid accessing the grid directly from the other form, expose the value required as a property or better pass it to the new form as parameter.
Joe could be the value of the cell like dataGridView2.CurrentRow[0].FormattedValue and pass this to the new form constructor like new Form2(object datagridvalue). Then use the value in the form later on.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add onClickListener in a Map CustomView
I created a Custom view to show a map in others fragments or activities.
But I want to get a simple click in frame, like google maps app does.
Anyone could help me?
There's custom view:
public class MapView extends FrameLayout {
private Subject<GoogleMap> mapSubject;
private static final float MAP_ZOOM_LEVEL_STATIC = 12.0f;
private Circle mCircle;
public MapView(@NonNull Context context) {
super(context);
init(context, null);
}
public MapView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public MapView(@NonNull Context context, @Nullable AttributeSet attrs,
@AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
if (!isInEditMode()) {
FragmentTransaction fragmentTransaction =((AppCompatActivity)context)
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(getId(), mapFragment);
fragmentTransaction.commit();
mapSubject = BehaviorSubject.create();
Observable.create((ObservableOnSubscribe<GoogleMap>) e -> mapFragment.getMapAsync(e::onNext))
.subscribe(mapSubject);
mapSubject.subscribe(googleMap -> mCircle = googleMap.addCircle(new
CircleOptions().center(new LatLng(0.0f, 0.0f)).radius(0)));
}
}
/**
* Update position and create a new Circle and move camera to new position
*
* @param location The location to be updated.
*/
public void updatePosition(LatLng location) {
mapSubject.subscribe(googleMap -> {
mCircle.remove();
mCircle = googleMap.addCircle(new
CircleOptions().center(location).radius(15)
.strokeWidth(10)
.strokeColor(Color.RED)
.fillColor(Color.RED));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,
MAP_ZOOM_LEVEL_STATIC));
});
}
/**
* This method is responsible to add a polyline in google maps
*
* @param results array with directions
*/
public void addPolyline(DirectionsResult results) {
if(results != null) {
mapSubject.subscribe(googleMap -> {
List<LatLng> decodedPath =
PolyUtil.decode(results.routes[0]
.overviewPolyline
.getEncodedPath());
googleMap.addPolyline(new
PolylineOptions()
.addAll(decodedPath)
.width(10)
.color(Color.RED)
.geodesic(true));
updatePosition(decodedPath.get(0));
});
}
}
}
That's how I use in xml:
<com.name.of.package.custom_view.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Thats how I'm trying to identify click (without success, because in debugger didn't pass here):
MapView mapView = (MapView)findViewById(R.id.mapView)
mapView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toogle(view);
Toast.makeText(mContext, "Map clicked!", Toast.LENGTH_SHORT).show();
}
});
A:
Searching about, I find a way to verify simple click in maps.
Create an function in MapView.java
/**
* This method is responsible to add a MapClickListener to handle simple clicks in map.
*
* @param mapClickListener class that will handle simple click
*/
public void setOnMapClick(GoogleMap.OnMapClickListener mapClickListener) {
mapSubject.subscribe(googleMap -> googleMap.setOnMapClickListener(mapClickListener));
}
After that, set an listener when you use mapView, for example:
mapView.setOnMapClick(this);
PS.: To put this you need to implement GoogleMap.OnMapClickListener in you activity/fragment that you are using mapView.
After implement, put override method in your fragment/activity:
@Override
public void onMapClick(LatLng latLng) {
if (Logger.DEBUG) Log.d(TAG, "onMapClick");
// Do something
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Matplotlib: Automatically displaying time column as 2 hour ticks on y axis in scatterplot
I have this data:
Time = ['2017-03-13 00:01:00', '2017-03-13 00:02:00', '2017-03-13 23:59:00']
Speed = [20, 40.5, 100]
Kilometer = [1.4, 2.0, 4.1]
N130317 = pd.DataFrame({'Time':Time, 'Speed':Speed, 'Kilometer':Kilometer})
I have converted the time using:
N130317['Time'] = pd.to_datetime(N130317['Time'], format = '%Y-%m-%d %H:%M:%S')
N130317['Time'] = pd.to_datetime(N130317['Time'], format).apply(lambda x: x.time())
N130317['Time'] = N130317['Time'].map(lambda t: t.strftime('%H:%M'))
I have made a plot using:
marker_size=1 #sets size of dots
cm = plt.cm.get_cmap('plasma_r') #sets colour scheme
plt.scatter(N130317['Kilometer'], N130317['Time'], marker_size, c=N130317['Speed'], cmap=cm)
plt.title("NDW 13-03-17")
plt.xlabel("Kilometer")
plt.ylabel("Time")
plt.colorbar().set_label("Speed", labelpad=+1) #Makes a legend
plt.show()
But the graph shows up like this (all the time stamps show up on the y axis which evidently doesn't have the space for them - there is a time stamp for every minute in my date):
What can I do to solve this? Any help would be greatly appreciated. I have tried so many things online.
A:
I used these lines to create some data, replace them with your data:
from itertools import product
Time = [f'2017-03-13 {H}:{M}:{S}' for H, M, S in list(product([('0' + str(x))[-2:] for x in range(0, 24)],
[('0' + str(x))[-2:] for x in range(0, 60)],
[('0' + str(x))[-2:] for x in range(0, 60)]))]
Speed = list(130*np.random.rand(len(Time)))
Kilometer = list(50*np.random.rand(len(Time)))
N130317 = pd.DataFrame({'Time':Time, 'Speed':Speed, 'Kilometer':Kilometer})
I converted the N130317['Time'] to timestamp with this line:
N130317['Time'] = pd.to_datetime(N130317['Time'], format = '%Y-%m-%d %H:%M:%S')
Then I set the yaxis format property to date:
import matplotlib.dates as md
ax=plt.gca()
xfmt = md.DateFormatter('%H:%M')
ax.yaxis.set_major_formatter(xfmt)
The whole code is:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as md
from itertools import product
Time = [f'2017-03-13 {H}:{M}:{S}' for H, M, S in list(product([('0' + str(x))[-2:] for x in range(0, 24)],
[('0' + str(x))[-2:] for x in range(0, 60)],
[('0' + str(x))[-2:] for x in range(0, 60)]))]
Speed = list(130*np.random.rand(len(Time)))
Kilometer = list(50*np.random.rand(len(Time)))
N130317 = pd.DataFrame({'Time':Time, 'Speed':Speed, 'Kilometer':Kilometer})
N130317['Time'] = pd.to_datetime(N130317['Time'], format = '%Y-%m-%d %H:%M:%S')
marker_size = 1 # sets size of dots
cm = plt.cm.get_cmap('plasma_r') #sets colour scheme
plt.scatter(N130317['Kilometer'], N130317['Time'], marker_size, c=N130317['Speed'], cmap=cm)
ax=plt.gca()
xfmt = md.DateFormatter('%H:%M')
ax.yaxis.set_major_formatter(xfmt)
plt.title("NDW 13-03-17")
plt.xlabel("Kilometer")
plt.ylabel("Time")
plt.colorbar().set_label("Speed", labelpad=+1) #Makes a legend
plt.show()
and it gives me this plot:
Please, note that the pd.to_datetime() has to be applied to a datetime object, not to a string. If you run this code:
hour = '2017-03-13 00:00:00'
pd.to_datetime(hour, format = '%H:%M')
You will get this error message:
ValueError: time data '2017-03-13 00:00:00' does not match format '%H:%M' (match)
So you need to use this code, in order to convert the string to a datetime:
hour = '2017-03-13 00:00:00'
hour = datetime.strptime(hour, '%Y-%m-%d %H:%M:%S')
pd.to_datetime(hour, format = '%H:%M')
This depends on the data type you have, I did not encounter this issue since I re-created the data as wrote above.
Version info
Python 3.7.0
matplotlib 3.2.1
numpy 1.18.4
pandas 1.0.4
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ESP8266 with Serial AT commands
I am trying to communicate with my ESP8266-07 through Arduino Nano Serial. I am using AT commands to reset, connect wifi, connect TCP server and so on. I have got one functional script, so i know that ESP8266 is wired correctly. I am using 3.3V to 5V logic converter and so on... This is the older functional script:
void esp_connect() {
Serial.println("AT+RST");
delay(2);
esp_timefuse = millis();
while(Serial.find("ready") == false) {
if(esp_timefuse - millis() >= 5000)
esp_connect();
}
Serial.println("AT+CWMODE=3");
delay(2);
esp_timefuse = millis();
while(Serial.find("OK") == false) {
if(esp_timefuse - millis() >= 2000)
esp_connect();
}
Serial.println("AT+CWJAP=\"WiFi 7-pekiel\",\"43664366\"");
delay(2);
esp_timefuse = millis();
while(Serial.find("OK") == false) {
if(esp_timefuse - millis() >= 2000)
esp_connect();
}
Serial.println("AT+CIPMUX=1");
delay(2);
esp_timefuse = millis();
while(Serial.find("OK") == false) {
if(esp_timefuse - millis() >= 2000)
esp_connect();
}
Serial.println("AT+CIPSTART=0,\"TCP\",\"10.10.10.6\",3600");
delay(2);
esp_timefuse = millis();
while(Serial.find("OK") == false) {
if(esp_timefuse - millis() >= 2000)
esp_connect();
}
}
But I am not satisfied with it. I am trying to do it best. So i wrote this script:
void esp_connect() {
Serial.println("AT+RST");
Serial.flush();
Serial.setTimeout(5000);
if(Serial.find("ready"));
else esp_connect();
Serial.println("AT+CWMODE=3");
Serial.flush();
Serial.setTimeout(2000);
if(Serial.find("OK"));
else esp_connect();
Serial.println("AT+CWJAP=\"WiFi 7-pekiel\",\"43664366\"");
Serial.flush();
if(Serial.find("OK"));
else esp_connect();
Serial.println("AT+CIPMUX=1");
Serial.flush();
if(Serial.find("OK"));
else esp_connect();
Serial.println("AT+CIPSTART=0,\"TCP\",\"10.10.10.6\",3600");
Serial.flush();
if(Serial.find("OK"));
else esp_connect();
}
When I am testing this new script through Serial monitor everything works. I am simulating ESP8266 so I just type "OK" and "OK" just like ESP8266. But when I connect it to ESP8266 nothing works. Where is the Mistake in my script? Is my usage of Serial.find() correct?
A:
I found that code is working perfectly and the mistake was too short timeout for connect to wifi. Two second was too short time duration for ESP8266. Quite a dumb mistake...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I have VS 2013 ignore certain syntax errors until I build?
For example, I could pretty much always do without the "not all code paths return a value" error squiggly. This generally means I'm in the process of writing the method. I don't need to be told it doesn't return a value. If I forget to add a return value, VS can tell me that when it builds. But I never want that while I'm working; it's annoying and usually tells me something I already know.
For another example, I could do without the errors that show up while I'm in the process of writing a switch statement, such as the one that tells me I don't have a break statement yet, as I'm still working on whatever case.
A:
You can try to disable "Show live semantic errors",
http://www.devcurry.com/2011/01/disable-squiggly-or-wavy-lines-in.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compiler warning "assignment from distinct objective-c type"
I'm learning objective-c, working through Aaron Hillegass' book "Cocoa Programming for Mac OS X - Third Edition". I'm working in Xcode to develop some of the example code, and keep getting a compiler warning on the last line of this method:
- (void) setEntryDate:(NSCalendarDate *) date {
[date retain];
[entryDate release];
entryDate = date;
}
The warning reads "warning: assignment from distinct objective-c type". What causes this warning? How do I prevent it from happening again?
It doesn't seem to affect execution of the program, but I don't understand what the problem is, or even if there really is a problem (could this just be a paranoid compiler?).
A:
NSCalendar and NSCalendarDate are indeed distinct types. You should decide which one you want entryDate to be (probably NSCalendarDate, judging by the "date" thing").
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cakephp change URL behaviour
We are developing a site using CakePHP.
We have a windows IIS server (shared hosting) with PHP5, that does not support .htaccess or mod_rewrite but still we have the site up and running and developed a lot of things.
The current URL structure is something like this:
mydomain/index.php/user/add
We want to change this to something like:
mydomain/index.php?controller=user&action=add
We want to do this as we are facing some unexpected session expired problems and we doubt that it is due to the user travelling from one url to another like this:
mydomain/index.php/user/add
to
mydomain/index.php/list/edit
this change the domain for IIS or PHP which cause the session to expire, but cake is interpreting the pages perfectly.
If there is a way to change the behiviour of Cake to take the URL's with question and amphersand, it will be great.
Thanks in advance.
A:
session expiring is not caused by the url structure.
have you check?
Configure::write('Session.timeout', '3600'); in core.php. make it longer
Configure::write('Security.level', 'high'); in core.php. make it medium or low
Configure::write('Session.checkAgent', false); in core.php make it false. can cause problem with ajax calls
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is $SL_n(\mathbb{R})$ a normal subgroup in $GL_n(\mathbb{R})$?
Let $N= GL_n(\mathbb{R})$ and $M=SL_n(\mathbb{R})$. Is $M$ normal subgroup in $N$? Why or why not?
I know how to do this with $GL_2(\mathbb{R})$ and $SL_2(\mathbb{R})$ but with $N= GL_n(\mathbb{R})$ and $M=SL_n(\mathbb{R})$ I don't even know all of their elements so I can't check the left and right cosets of $M$ in $N$.
A:
Remember that $H$ is normal in $G$ if $ghg^{-1} \in H$ for all $g \in G$, $h \in H$. Also note that for square matrices $A, B$ we have $\det(AB) = \det(A)\det(B)$.
A:
Hint:
Is the determinant map
$$\det:GL_n(\Bbb R)\to\Bbb R^*\,$$
a homomorphism....?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error using stable_partiton
I am trying to solve a topcoder problem where I have to remove all the vowels from a string unless the string contains only vowels. I am trying to partition the string using stable_partition and a function isVowel.
`
// {{{ VimCoder 0.3.6 <-----------------------------------------------------
// vim:filetype=cpp:foldmethod=marker:foldmarker={{{,}}}
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>
using namespace std;
// }}}
class VowelEncryptor
{
public:
bool isVowel(char letter)
{
return (letter == 'a' || letter == 'e' || letter == 'o' || letter == 'o' || letter == 'u');
}
vector <string> encrypt(vector <string> text)
{
int nElements = text.size();
for (int i = 0; i < nElements; i++)
{
string::iterator bound = stable_partition(text[i].begin(), text[i].end(), isVowel);
if (bound != text.end())
{
text[i].erase(text[i].begin(), bound);
}
}
return text;
}
};
But on compiling I am getting this error message:
(3 of 458): error: cannot convert ‘VowelEncryptor::isVowel’ from type ‘bool (VowelEncryptor::)(char)’ to type ‘bool (VowelEncryptor::*)(char)’
A:
Try making isVowel static.
A pointer to a member function can't be used without an actual object instance to be called on, which stable_partition can't do without help. Either make the function static or use std::bind.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove all Instance on stage as3
Im having trouble on removing instances on the stage.
The error I keep getting after I click the button 2 times is
"The supplied DisplayObject must be a child of the caller"
Can somebody help me with this?
package src
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip
{
var positionY:Number = 80;
var positionX:Number = 0;
var motion:MovieClip;
var fCombo:Array = new Array();
var n:Number;
public function Main()
{
generate.addEventListener(MouseEvent.MOUSE_UP, loop);
generate.addEventListener(MouseEvent.MOUSE_DOWN, remove);
n = Number(inputText.text);
}
function loop(me:MouseEvent):void
{
var combo:Array = [Punch, Kick, Knee, Elbow];
n = Number(inputText.text);
for(var i:Number = 0;i < n;i++ )
{
motion = new combo[randomNumber(4)]();
fCombo.push(motion);
motion.y = positionY;
motion.x = positionX;
positionX += 100;
addChild(motion);
if (i == 4 || i == 9 || i == 14)
{
positionY += 40;
positionX = 0;
}
}
}
function remove(me:MouseEvent):void
{
for (var j:Number = 0; j < n; j++ )
{
removeChild(fCombo[j]);//error
}
positionY = 80;
positionX = 0;
}
function randomNumber(max:Number):Number
{
return(Math.floor(Math.random() * max ));
}
}
}
A:
You're adding the new objects you create to the array, and then using that to remove them. But you're forgetting to either create a new list or remove the objects from the old list. So, when time comes to loop over the list you're trying to remove objects that have already been removed.
You can fix this in several ways, one is to remove objects from the stage AND array in your loop:
function remove(me:MouseEvent):void
{
while(fCombo.length)
{
removeChild(fCombo.pop());
}
positionY = 80;
positionX = 0;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to find element by color in selenium using python
This is my case.Two div case are the almost the same, but I need click only "Claim" from first one.Can I use background color to indentify my element? Or any other ideas?
1.
<div class="well well-sm" style="width:150px;margin:5px;text-align:center;float:left;">
<p><b style="color:#227A11">$0.005</b></p>
<p><a href="./seecashlinks.php?ocd=open&id=96396" class="btn btn-success" style="background:#0373F1;">Claim</a></p>
</div>
2.
<div class="well well-sm" style="width:150px;margin:5px;text-align:center;float:left;">
<p><b style="color:#227A11">$0.001</b></p>
<p><a href="./seecashlinks.php?ocd=open&id=22952" class="btn btn-success" style="background:#CC07DD;">Claim</a></p>
</div>
A:
This is how you can identify the div-element that contains an anchor element with the background color you were searching for using xpath:
driver.findElement(By.xpath("//a[@style='background:#0373F1;']/ancestor::div[1]"));
* If there are several anchor-elements with that background color on your site you would have to modify your xpath accordingly (you would need to first search for all "possible" parent elements
In your case you could for example first search for all div elements that contain class "well":
"//div[contains(@class, 'well')]/a[@style='background:#0373F1;']/ancestor::div[1]"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert HH:MM:SS
I'm currently working on a call report however i've hit a snag. I need to calculate how long an agent has spent on the phone, the source data is in HH:MM:SS for the call duration. as in 1hr 12mins 10 seconds as appose to a number of seconds. So if 2 agents had taken 2 calls the time spent would sum up for that day.
Is it possible to change this into seconds? or can anyone suggest something a but better?
A:
Time to Seconds
Assuming it's a time datatype then you can change to seconds like this
DATEDIFF(second, 0, @YourTimeValue)
And here's a simple aggregation example (ie sum)
DECLARE @data TABLE (TimeColumn TIME)
INSERT INTO @data values ('01:12:10'), ('02:15:45')
SELECT SUM(DATEDIFF(SECOND, 0, TimeColumn)) FROM @data
Which results in 12475 seconds
Seconds to Time
And I guess to complete the picture to convert back to time format from seconds
SELECT CAST(DATEADD(SECOND, @TotalSecondsValue, 0) AS TIME)
or as part of the aggregation example
DECLARE @data TABLE (TimeColumn TIME)
INSERT INTO @data VALUES ('01:12:10'), ('02:15:45')
SELECT CAST(DATEADD(SECOND, SUM(DATEDIFF(SECOND, 0, TimeColumn)), 0) AS TIME) FROM @data
Which results in a time of 03:27:55
A:
If column type is datetime then:
(DATEPART(hh, @yourValue) * 60 * 60) + (DATEPART(mi, @yourValue) * 60) + DATEPART(s, @yourValue)
Datepart reference
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Function-only answers to function-or-program questions should provide a test program
From Default for Code Golf: Program, Function or Snippet?, it is clear that the default for code-golf is to allow program and function answers.
For function-only answers, it may be advantageous for answers to include a complete test program that calls the function for some examples, so that it is easy for users unfamiliar with the given language to verify the answer.
Should we require this?
A:
A test program is helpful, but not required. The usefulness of an answer drives the vote score. This should be incentive enough for users to include a test program.
A:
What should be required, in my opinion, is what the function which solves the problem is called. Since an answer may define many functions, this should be clarified.
This is especially important in languages such as Pyth, where a named function may be defined without using the name anywhere in the program.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can Yarn and NVM Coexist on Windows?
Yarn was working for me until I decided I needed multiple versions of node. So I uninstalled yarn and installed nvm, following instructions from the following guide
I then successfully re-installed yarn using the msi installer. Unfortunately, yarn global add [name] installed packages in a location seemingly spanning all nvm-controlled node versions, and yet equally inaccessible to all of them. That is, npm could not find anything installed globally by yarn. Or, for example, after using yarn to install gulp globally, I find that gulp is not available on the command line (and its cmd files are not found in c:\program files\nodejs).
So I uninstalled the yarn msi. I then re-installed yarn simply with npm i --global yarn, as suggested here. This, at last, caused yarn to be linked to the current nvm controlled node version. Excellent.
However, when I again tried yarn to install global packages I discovered they were not installed properly. For example I ran:
nvm use 5.11.0
yarn global add jspm gulp karma karma-cli
The packages installed successfully, but when I try "gulp" from the command line, it is not available. Also, when I npm ls --global --depth=1 I see that the packages I installed are nowhere to be found. If I try yarn global ls --depth=0 it takes a very long time to tell me that my packages (jspm, gulp, karma, karma-cli) are in fact installed.
Worse, I later decided to do the following:
nvm use 7.3.0 //fresh node install...no packages installed
npm i --global yarn
yarn global ls
The yarn command then shows me the same packages that I installed globally when nvm use 5.11.0 had been in effect. In short, yarn insists on some kind of global install location (separate from what nvm controlled node versions see). I also do not know the file location where yarn is keeping those global packages, so I'm not sure how "clean" of an uninstall I could attempt.
In short, I don't think yarn and nvm are compatible. Is this correct?
Version Info
Windows 10 Pro, x64
nvm v1.1.3
yarn v0.21.3
node 5.11.0 (selected by NVM)
node 7.8.0 (selected by NVM)
Update
I found issue 1491 might contain my answer. I learned that:
The location of yarn packages installed globally is intentionally in a different location than packages installed globally for npm.
There is indeed a yarn bug which prevents globally installed packages from being available on the command line (doh!). This defeats the purpose of the global install of a package.
The location where Yarn keeps its data on Windows is %LocalAppData%\Yarn
I think the reason yarn was working before I installed nvm, is simply that I had not tried using to install global packages...and thus had not yet noticed the bug. In short, I think it is fine with nvm. However, I now feel I am wasting my time using the npm i --global yarn approach to installing yarn...since yarn will simply put all its global packages into one spot anyway. And, due to the current bug, the only tool I should use for installing global packages is npm itself.
A:
It's a while ago you asked, but I just stepped over your question.
You can simply install yarn as node module globally:
npm i -g yarn
This works very nicely when using nvm-windows.
Additional hint: Since switching to a new node version with nvm requires to re-install all globally installed node modules, I started to use yarn instead of npm for managing all other global modules except of npm and yarn itself. This way, updating node is quite painless.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using results of an aggregation to filter documents in another index
I have 2 indexes:
users
navigations
Let's say users looks like this:
{
"properties": {
"cookies": {"type": "keyword"},
"name": {"type": "text"}
}
}
And navigations looks like this:
{
"properties": {
"url": {"type": "keyword"},
"cookie_id": {"type": "keyword"}
}
}
As you can notice, users and navigations can be joined together by the cookie_id and cookies fields.
Actually my indexes have more fields but only these are necessary to demonstrate my issue.
I'm storing users and navigations in 2 different indexes instead of using a join mapping or a nested mapping because I'll have a lot more navigations than users and in the majority of my search use cases I'll only search for users, thus I don't want to maintain a list of navigations per users. I prefer keeping them separate (I also have some other constraints that drive my choice for 2 separate indexes such as data reconciliation, etc...).
What I'd like to do is a query/aggregation like this: "give me all users with name Fabien that navigated 5 times on url http://example.com"
I had the following query/aggregation so far (the search query is done on my 2 indexes):
POST /users,navigations/_search
{
"query": {
"bool": {
"must": [
{"match": {"name": "Fabien"}}
]
}
},
"aggregations": {
"all_navs": {
"global": {},
"aggregations": {
"cookies": {
"terms": {"field": "cookie_id"},
"aggregations": {
"page_visited": {
"filter": {
"bool": {
"must": [
{"term": {"url": "http://example.com"} }
]
}
},
"aggregations": {
"number_page_visited": {
"value_count": {"field": "type"}
}
}
},
"count_filter": {
"bucket_selector": {
"buckets_path": {
"count": "page_visited>number_page_visited"
},
"script": "params.count > 5"
}
}
}
}
}
}
}
}
With this query I can filter my users with name = Fabien, and I can get the cookie_id value from navigations where there are at least 5 documents with url = http://example.com.
But I can't figure out how to use the cookie_ids from my aggregation to filter my users.
Any idea?
Thank you!
A:
Solution with two separate indices
Because elasticsearch is not a relational database, you will not be able to retrieve your results in a single request. It is a strong limitation of elasticsearch, but it is also a major reason for its great performances.
Basically, elasticsearch will compile your query into a Lucene query and perform a scan of the indices using the Lucene query. There is no mechanism where some parameter in the query (e.g. the value of the user_id field) is dependent of the result of another query (e.g., find all id values from users where the name is "Fabien").
You will have to perform the join externally :
first, retrieve all documents from index users where name is Fabien. If the number of documents is not bounded, you will have to perform a scroll search or use search_after
second, retrieve all documents from index navigation where user_id is in the set of documents returned from the first request and where your other criterion are satisfied.
This approach can be slow and you do not have guarantees that the users index has not been updated when you run the second query.
Solution with join mapping
Actually if you use join type mapping, you do not need to use aggregations for your use case.
Please note that join field has several restriction and is not recommended as the default solution to model one to many relationships.
Here is a working example to should work for your requirement.
The mapping : contains both user and navigation field plus a join field.
PUT /user_navigation
{
"mappings": {
"properties": {
"cookies": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"join_field": {
"type": "join",
"relations": {
"user": "navigation"
}
}
}
}
}
Add some testing documents. Two parent documents have name: Fabien but only one have two children with cookies: http://example.com. The other document has two children with cookies: http://example.com but is not named with Fabien.
POST user_navigation/_doc/_bulk
{ "index" : { "_index" : "user_navigation", "_id" : "1" } }
{ "name" : "Fabien", "join_field": "user" }
{ "index" : { "_index" : "user_navigation", "_id" : "2" } }
{ "name" : "Fabien", "join_field": "user" }
{ "index" : { "_index" : "user_navigation", "_id" : "3" } }
{ "name" : "Autre", "join_field": "user" }
{ "index" : { "_index" : "user_navigation", "routing": "1" } }
{ "cookies": "http://example.com", "join_field": { "name": "navigation", "parent": "1" }}
{ "index" : { "_index" : "user_navigation", "routing": "1"} }
{ "cookies": "http://example.com", "join_field": { "name": "navigation", "parent": "1" }}
{ "index" : { "_index" : "user_navigation", "routing": "2"} }
{ "cookies": "http://example.com", "join_field": { "name": "navigation", "parent": "2" }}
{ "index" : { "_index" : "user_navigation", "routing": "2"} }
{ "cookies": "other_url", "join_field": { "name": "navigation", "parent": "3" }}
{ "index" : { "_index" : "user_navigation", "routing": "3"} }
{ "cookies": "http://example.com", "join_field": { "name": "navigation", "parent": "3" }}
{ "index" : { "_index" : "user_navigation", "routing": "3"} }
{ "cookies": "http://example.com", "join_field": { "name": "navigation", "parent": "3" }}
The following request use has_child query and will return only the document with name: Fabien and such that it has at least two children document with cookies: http://example.com.
GET user_navigation/_doc/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"name": "Fabien"
}
},
{
"has_child": {
"type": "navigation",
"query": {
"term": {
"cookies": "http://example.com"
}
},
"min_children": 2,
"inner_hits": {}
}
}
]
}
}
}
The response will contain only the document with id 1.
"min_children" parameter allows to change the minimum number of children documents that must fulfill the request.
"inner_hits": {} allows to retrieve the children documents in the response.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Looking for elementary proof that irreducible/smooth curve in $\mathbb C^2$ is connected in Euclidean topology of $\mathbb C^2$
Let $f(X,Y)\in \mathbb C[X,Y]$ be an irreducible polynomial. I know that the zero set of $f$ , $V(f):=\{(a,b)\in \mathbb C^2 : f(a,b)=0\}$ is connected in the usual Euclidean topology of $\mathbb C^2$ . Is there a proof of this result without using too much algebraic geometry ? What are the most elementary proof of this result ?
If we assume that $V(f)$ is smooth i.e.
$$\forall p \in \mathbb C^2\colon\quad(\partial f/\partial X , \partial f/\partial Y)|_p\ne (0,0),$$ can we make a proof substantially more elementary ?
A:
How about this? By Noether normalization, after a generic change of coordinates, our curve $C$ is of the form
$$y^d + f_1(x) y^{d-1} + \cdots + f_d(x)=0$$
for various polynomials $f_j$.
Let $\Delta(x)$ be the discriminant of this polynomial as a polynomial in $y$. Since $f$ is squarefree as a polynomial in $\mathbb{C}[x,y]$, we know that $\Delta(x)$ is not identically zero. So it has finitely many zeroes $z_1$, $z_2$, ..., $z_N$. Let $U = \mathbb{C} \setminus \{ z_1, z_2, \ldots, z_N \}$. For $x \in U$, there are $d$-distinct roots $y$ of the above polynomial.
Let $\pi$ be projection onto the $x$-coordinate. Then the implicit function theorem shows that $\pi^{-1}(U) \to U$ is a $d$-fold covering map. We want to show $\pi^{-1}(U)$ is connected. Suppose not. Then it breaks into components $Y_1$, $Y_2$, ..., $Y_r$ which cover $U$ with degrees $k_1$, $k_2$, ..., $k_r$ where $\sum k_i = d$.
Choose a component $Y$ of $\pi^{-1}(U)$, with $Y \to U$ of degree $k$.
For $1 \leq j \leq k$ and $x \in U$, let $e_j(x)$ be the $j$-th elementary symmetric function in the $y$-coordinates of the $k$ points of $Y \cap \pi^{-1}(x)$.
The function $e_j$ is holomorphic on $U$. At the punctures $z_1$, ..., $z_N$, the function $e_j$ is bounded, since $C \to \mathbb{C}$ is proper. So, by the Riemann extension theorem, $e_j$ extends to a holomorphic function on all of $\mathbb{C}$. Also, $e_j$ is a polynomial in algebraic (multivalued) functions, so its growth rate as $|x| \to \infty$ is bounded by $|x|^N$ for some $N$. We see that $e_j(x)$ is an entire function bounded by a polynomial, so it is a polynomial. Thus, $y^k - e_1(x) y^{k-1} + \cdots \pm e_k(x)$ is a polynomial of degree $k$ vanishing on $Y$.
We can repeat this for each component $Y_i$ and get a polynomial $g_i(x,y)$ with $y$-degree $k_i$ vanishing on the corresponding points of the cover $\pi^{-1}(U) \to U$. Then $\prod g_i(x,y)$ vanishes on all of $\pi^{-1}(U)$, and hence is divisible by $f$. Since $f$ and $\prod g_i(x,y)$ have the same $y$-degree, they are proportional. This gives a nontrivial factorization of $f$, giving our contradiction.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
integration of $2x^{2}3^{x^3}$
Consider the integral
$$\int2x^23^{x^3}dx$$
So doing basic moves and U-sub yields
$$2\int x^23^{x^3}dx$$
$$u=3^{x^3}$$
$$du=3^{x^3+1}x^2\ln(3)$$
Now plugging in with u yields
$$2\int\frac{u}{\ln(3)*3^{\frac{\ln(u)+\ln(3)}{\ln(3)}}}du$$
but from here I am lost, I think this way of solving is too complex. Keep in mind I am reviewing for my Calc 2 test and this type of manipulation of an integral is very foreign to me and not something we have covered in class.
A:
Hints: Let $u=x^3$. Then your integral becomes $$\frac{2}{3}\int 3^u\,du$$
and $\int a^x\,dx=\frac{a^x}{\ln a}+C$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it easy to convert an image to a cartoon with high quality?
Is it easy to convert an image to a cartoon with high quality ? Like this:
I've watched this tutorial : but the quality of the outcome is still far away from the one above.
Is there a way to make a better one (as close as the example above) ?
A:
Tracing software may help getting started, but then there's still a lot of illustrating craft there. Photoshop and Gimp does not sound like the right tools for the trade, Illustrator and Inkscape are more like it. IIRC both should have embedded tracers.
A:
If you have Adobe Flash it has Trace tool in it's Menus (Modify -> Bitmap -> Trace Bitmap). Change it's parameters to get the best result. The good thing is despite Adobe Photoshop it will return a vector image. if you need a vector image I think it is the best way.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.Net Core project type used to share layout with multiple projects
Currently I have a Razor Class Library which generates a .net standard project. In this project I have my _Layout.cshtml and other pages that I share with other .net core projects.
While all this works I ran into an issue when I needed to have my models shared between various projects also. I extracted the models along with their migrations into a separate class library (This project is a .net core class library because of the migration files). At this point everything is still OK, but as soon as I needed to reference the entity class library from the layout project I could not do this because a .net standard project cannot reference a .net core project (for obvious reasons).
Due to these requirements I figured it would be best to make the layout project a .net core project instead of a .net standard project this way I wont have any issues referencing the projects. I don't need to access the layout project from any other projects that are not .net core so I don't need the compatibility .net standard provides.
Anyhow the issue I am currently facing is that the web application cannot see the _Layout.cshtml file to load it. I am using the exact same code that was working with my standard library. Below is the line and the error I get when trying to run the application:
var filesProvider = new ManifestEmbeddedFileProvider(GetType().Assembly, "resources");
System.InvalidOperationException: 'Could not load the embedded file manifest 'Microsoft.Extensions.FileProviders.Embedded.Manifest.xml' for assembly 'MyLayoutProject'.'
Are there any modifications required to make this work? Is this even possible? What other ideas can be thrown at me to get this working?
Update
Below is the .csproj of the shared layout project (I added GenerateEmbeddedFilesManifest and the ItemGroups at the bottom after the nuget packages)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="bootstrap" Version="4.3.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="2.2.0" />
<PackageReference Include="Microsoft.NET.Sdk.Razor" Version="2.2.0" />
<PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
</ItemGroup>
<ItemGroup>
<Content Update="Areas\Features\Pages\Shared\_Layout.cshtml">
<Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
<Content Update="Areas\Features\Pages\_ViewStart.cshtml">
<Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\**\*" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="Resources\js\jquery-3.3.1.min.js" />
</ItemGroup>
</Project>
With this update the original error message is gone, however the layouts don't load at all.
A:
I was able to accomplish this by removing all my changes and using the original .net standard class library project. What I did was edit the csproj and changed the project type to a netcoreapp2.2. It seems to be working with that minor change...
<TargetFramework>netcoreapp2.2</TargetFramework>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dining Philosophers in C memory leaks
i am trying to implement Dining Philosophers in C using Resource hierarchy solution. when i am using valgrind everything goes fine. Unfortunately when i done this using console im getting random seqfaults. One time my program will be succesful,one time it will broke on the beginning. I would be grateful if anybody could point where i did mistake and why it's 100% succesfull.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_PHILOSPHERS 5
sem_t forks[NUM_PHILOSPHERS];
void *philosopher(void *param){
printf("Thread created!");
int *id = (int *)param;
int L = 0;
sem_t* Myforks[2];
int par = *id;
if(par == 4){
Myforks[0] = &forks[4];
Myforks[1] = &forks[0];
}else{
Myforks[0] = &forks[par];
Myforks[1] = &forks[par+1];
}
while(L!=5){
printf("Eat spaghetti!",*id);
sem_wait(Myforks[0]);
sem_wait(Myforks[1]);
//.....
printf("EAT spaghetti!",*id);
sem_post(Myforks[1]);
sem_post(Myforks[0]);
L=L+1;
}
pthread_exit(NULL);
}
int main(){
int i;
pthread_t threads[NUM_PHILOSPHERS];
for(i = 0; i < NUM_PHILOSPHERS; i++)
sem_init(&forks[i], 0, 1);
for(i = 0; i < NUM_PHILOSPHERS; i++)
pthread_create(&threads[i], NULL, philosopher, (void *)&i);
return 0;
}
A:
int i;
...
for(i = 0; i < NUM_PHILOSPHERS; i++)
pthread_create(&threads[i], NULL, philosopher, (void *)&i);
^^
Passing a pointer to a local variable isn't going to work. You're passing the same address to all of the threads, so there's an inherent race condition. You point them a pointer to i and them almost immediately you increment i. What value will they read when they access *param? Who knows!
You'll want to create an array with NUM_PHILOSPHERS (sic) slots in it and pass a different address to each thread. You'll also want to make sure that array isn't destroyed when main() exits—i.e., make the array global or static, not local.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
EclipseLink (JPA 2.1) Query not returning results where it clearly should
I am trying to retrieve the next page of results from the database using the code below.
public Collection<Product> getCategoryProducts(Category selectedCategory, String start) {
Query query = em.createQuery("SELECT p FROM Product p WHERE p.categoryId = :categoryId")
.setParameter("categoryId", selectedCategory)
.setMaxResults(20);
if (null != start) {
query.setFirstResult(Integer.parseInt(start));
}
return query.getResultList();
}
My Product table has about 1000 rows where each product belongs to a category.
If I pick a category like category 1 which has 80 products. I am able to view 4 pages of products each with 20 products. Problem comes in when I try to access products belonging to a higher categoryId. I can only view the first 20 results but the next page returns 0 results.
E.g category 15 has products ranging from id=459 to id=794 where id is the primary key.
the query will return the first 20 results when I access the category page from https://localhost:8181/myapp/category?categoryId=15 but clicking the more link at the bottom https://localhost:8181/myapp/category?categoryId=15&start=478 returns 0 results. What am I missing?
see also this question is similar to this
A:
I finally found my error. Apparently the position I am setting for first result should be a product of the page number and the page size. In my case I was setting first result as the Id of the entity I am retrieving. as a result for the first few pages, the result size contained the ID but as the page numbers increased the id is not contained within the result set. This is the kind of mistakes you don't know that you don't know until you know that you don't know.
public Collection<Product> getCategoryProducts(Category selectedCategory, String page) {
int pageSize = 20;
EntityManager entityManager = Persistence.createEntityManagerFactory("techbayPU").createEntityManager();
Query query = entityManager.createQuery("SELECT p FROM Product p WHERE p.categoryId = :categoryId ORDER BY p.id", Product.class);
query.setMaxResults(pageSize);
if (null != page) {
query.setFirstResult(Integer.parseInt(page) * pageSize);
}
query.setParameter("categoryId", selectedCategory);
return query.getResultList();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make this script grep only the 1st line
for i in USER; do
find /home/$i/public_html/ -type f -iname '*.php' \
| xargs grep -A1 -l 'GLOBALS\|preg_replace\|array_diff_ukey\|gzuncompress\|gzinflate\|post_var\|sF=\|qV=\|_REQUEST'
done
Its ignoring the -A1. The end result is I just want it to show me files that contain any of matching words but only on the first line of the script. If there is a better more efficient less resource intensive way that would be great as well as this will be ran on very large shared servers.
A:
The following code is untested:
for i in USER; do
find /home/$i/public_html/ -type f -iname '*.php' | while read -r; do
head -n1 "$REPLY" | grep -q 'GLOBALS\|preg_replace\|array_diff_ukey\|gzuncompress\|gzinflate\|post_var\|sF=\|qV=\|_REQUEST' \
&& echo "$REPLY"
done
done
The idea is to loop over each find result, explicitly test the first line, and print the filename if a match was found. I don't like it though because it feels so clunky.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convergence of a series of functions in terms of a parameter
Consider the sequence of functions $\{f_{n,\alpha}\}_{n\in \mathbb{N}}$ defined by $$f_{n,\alpha}(x)=\frac{|x|^n}{x^{2n}+n^{\alpha}}$$ where $x\in \mathbb{R}$ and $\alpha>0$. I have to study the intervals of pointwise, uniform and normal convergence of $\sum\limits_{n=1}^{\infty}f_{n,\alpha}$ in terms of $\alpha$.
It's pretty easy to see by comparison with $|x|^n$ and $\frac{1}{|x|^n}$ that the series converges pointwise in $\mathbb{R}\setminus \{\pm 1\}$ for every $\alpha>0$ and since $f_{n,\alpha}(1)\sim \frac{1}{n^{\alpha}}$, the series converges pointwise in all $\mathbb{R}$ iff $\alpha>1$.
Also, studying $f'_{n,\alpha}(x) = \frac{n|x|^{n-1} (n^{\alpha}-x^{2n})}{(x^{2n}+n^{\alpha})^2}$ we get that $\sup\limits_{x\in \mathbb{R}} f_{n,\alpha}(x)=\frac{1}{2n^{\alpha/2}}$ attained at $x=n^{\frac{\alpha}{2n}}$, thus we have normal convergence in all $\mathbb{R}$ iff $\alpha>2$.
Now the problem is uniform convergence. Clearly if $\alpha>2$ the convergence is uniform in all $\mathbb{R}$, since the convergence is normal. Also, we already know that the convergence is uniform in all intervals of the form $[-a,a]$ with $0\leq a<1$ and $(-\infty,b]\cup [b,+\infty]$ with $b>1$ for every $\alpha>0$. We can extend uniform convergence to $[-1,1]$ iff $\alpha>1$, since $$\sup\limits_{x\in [-1,1]} f_{n,\alpha}(x)=f_{n,\alpha}(1)=\frac{1}{1+n^{\alpha}}$$ so by Weierstrass criterion we have uniform convergence if $\alpha>1$, and if $\alpha\leq 1$ the convergence can't be uniform in $[-1,1]$ since each $f_{n,\alpha}(x)$ is continuous but the sum $f(x)$ would go to infinity in $x=\pm 1$.
However, what about the uniform convergence in $[1,+\infty)$ when $1<\alpha\leq 2$? My problem is the right neighbourhood of $1$, since for large enough $n$ we have that $n^{\frac{\alpha}{2n}}\in [1,1+\delta]$ thus $\sup\limits_{x\in [1,1+\delta]} f_{n,\alpha}(x)=\frac{1}{2n^{\alpha/2}}$ and Weierstrass criterion for uniform convergence is inconclusive.
A:
Fix $\alpha\in(1,2]$, and the domain $[1,\infty)$.
First, you see that there is no normal convergence, as $$\lVert f_{n,\alpha}\rVert_\infty = f_{n,\alpha}(n^{\alpha/(2n)} = \frac{1}{2n^{\alpha/2}}$$ and thus $\sum_{n=1}^\infty \lVert f_{n,\alpha}\rVert_\infty$ diverges.
But normal convergence is stronger than uniform convergence, so this does not preclude uniform convergence. However, the following does:
$$
\sup_{x\geq 1} \left\lvert f(x)-\sum_{n=1}^N f_{n,\alpha}(x)\right\rvert
= \sup_{x\geq 1} \sum_{n=N+1}^\infty f_{n,\alpha}(x) \geq \sup_{x\geq 1} \sum_{n=N+1}^{2N}f_{n,\alpha}(x)\geq \sum_{n=N+1}^{2N}f_{n,\alpha}(N^{\alpha/(2N)})
$$
but
$$\begin{align}
\sum_{n=N+1}^{2N}f_{n,\alpha}(N^{\alpha/(2N)})
&= \sum_{n=N+1}^{2N}\frac{N^{\alpha/2}}{N^{\alpha}+n^\alpha}
= \frac{1}{N^{\alpha/2}}\sum_{n=N+1}^{2N}\frac{1}{1+\left(\frac{n}{N}\right)^\alpha}
\geq \frac{1}{N^{\alpha/2}}\sum_{n=N+1}^{2N}\frac{1}{1+2^\alpha}\\
&= N^{1-\alpha/2}\frac{1}{1+2^\alpha}
\end{align}$$
which does not go to $0$ as $N\to\infty$.
Note that the issue is indeed on the right-neighborhood of $1$, as
$$
n^{\frac{\alpha}{2n}} = 1+\frac{\alpha\log n}{2n} + o\left(\frac{1}{n}\right)
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adapter not creating views in programmatically created recycler view after adding item decoration
I am programmatically creating RecyclerView assigning adapter to it and adding item decoration also.. but adapter is not creating views. When I removed item decoration its building fine. There is not issue with item decoration as I used that piece of code in xml created RecyclerView without any issues.
Sample code is as below:
RecyclerView recyclerView = new RecyclerView(context);
LinearLayout.LayoutParams recyclerViewLayoutParams =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
recyclerViewLayoutParams.gravity = Gravity.START;
recyclerView.setLayoutParams(recyclerViewLayoutParams);
recyclerView.setClipToPadding(false);
ll_parent_layout.addView(recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(getParent());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);
// recyclerView.removeItemDecoration(gridSpacingItemDecoration);
// recyclerView.addItemDecoration(gridSpacingItemDecoration);
Adapter adapter = new Adapter(Activity.this, ResponseMap);
// linearSpacingItemDecoration = new LinearSpacingItemDecoration(R.dimen.margin8, adapter.getItemCount());
// recyclerView.removeItemDecoration(linearSpacingItemDecoration);
// recyclerView.addItemDecoration(linearSpacingItemDecoration);
recyclerView.setAdapter(adapter);
A:
Issue was with how item decorator class was getting initialized and reinitialzed.. I figured in after some time
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Would life expectancy increase if we replaced healthy organs with artificial ones?
Can we increase life expectancy by replacing important organs for life such as the heart, kidneys, young blood, etc. (but not the brain)? Most organs can fail and, for the ones which we already have the technology to develop artificially, would it be beneficial even if the person is otherwise healthy?
A:
No - not in a worthwhile way.
Given the current state of medicine, organ break down is not your main problem any more. Operations to replace organs with artificial ones work, although there is still a non-negligible risk to it. Even if we assume that we can replace major organs affected by cancer and ignore the spread of cancer through metastases, there are more drastic limiting effects of irreplaceable body parts.
Three parts of our body form the main problem, responsibles for ~75% of deaths in elderly people:
blood vessels: they run everywhere in the body from wide vessels as the carotis to extremely narrow capillaries in the brain. They age naturally and there is no way of replacing the smaller ones in less accessible body parts such as the brain. If they get clotted or burst, your suffer from thrombosis resulting in stroke, heart attack or other cardio-vascular symptoms.
nervous system: nerves are hard to replace, they actually die off, making elderly people lose capacities such as sensitive touch, hearing, temperature feeling and regulation etc.
brain: the main problem limiting life span or better to be said the life span lived with a certain quality of life is the brain's capacity. Altzheimer's disease, dementia, the natural deterioration of reflexes and mental constitution are all effects limiting the human life span automatically and most radically. Unless you can keep these mental effects in check, no organ replacement will make people life longer in a worhtwhile way of living.
A:
TL;DR: No, as transplanting an organ have drawbacks. Replacing a functional organ is just asking for trouble
Transplants can fail:
Everyone talks about the success rates of kidney transplants. Rarely
do we talk about what happens when transplants fail. People will quote
the official statistics that 97% of kidney transplants are working at
the end of a month; 93% are working at the end of a year; and 83% are
working at the end of 3 years
https://www.kidney.org/transplantation/transaction/TC/summer09/TCsm09_TransplantFails
Those are just some numbers about current success rate of kidney transplants. 83% of success rate is very good for those who would die without transplant. But they are just disastrous if the people were healthy.
Complications
A transplant can have a lot of complications. Just for a heart transplant, you can get:
Organ Rejection
Infections
Graft Coronary Artery Disease
High Blood Pressure/Hypertension
Diabetes
No long term support
Here is an abstract about long-term outcome following heart transplantation. It's not dramatic in current world, as people with heart problem are in the majority of cases quite old. But it's problematic for transplantation on younger folks
Money cost
Another problem is the cost of a transplantation. A surgery operation cost a lot. An artificial organ even more. Replacing every organ of every human would be just way beyond budget accorded to health organization. And this money could be spent way better on other fields. Organ failure is just one way to die. They are plenty others way to die, either environmental (accidents for example), or other diseases (cancer, ischemic stroke, diabetes...)
A:
That depends on your definition of "life"... But the answer is probably no.
If you replace the heart of a healthy human with an artificial one, that human won't die from a heart failure. But he can still die from cancer, stroke or a broken neck because he fell down the stairs. That means the overall number of deaths due to physical cause will be smaller, but not zero.
The human body is already able to stay relatively healthy into old age if it's maintained and moderately trained. The same applies to our brains. As long as people have something to do in their life, most stay clear minded into old age. But if they lose that purpose or task, the brain power decreases just as much as an unused muscle.
By replacing vital organs you can keep the body alive and minimize the numbers of deaths due to organ failure and unhealthy lifestyle. But those people might be no more than human vegetable if they don't have any reason to keep their brains active and trained to manage the basics of life.
The more sophisticated a society is, the more likely it is that people lose their mental prowess. Our great-grandfathers (and mothers) had to learn many things about agriculture, observe nature and contribute to the family even in old age. Their bodies degenerated faster than their brains.
In our current society, we learn a lot of stuff in school (most of which we never use in life), but we have computers, smart phones, calculators and navigation systems to do the hard thinking for us. After retirement many people lose any purpose in their life and their brains degenerate rapidly due to the lack of mental training. (This effect is called Digital Dementia)
If this trend continues in the future, the degeneration of brains might set in even earlier in life and be more devastating, because all the gadgets that make life so comfortable mean people never need to train their brains.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular Material matToolTip does not display when using ngFor function
I have a set of data called reports which contain an array of networks (report.networks). I have model.ts to manipulate the networks array before i return it back. I do an ngFor to iterate over the network data to display the details which works fine. However, adding a matToolTips within the ngFor does not get displayed.
component.html
<span matTooltip="Tooltip Works">Tooltip Works</span>
<div *ngFor="let network of report.networks">
<span matTooltip="Tooltip Does NOT work!">Tooltip Does NOT work</span>
</div>
component.ts
import { Report } from './../../core/models/report/report.model';
@Component({
selector: 'app-report-detail',
templateUrl: './report-detail.component.html',
styleUrls: ['./report-detail.component.scss']
})
export class ReportDetailComponent implements OnInit {
report: Report;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.report = this.route.snapshot.data.report;
console.log(this.report);
}
}
report.model.ts
export class Report {
networks?: any = null;
constructor(data?: Report) {
if (data) {
this.deserialize(data);
}
}
private deserialize(data: Report) {
const keys = Object.keys(this);
for (const key of keys) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
}
get networks() {
let n = this.networks;
//some manipulation
return n
}
}
A:
As mentioned here https://github.com/angular/material2/issues/10039
The array is instance being created over and over again when using a function in a ngFor which causes multiple issues like matToolTip not displaying as-well as performance issues.
Another way i got around this is to change my model.ts file. So below im assigning a variable to the result of the function. Then i use this variable inside the ngFor isntead of the function directly.
export class Report {
networks?: any = null;
//custom
customNetworks? : any = null;
constructor(data?: Report) {
if (data) {
this.deserialize(data);
this.customNetworks = this.generateNetworks()
}
}
private deserialize(data: Report) {
const keys = Object.keys(this);
for (const key of keys) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
}
generateNetworks() {
let n = this.networks;
//some manipulation
return n
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How get an apostrophe in a string in javascript
I'm doing some stuff with javascript and I'm wondering, how do I put an apostrophe in a string in javascript?
theAnchorText = 'I apostrophe M home';
A:
You can use double quotes instead of single quotes:
theAnchorText = "I'm home";
Alternatively, escape the apostrophe:
theAnchorText = 'I\'m home';
The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.
There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.
A:
You can try the following:
theAnchorText = "I'm home";
OR
theAnchorText = 'I\'m home';
A:
This is plain Javascript and has nothing to do with the jQuery library.
You simply escape the apostrophe with a backslash:
theAnchorText = 'I\'m home';
Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:
theAnchorText = "I'm home";
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In Javascript why do Date objects have both valueOf and getTime methods if they do the same?
MDN says that valueOf and getTime are functionally equivalent. Why have two functions that do the very same thing?
A:
The Date.prototype.getTime method returns the number of milliseconds since the epoch (1970-01-01T00:00:00Z); it is unique to the Date type and an important method.
The Object.prototype.valueOf method is used to get the "primitive value" of any object and is used by the language internally when it needs to convert an object to a primitive. For the Date class, it is convenient to use the "time" attribute (the value returned by getTime()) as its primitive form since it is a common representation for dates. Moreover, it lets you use arithmetic operators on date objects so you can compare them simply by using comparison operators (<, <=, >, etc).
var d = new Date();
d.getTime(); // => 1331759119227
d.valueOf(); // => 1331759119227
+d; // => 1331759119227 (implicitly calls "valueOf")
var d2 = new Date();
(d < d2); // => true (d came before d2)
Note that you could implement the "valueOf" method for your own types to do interesting things:
function Person(name, age) {this.name=name; this.age=age;}
Person.prototype.valueOf = function() {return this.age; }
var youngster = new Person('Jimmy', 12);
var oldtimer = new Person('Hank', 73);
(youngster < oldtimer); // => true
youngster + oldtimer; // => 85
A:
There are no difference in behaviour between those two functions:
https://code.google.com/p/v8/codesearch#v8/trunk/src/date.js&q=ValueOf&sq=package:v8&l=361
// ECMA 262 - 15.9.5.8
function DateValueOf() {
return UTC_DATE_VALUE(this);
}
// ECMA 262 - 15.9.5.9
function DateGetTime() {
return UTC_DATE_VALUE(this);
}
But there are historical differences.
A:
valueOf is a method of all objects. Objects are free to override this to be what they want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I compile mysql-connector-c for macOS 10.13.x using C?
Synopsis
I have a small c program, it's a standard "hello world" application to test I can access the mysql connection driver accordingly:
#include <stdio.h>
#include "mysql.h"
int main(int argc, const char **argv)
{
printf("MySQL client version: %s\n", mysql_get_client_info());
return 0;
}
When I compile this using the following; I get an error:
gcc src/main.c \
-Wall \
-Ilib/mysql-connector-c-6.1.11-macos10.12-x86_64/include \
-o bin/test
Undefined symbols for architecture x86_64:
"_mysql_get_client_info", referenced from:
_main in main-59d4fb.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I have then attempted to link mysql with the following:
gcc src/main.c \
-Wall \
-Ilib/mysql-connector-c-6.1.11-macos10.12-x86_64/include \
-Llib/mysql-connector-c-6.1.11-macos10.12-x86_64/mysql-connector-c-6.1.11-src/libmysql \
-lmysql \
-o bin/test
ld: library not found for -lmysql
clang: error: linker command failed with exit code 1 (use -v to see invocation)
It's worth noting I am using c not c++ and I am not using XCode just Vim and gcc as can be seen above.
Alternative attempt
I then decided perhaps i've done something wrong with compiling the source from MySQL This particular link and so I deleted the lib directory within my application and installed them via homebrew:
I tried brew install mysql-connector-c I also received the same errors as above despite changing the -I -L -l accordingly the new paths /usr/local/Cellar/... and exactly the same problems were occurring.
Conclusion
I could not find any .c files in any of the compiled mysql libraries, I did find a libmysql inside the source i compiled and attempted to link that which also failed. I personally feel it's a linking problem I just don't know what or how, if anyone could help me with this I would really appreciate it.
Anyone who may want to see the response of -v please see below:
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.3.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.13.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name main.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -fno-strict-return -masm-verbose -munwind-tables -target-cpu penryn -target-linker-version 305 -v -dwarf-column-info -debugger-tuning=lldb -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/9.0.0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -I lib/mysql-connector-c-6.1.11-macos10.12-x86_64/include -I/usr/local/include -Wall -fdebug-compilation-dir /Users/ash/Projects/samp-db2 -ferror-limit 19 -fmessage-length 173 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.13.0 -fencode-extended-block-signature -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/v7/_rm0d0qx2r32ln2f7_dpnrw40000gn/T/main-3d5e25.o -x c src/main.c
clang -cc1 version 9.0.0 (clang-900.0.39.2) default target x86_64-apple-darwin17.3.0
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/local/include"
ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/Library/Frameworks"
#include "..." search starts here:
#include <...> search starts here:
lib/mysql-connector-c-6.1.11-macos10.12-x86_64/include
/usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/9.0.0/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks (framework directory)
End of search list.
"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -lto_library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libLTO.dylib -no_deduplicate -dynamic -arch x86_64 -macosx_version_min 10.13.0 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk -o bin/cmig /var/folders/v7/_rm0d0qx2r32ln2f7_dpnrw40000gn/T/main-3d5e25.o -L/usr/local/lib -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/9.0.0/lib/darwin/libclang_rt.osx.a
A:
> brew install mysql-connector-c
> clang mysql_connect_test.c -l mysqlclient -o mysql_test
> ./mysql_test
MySQL client version: 6.1.11
same code in mysql_connect_test.c, everything is ok.
> ls /usr/local/Cellar/mysql-connector-c/6.1.11/lib
libmysqlclient.18.dylib libmysqlclient.a libmysqlclient.dylib
Your code just need link to libmysqlclient.
And in your post:
gcc src/main.c \
-Wall \
-Ilib/mysql-connector-c-6.1.11-macos10.12-x86_64/include \
-o bin/test
It is wrong, because you just pass library search path to gcc, but also need pass which library you should link, for example, -lmysqlclient.
gcc src/main.c \
-Wall \
-Ilib/mysql-connector-c-6.1.11-macos10.12-x86_64/include \
-Llib/mysql-connector-c-6.1.11-macos10.12-x86_64/mysql-connector-c-6.1.11-src/libmysql \
-lmysql \
-o bin/test
wrong name of link library, and mysql-connector-c-6.1.11-macos10.12-x86_64 just contains source code? If yes, you need compile mysql-connector-c first.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
same value is assigned to all elements that have different id
I am building and application that has a customized shopping cart.
I am using fancybox (ajax) to get color-codes for five different sofa types (Furniture). After fancybox loads contents (colors) from database I am able to choose and select color for each sofa type. I have associated a code to each color which I am getting in a variable (colorCode). I am able to get the color’s code from the html page, code is
$('body').on('click', '.margin', function() {
// Get the code of selected Color
colorCode= $(this).children('.color-code').text();
//Write the selected color-code in the div-element on frontend so that user can see the selected color code.
$('#'+selectedIdCode).empty().text(colorCode);
});
Now if i click on the select option, it will display fancybox with colors, i can select colors by clicking on them and the selected color is displayed in the color’s div-element to user
But this works fine for first time only and if i select color for the second product it behaves accordingly but in the end it will update the color-code of the previous Sofa to the new one.
Suppose I selected the color of a Single-Seater sofa it writes in the color-code div-element (6). But when I select the color-code for second sofa, Two-Seater sofa. It overwrites the color-code div element of the Single-Seater sofa as well to (20).
See the 1 Seater sofa's code has been changed from (6) to (20). Similarly now if i select color for 3 Seater sofa, It will overwrite the color codes of 2-Seater as well as 1-Seater sofa.
Problem is when ever a new color is selected for a product the previous color-codes of other products are also over-written by the latest color-code.
I think issue lies here
$('body').on('click', '.margin', function() {
SAMPLE HTML CODE
<td>
<div class="btn-group select-color-minwidth">
<div class="btn" id="1seater-code">Select Color</div>
<a class="code-selector fancybox.ajax btn" id="1seater">
<i class="fa fa-pencil"></i>
</a>
</div>
</td>
<td>
<div class="btn-group select-color-minwidth">
<div class="btn" id="2seater-code">Select Color</div>
<a class="code-selector fancybox.ajax btn" id="2seater">
<i class="fa fa-pencil"></i>
</a>
</div>
</td>
<td>
<div class="btn-group select-color-minwidth">
<div class="btn" id="3seater-code">Select Color</div>
<a class="code-selector fancybox.ajax btn" id="3seater">
<i class="fa fa-pencil"></i>
</a>
</div>
</td>
jQUERY CODE
$(document).ready(function() {
$('.code-selector').click(function(){
var colorCode;
//Which category is clicked 1 Seater or 2 Seater or 3 Seater etc
var selectedId = $(this).attr('id');
//The id of the Div-Element where the value for selected code will be displayed
var selectedIdCode = selectedId+'-code';
$(".code-selector").fancybox({
padding:10,
margin:100,
openEffect : 'elastic',
openSpeed : 150,
closeEffect : 'elastic',
closeSpeed : 500,
closeClick : false,
href : 'fancyboxajax.php',
helpers : {
overlay : null
}
});
$('body').on('click', '.margin', function() {
// Get the code of selected Color
colorCode= $(this).children('.color-code').text();
//Update the selected Color code
$('#'+selectedIdCode).empty().text(colorCode);
});
});
});
And Finally the FANCYBOXAJAX.PHP
<script type="text/javascript">
$('.margin').click(function(){
//Remove selection from other and apply to the Current one
$('.selected').css('display','none');
$(this).children('.selected').css('display','block');
// Show the save button
$('.save-button').css('display','block');
// take user to Save button
$(".fancybox-inner").animate(
{ scrollTop: 0 },
{
duration: 100,
easing: 'linear'
});
// Close the Fancy box
$('#close-njk').click(function() {
$.fancybox.close();
});
});
</script>
<div class="tiles">
<p>Select any color and click on save Button, Below</p>
<div class="save-button">
<button class=" col-3 btn btn-primary " id="close-njk">Save</button>
</div>
<?php
$db->set_table('raw_material');
$results = $db->all();
foreach ($result as $result) {
echo '<div class="margin">
<div class="selected"><img src="check_success-64.png"></div>
<img class="njk-img" src="gallery/raw_material_tiles_2/'.$result['material_name'].'.jpg" width="100" height="75">
<div style="display:none" class="color-code">'.$result['id'].'</div>
</div>';
}
?>
</div>
Any assistance in this regard is appreciated.
Thanks
A:
Luckily i found its solution
My main problem was that i was trying to get the color-code from the front end or my Html page.
But
I when i tried to access the id from the fancyboxajax.php page it changed/updated only the specific id rather than all the ids.
So i passed the id as a variable to fancybox and from the page which was loading in the fancybox i assigned the color-codes to the specific id.
here is code illustration
$(document).ready(function() {
$('.code-selector').click(function(){
var colorCode;
//Which category is clicked 1 Seater or 2 Seater or 3 Seater etc
var selectedId = $(this).attr('id');
//The id of the Div-Element where the value for selected code will be displayed
var selectedIdCode = selectedId+'-code';
//Get the respective selected option id
var selectedOption = '#'+selectedId+'-option';
//Get the respective selected option id value
var selectedOptionValue = $(selectedOption).find(":selected").attr('value');
$(".code-selector").fancybox({
padding:10,
margin:100,
openEffect : 'elastic',
openSpeed : 150,
closeEffect : 'elastic',
closeSpeed : 500,
closeClick : false,
href : 'fancyboxajax.php?code='+selectedIdCode+'&option='+selectedOptionValue,
helpers : {
overlay : null
}
});
});
});
and the fancyboxajax.php page respectively
var code ="<?php echo $_GET['code']; ?>";
var option = "<?php echo $_GET['option']; ?>";
// Close the Fancy box
$('#close-njk').click(function() {
$.fancybox.close();
$('#'+code).text(color);
$('#'+code+'-color').val(color);
});
Thank you to all those who spent time on my question and gave valuable suggestions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HttpResponseMessage.Content.Headers ContentDisposition is null
When downloading a file with HttpClient, I'm downloading first the headers and then the content. When headers are downloaded, I can see Headers collection on the Content property of HttpResponseMessage, but when accessing it through ContentDisposition on Headers, get null
Why this is happening? Fiddler shows headers are fine...
Code:
var responseMessage = await httpClient.GetAsync(uri,
HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(continueOnCapturedContext: false);
Update 1
It looks like this class is following Content-Disposition implementation outlined in RFC 2616 and fails to handle Content-Disposition implementation update RFC 6266. RFC 2616 defines filename parameter value to be a quoted-string, where update RFC 6266 just states it should be value.
RFC 2616 Grammar
content-disposition = "Content-Disposition" ":"
disposition-type *( ";" disposition-parm )
disposition-type = "attachment" | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = "filename" "=" quoted-string
disp-extension-token = token
disp-extension-parm = token "=" ( token | quoted-string )
RFC 6266 Grammar
content-disposition = "Content-Disposition" ":"
disposition-type *( ";" disposition-parm )
disposition-type = "inline" | "attachment" | disp-ext-type
; case-insensitive
disp-ext-type = token
disposition-parm = filename-parm | disp-ext-parm
filename-parm = "filename" "=" value
| "filename*" "=" ext-value
disp-ext-parm = token "=" value
| ext-token "=" ext-value
ext-token = <the characters in token, followed by "*">
where ext-value = <ext-value, defined in [RFC5987], Section 3.2>
Examples
Working case
Failing case
Update 2
Opened a ticket with MS connect.
Update 3
Microsoft has acknowledged that this is a bug and will fix it.
A:
Thank you - finding this definitely helped me. For the benefit of others, here is my workaround (as apparently this is still a thing today???)
I am in a somewhat controlled environment, so the following code assumes:
Only one Content-Disposition Header
The tag is in the format: inline; "filename";
This will reset the response's ContentDisposition header, so subsequent code works seamlessly:
<!-- language: c# -->
if (response.Content.Headers.ContentDisposition == null)
{
IEnumerable<string> contentDisposition;
if (response.Content.Headers.TryGetValues("Content-Disposition", out contentDisposition))
{
response.Content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(contentDisposition.ToArray()[0].TrimEnd(';').Replace("\"",""));
}
}
A:
The problem is with the trailing ; in the content-disposition header
[Fact]
public void ParseContentDispositionHeader()
{
var value = ContentDispositionHeaderValue.Parse("attachment; filename=GeoIP2-City_20140107.tar.gz");
Assert.Equal("GeoIP2-City_20140107.tar.gz",value.FileName);
}
If I add the semi-colon the parsing will fail. If you look at the RFC6266 grammar, the semi-colon is only supposed to precede the parameter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compression class error - Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
I've created this simple compression class for a client server TCP data connection and it all looks fine to me with no build errors however I am getting a run time error that I cannot correct. The error I am getting is Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1.
Code:
import java.io.Serializable;
import java.util.ArrayList;
public class CompressedMessage implements Serializable
{ // this instance variable will store the original, compressed and decompressed message
private String message;
public CompressedMessage(String message)
{
// begin by coding this method first - initialise instance variable message with the original message
this.message = message;
}
public String getMessage()
{
return this.message;
}
private boolean punctuationChar(String str)
{
// Hint: check if the last character in the string is a punctuation
int length = str.length();
str = str.substring(length -2,length-1);
if(str.equals(",") || str.equals("!") || str.equals(".") || str.equals("?"))
{
return true;
}
else
{
return false;
}
}
private String getWord(String str)
{ // Hint: if last character in string is punctuation then remove
if(punctuationChar(str)== true)
{
//remove punctuation of last char
str = str.substring(0,str.length()-1);
}
return str;
}
public void compress()
{ /* read through section 3 of the practical 5 document
to get you started. This is called by the server,
have a look at the server code where it is called */
ArrayList<String> newMessage = new ArrayList<String>();
String[] words = message.split(" ");
for (String word : words)
{
getWord(word);
//if word has already appeared replace with position of previous word
if(newMessage.contains(word))
{
String str = Integer.toString(newMessage.indexOf(word));
str = str + " ";
newMessage.add(str);
}
else
{
word = word + "";
newMessage.add(word);
}
//if word had a punctuation at the end add it back in
//System.out.println(word);
}
this.message = newMessage.toString();
System.out.println("****************COMPRESSING*****************");
System.out.println(newMessage);
}
public void decompress()
{ /* read through section 3 of the practical 5 document
to get you started. This is called by the client,
have a look at the client code where it is called */
ArrayList<String> decompMessage = new ArrayList<String>();
String[] words = message.split(" ");
for (String word : words)
{
getWord(word);
if(word.substring(0,1).matches("[0-9]"))
{
int num = Integer.parseInt(word);
decompMessage.add(decompMessage.get(num));
}
else
{
decompMessage.add(word);
}
}
this.message = decompMessage.toString();
System.out.println("****************DECOMPRESSING*****************");
System.out.println(decompMessage);
}
}
Error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1952)
at CompressedMessage.punctuationChar(CompressedMessage.java:24)
at CompressedMessage.getWord(CompressedMessage.java:40)
at CompressedMessage.compress(CompressedMessage.java:61)
at P5_Server.waitForData(P5_Server.java:72)
at P5_Server.main(P5_Server.java:159)
I have tried changing the way a calculated the strings based on the length() but it didn't reduce the errors.
Can anyone see what I'm doing wrong?
A:
What if you str is length 0 (empty string ) or length 1? In that case str = str.substring(length -2,length-1); will result into exception.
You need to put a length check before performing the substring:
if(length > 1){
str = str.substring(length-2,length-1);
}
Since you are trying to get only one character, I think you can simply do as:
if(length > 1){
str = String.valueOf(str.charAt(length-2))
}
Please make sure that str is not null otherwise put a null handling as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Entity Framework Combining Strings
What would be the best method to concatenate leadTag + content + EndTag into a string for entry into the database?
Here is my data model
namespace stories.Models
{
public class StoryModels
{
[Key]
public int id { get; set; }
public DateTime? date { get; set; }
[Required]
public string title { get; set; }
[Required]
public string leadTag { get; set; }
public string product { get; set; }
public string user { get; set; }
[Required]
public string content { get; set; }
public string EndTag { get; set; }
}
}
A:
One way to do it would be to create another property in your model to combine the data. You could then use that property when writing to the database:
public string CombinedProperty
{
get
{
return String.Format("{0}\n{1}\n{2}", leadTag, content, EndTag);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Замена битов в байтах (двойная плотность пикселей)
Имеется массив байт (Конвертированый BMP) в котором нужно проверять биты
если бит=1 то следующий тоже=1 если бит=0 то следующий=0
как реализовать такой цикл ?
A:
Судя по вашим предыдущим вопросам, вы работаете с массивом байтов, полученным из изображений типа System.Drawing.Image, System.Drawing.Bitmap.
Как вариант, можно обойтись возможностями самой GDI+.
Допустим, имеется картинка с исходным изображением:
Bitmap source = new Bitmap("source.bmp");
Следующая строка кода создаст новую картинку, увеличенную вдвое (растянутую) по горизонтали. Вроде, именно это вам и нужно.
Bitmap target = new Bitmap(source, source.Width * 2, source.Height);
Всё! Можно её использовать. Например, сохранить:
target.Save("target.bmp", ImageFormat.Bmp); // выберите желаемый формат
Код на C#. Думаю, перевести на C++/CLI не составит труда.
Другой вариант, отрисовка через Graphics. У этого класса есть множество свойств, можно поиграться с их настройкой для получения нужного качества.
Bitmap target = new Bitmap(source.Width * 2, source.Height); // создаем пустое изображение
var graphics = Graphics.FromImage(target);
//graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
//graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(source, new Rectangle(0, 0, target.Width, target.Height));
И напоследок, кардинальный способ. Использовать метод LockBits.
В примере кода по ссылке показано, как скопировать изображение в массив байтов и работать с ним в цикле. Это будет быстрее, чем копирование через MemoryStream. К тому же, в массиве будет именно сырая пиксельная карта, без шапки и т. п.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to collect errors after call `valid?` method on object?
class Oauth
RESPONSE_TYPE = 'response_type'
CLIENT_ID = 'client_id'
REDIRECT_URI = 'redirect_uri'
AUTHORIZATION_TOKEN = 'authorization_token'
REQUIRED_PARAMS = [RESPONSE_TYPE, CLIENT_ID, REDIRECT_URI]
VALID_PARAMS = REQUIRED_PARAMS
attr_reader :errors
def initialize(params)
@params = params
@errors = []
end
def valid?
REQUIRED_PARAMS.all?{ |param| valid_params.has_key?(param) }
end
# private
def valid_params
@params.slice(*VALID_PARAMS)
end
end
I would like to collect missing #{param} key errors after calling valid? method.
A:
You can try to make your OAuth Object an ActiveModel it behaves like an ActiveRecord Model but is not backed via DB. ActiveModel allows you to use validations as you would in an AR model, so fetching the validation errors would be likewise.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Combine filtering (e.g. with grep) with plot function?
Just getting started with R and I have not been able to find any examples to answer my question!
I have put together a data set that looks like:
Sample.Name Component.name TCAmount Ratio
1A-S0 Alprazolam 0.0 0.05
1A-S1 Alprazolam 1.5 0.07
1A-S2 Alprazolam 3.1 0.08
1A-S3 Alprazolam 6.25 0.10
2A-S0 Alprazolam 0.0 0.06
2A-S1 Alprazolam 1.5 0.08
2A-S2 Alprazolam 3.1 0.09
2A-S3 Alprazolam 6.25 0.10
1B-S0 Alprazolam 0.0 0.05
1B-S1 Alprazolam 1.5 0.08
1B-S2 Alprazolam 3.1 0.10
1B-S3 Alprazolam 6.25 0.11`
I'm now looking for a way to select all the rows containing "1A" in the Sample.Name column (so that would include 1A-S0, 1A-S1, 1A-S2, 1A-S3) and then have R plot the Ratio versus TCAmount of only the rows containing this string. Eg. I have come across grep which is able to select rows which contain the term "1A":
> df1<-grep(("1A"), alprazolam.df$Sample.Name, value=TRUE)
> df1
I get back:
[1] "1A-S0" "1A-S1" "1A-S2" "1A-S3"
My question is: how do I command R to now plot the Ratio and TCAmount for only these columns grep picks out? I would prefer not to create a subset of this data to then have to create specific commands pointing to as well since this is already a subset of a larger dataset. If I were to start creating more subsets I will end up with 50 of these data sets times the number of subsets this gets broken into... AH!
If possible, I would ultimately like to be able to create a loop where R knows to use the Sample.Name levels (in this case 1A, 2A, 1B) to create three plots automatically showing the Ratio versus TCAmounts.
Thanks for any help you can offer!
A:
This is a solution that uses the package ggplot2 for plotting. It will also create a plot for each of Sample.Name levels in your data (where I assumed the Sample.Name level to be the first two characters in Sample.Name). ggplot2 can use a column in your data frame to automatically split the data in group and create several plots.
I first add a column Sample.Name.Level to the data frame as follows:
alprazolam.df$Sample.Name.Level <- substr(alprazolam.df$Sample.Name, 1, 2)
Then the plot is created by
library(ggplot2)
ggplot(alprazolam.df, aes(x = TCAmount, Ratio)) +
facet_wrap(~ Sample.Name.Level) + geom_line()
which gives
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery not loading?
Feel free to yell abuse at me if I'm being stupid here, but I'm getting confused. It seems like everything should work fine :/ I've triple checked the file locations and everything is fine
I have this in the head:
<head>
<meta charset="utf-8">
<title>Website</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
</head>
I have a list of links like this:
<ul class="menu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
And in functions.js I have this...
console.log('WTF.. THIS LOGS IN THE CONSOLE!?!?!?!');
// debugging purposes
alert($('a').attr('href'));
$('.menu li a').click(function(e){
alert('hey');
e.preventDefault();
});
I get an alert saying 'undefined' and when I click on a link, default actions is prevented and I don't get an alert...
The conclusion I've come to is there was a problem somewhere with the jQuery... but I just can't find whats going on here
A:
You probably have to wrap your code within a document.ready handler:
$(document).ready(function() {
console.log('WTF.. THIS LOGS IN THE CONSOLE!?!?!?!');
// debugging purposes
alert($('a').attr('href'));
$('.menu li a').click(function(e){
alert('hey');
e.preventDefault();
});
});
Keep in mind Javascript is executed as soon as it appears in a page, your <a> elements do not exist yet when your script executes. Using the "ready" event, you ensure your DOM is fully available when your code runs.
You could also add the reference to your functions.js file at the end of the body, before </body> tag.
A:
$(function(){
//....Your code of java script must be
});
try this,it will run..
A:
You tried wrapping it all in a $(document).ready() to ensure the dom has loaded?
$(document).ready(function() {
console.log('WTF.. THIS LOGS IN THE CONSOLE!?!?!?!');
// debugging purposes
alert($('a').attr('href'));
$('.menu li a').click(function(e){
alert('hey');
e.preventDefault();
});
});
That should work for you. (Shortcut for $(document).ready(function() {}); is $(function() {});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Conversion System::Uint^ to unsigned long
I have a function which takes pointer value as argument in my C Static Library.
Now I am writing C/CLI wrapper on it which in turn will be used in C# code.
long function_C( PULONG pulsize, PULONG pulcount );
Wrapper Function C++/CLI
long function_Managed( System::Uint^ size, System::Uint^ pulcount );
I am calling function_C function from function_Managed.Now I facing problem to convert System::Uint^ PULONG.
My Query is
1. is this correct do this.
2. If this is correct than how to convert System::Uint^ to PULONG
A:
long function_C(PULONG pulsize, PULONG pulcount);
int function_Managed(unsigned% size, unsigned% count)
{
unsigned long lsize = size, lcount = count;
long const ret = function_C(&lsize, &lcount);
size = lsize, count = lcount;
return ret;
}
To C# code, function_Managed will have this signature:
int function_Managed(ref uint size, ref uint count)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I change template engine in Play Framework?
How would I change the template engine in Play! to a different engine than the default one? Can you give an example?
A:
I don't even ask why you want to do that.
That's simple, Play can return Result with ANY content you will give it, so you can just easily use:
return ok("<h1>Code rendered from your alternative engine</h1>").as("text/html");
A:
It depends on which template engine you want to use. There are a number of options in Play's Module Directory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Class global variables in Objective-C
I'm trying to create variables that can be accessed from any class coming from a Java background I'm struggling to understand this in Objective-C..
in Java we have:
public static int MAIN_MENU = 1, SELECTION_SCREEN = 2;
These can be accessed anywhere like so:
ClassName.MAIN_MENU;
How would do achieve the same thing in its simplest form for Objective-C keeping it within a class?
A:
In Objective-C, classes have no static members. The best I can imagine is creating a getter and setter class method with an utterly ugly global variable:
static T _member = initialValue;
+ (T)someStaticMember
{
return _member;
}
+ (void)setSomeStaticMember:(T)newVal
{
_member = newVal;
}
If you only need a getter, i. e. emulation of a read-only member, then move the static variable inside the function, at least you will have one less global that way.
BUT: if you only need integer constants, why not use an enum? Or at least some macros?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Plot a generic function in Python
I have the following mathematical function in Python:
y = max(0, |x| - epsilon)
To plot it I have done the usual
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-100,100,400)
y = np.maximum(0, np.absolute(x) - 10)
plt.plot(x,y)
plt.show()
but I want to plot it without assigning any value to epsilon as shown in the picture
A:
If you know the value of epsilon, then you can do it using plt.xticks:
epsilon = 10
x = np.linspace(-100, 100, 10000)
y = np.maximum(0, np.absolute(x) - epsilon)
plt.figure()
plt.plot(x, y)
plt.xticks([-epsilon, epsilon], ["$-\\varepsilon$", "$\\varepsilon$"])
plt.plot()
If you don't, then you can just determine its value using y:
epsilon = x[y == 0][-1]
And then applying the code above.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is there no gem that uses the full shipping api for UPS?
Right now I have a project I'm working on and they want to use UPS as a carrier for shipping, but all the gems that have anything to do with shipping only track and get rates, none of them use the shipping api to actually create shipments. If anyone has found anything that does this I'd like to know.
Thanks in advance for everyone's time.
A:
did you have a look at the shopify active_shipping gem?
https://github.com/Shopify/active_shipping
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Probability of Random number repeating
In the situation of having a high entropy random number generator, that generates numbers in the range of 0 and 2,147,000,000.
If i have a list of 1,000,000 integer values, what are the chances that a random number will already be on my list?
A:
One minus the probability that they are all different:
$$1 - \left( 1- \frac{1}{n} \right)
\left( 1- \frac{2}{n} \right)
\cdots \left( 1- \frac{k-1}{n} \right),$$
where $n=2,147,000,001$ (since you include $0$) and $k=1,000,000.$
See the birthday problem for more information.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why there are two keys for Azure DocumentDB (primary and secondary)?
The subject says it all...
Why there are two keys for Azure DocumentDB (primary and secondary)?
A:
This is so that you can expire a key without having any system downtime. Say you want to replace your primary key. The procedure is
Configure your service to use the secondary key - if you use the service config you can do this without downtime.
Regenerate the primary key
(Optional) reconfigure your service to use the new primary key
If there was only one key at a time, your service would be down while you did the key replacement.
Good practise is to replace your keys on a regular basis (e.g every 6 months or whatever is appropriate based on the sensitivity of your data). You should also replace keys when anyone who has access to the keys leaves your business or team. Finally, you should obviously replace them if you think they have been compromised in some way. E.g. accidentally written to a log or posted to a public GitHub repo - it happens...
https://securosis.com/blog/my-500-cloud-security-screwup
Both the primary and secondary keys can be regenerated in the Azure portal (note: at the time of writing this is the preview portal). Select your DocumentDB then the Keys pane. There are two buttons at the top of the pane:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Symfony 4 kernel controller event listener - implement interface
I want to make some operations before controller load and I have problem with include interfaces or classes into function.
My question is how should I do it to start working?
There is a code:
~/src/Controller/ControllerListener.php
<?php
namespace App\EventListener;
use App\Controller\DailyWinController;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class ControllerListener implements DailyWinController
{
public function onKernelController(FilterControllerEvent $event, LoggerInterface $logger) {
$logger->alert('Working');
}
}
~/src/Controller/DailyWinController.php
<?php
namespace App\Controller;
interface DailyWinController {
// maybe there something?
}
~/src/Controller/UserController.php
<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\DailyWin;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class UserController extends Controller implements DailyWinController
{
/**
* @Route("/user", name="user")
* @param AuthorizationCheckerInterface $authChecker
* @param UserInterface $user
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function user(AuthorizationCheckerInterface $authChecker, UserInterface $user = null, LoggerInterface $logger) {
if ($authChecker->isGranted('ROLE_USER') === false) {
return $this->redirectToRoute('logowanie');
}
$logger->warning('Logger is working');
$em = $this->getDoctrine()->getManager();
$DWrep = $em->getRepository(DailyWin::class);
$userId = $user->getId();
$dailyWin = $DWrep->findOneBy(['userId' => $userId]);
return $this->render('andprize/user/index.html.twig', array(
'dailyWin' => $dailyWin,
'userId' => $userId
));
}
}
I have the following problem:
FatalThrowableError Type error: Argument 2 passed to
App\EventListener\ControllerListener::onKernelController() must
implement interface Psr\Log\LoggerInterface, string given
A:
You have to inject the logger to the listener.
<?php
namespace App\EventListener;
use App\Controller\DailyWinController;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class ControllerListener implements DailyWinController
{
protected $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger=$logger;
}
public function onKernelController(FilterControllerEvent $event) {
$this->logger->alert('Working');
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Job offer has been given unofficially, but delay in official contract
This may not be something big but I am kind of stressed out because I don't know what to expect. After 4 interviews, the HR told me that I got the job and also sent me an e-mail describing the job proposal. That was last Thursday. He told me that he would contact me again to discuss the starting date, but until now I haven't received a call.
My question is: Is it proper to send an e-mail inquiring about the starting date or should I just sit and wait. Or does waiting show that I am not interested enough?
A:
My question is: Is it proper to send an e-mail inquiring about the
starting date or should I just sit and wait. Or does waiting show that
I am not interested enough?
There's nothing improper about either action.
Certainly you are anxious, but if it's been less than a week since your last contact, it's most likely nothing to worry about. Often, HR needs to coordinate things on their end. Sometimes that requires a lot of paperwork and discussions with the hiring manager, etc. These things can take some time.
If you want to send a quick email indicating that you haven't heard from them, and asking if there's any more information they need from you, there will most likely be no harm in that.
On the other hand, waiting at least a week wouldn't be harmful either.
Try to relax a bit. If you still haven't heard by Thursday, shoot them a note.
One time I had to wait 3 weeks (due to vacations and a lot of other hiring going on) before I got my formal offer after having informally being offered the job. It came through, we negotiated a bit more on the final details, I was hired, and it worked out fine.
One more note - don't give your notice at your current job until you get the real formal offer. It's unusual, but things could happen which derail the process.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rotate Video- Could not write header for output file #0 (incorrect codec parameters ?)
I am using below command to rotate video-
{"-y", "-ss", "" + startMs / 1000, "-t", "" + (endMs - startMs) / 1000, "-i", inputPath, "-vf", "transpose=" + type,"-c:a", "copy", outputPath}
I am getting below failure message in Android Oreo-
"ffmpeg version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers\n
built with gcc 4.8 (GCC)\n configuration: --target-os=linux
--cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi-
--arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot
--enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include
-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib
-Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=\n libavutil 55. 17.103 / 55. 17.103\n libavcodec 57. 24.102 / 57. 24.102\n libavformat 57. 25.100 /
57. 25.100\n libavdevice 57. 0.101 / 57. 0.101\n libavfilter 6. 31.100 / 6. 31.100\n libswscale 4. 0.100 / 4. 0.100\n libswresample 2. 0.101 / 2. 0.101\n libpostproc 54. 0.100 /
54. 0.100\nInput #0, mov,mp4,m4a,3gp,3g2,mj2, from '/storage/emulated/0/Download/dolbycanyon.3gp':\n Metadata:\n
major_brand : 3gp4\n minor_version : 512\n
compatible_brands: isomiso23gp4\n Duration: 00:00:38.07, start:
0.006250, bitrate: 402 kb/s\n Stream #0:0(und): Video: h263 (s263 / 0x33363273), yuv420p, 704x576 [SAR 12:11 DAR 4:3], 384 kb/s, 29.97
fps, 29.97 tbr, 30k tbn, 29.97 tbc (default)\n Metadata:\n
handler_name : VideoHandler\n Stream #0:1(und): Audio: amr_nb
(samr / 0x726D6173), 8000 Hz, mono, flt, 12 kb/s (default)\n
Metadata:\n handler_name : SoundHandler\n[libx264 @
0xf64e5400] using SAR=11/12\n[libx264 @ 0xf64e5400] using cpu
capabilities: none!\n[libx264 @ 0xf64e5400] profile High, level
3.1\n[libx264 @ 0xf64e5400] 264 - core 148 - H.264/MPEG-4 AVC codec - Copyleft 2003-2015 - http://www.videolan.org/x264.html - options:
cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1
psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1
8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2
threads=12 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1
interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2
b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250
keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf
mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40
aq=1:1.00\n[mp4 @ 0xf64a8600] Could not find tag for codec amr_nb in
stream #1, codec not currently supported in container\nOutput #0, mp4,
to '/storage/emulated/0/Movies/rotate_video4.mp4':\n Metadata:\n
major_brand : 3gp4\n minor_version : 512\n
compatible_brands: isomiso23gp4\n encoder : Lavf57.25.100\n
Stream #0:0(und): Video: h264 (libx264) ([33][0][0][0] / 0x0021),
yuv420p, 576x704 [SAR 11:12 DAR 3:4], q=-1--1, 29.97 fps, 30k tbn,
29.97 tbc (default)\n Metadata:\n handler_name : VideoHandler\n encoder : Lavc57.24.102 libx264\n Side
data:\n unknown side data type 10 (24 bytes)\n Stream
0:1(und): Audio: amr_nb (samr / 0x726D6173), 8000 Hz, mono, 12 kb/s (default)\n Metadata:\n handler_name : SoundHandler\nStream
mapping:\n Stream #0:0 -> #0:0 (h263 (native) -> h264 (libx264))\n
Stream #0:1 -> #0:1 (copy)\nCould not write header for output file #0
(incorrect codec parameters ?): Invalid argument\n"
Why am i getting this error and how can i resolve it?
A:
MP4 does not officially support amr_nb audio. To force it anyway,
{"-y", "-ss", "" + startMs / 1000, "-t", "" + (endMs - startMs) / 1000, "-i", inputPath, "-vf", "transpose=" + type,"-c:a", "copy", "-atag","samr", outputPath}
But recommend you save to .3gp instead.
Alternatively, you can re-encode audio by dropping "-c:a", "copy"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there any kind of inverse for the "has" function (contains at least 1) negated to (contains none)
I am looking for all cards where the key has been returned. Closest I have been able to find is the has and hasNot, but hasNot isnt property based.
Trying to get it to be something like this
g.V().hasLabel('card').both().DOESNOTHAVE('keyReturned',false)
A hasAll would work as well
A:
This is what I came up with
g.V().hasLabel("Location").has("Name", "{location}").out("locatedat").not(out("being used by").has("approved", true).has("keyReturned", false))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java8: select min value from specific field of the objects in a list
Suppose to have a class Obj
class Obj{
int field;
}
and that you have a list of Obj instances, i.e. List<Obj> lst.
Now, how can I find in Java8 the minimum value of the int fields field from the objects in list lst?
A:
list.stream().min((o1,o2) -> Integer.compare(o1.field,o2.field))
Additional better solution from the comments by Brian Goetz
list.stream().min(Comparator.comparingInt(Obj::getField))
A:
You can also do
int min = list.stream().mapToInt(Obj::getField).min();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Automatically scroll to the bottom of a text area
I have a text area with scroll bar. At regular intervals, I am adding new lines of text to it. I would like the text area to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added. How can I accomplish this?
textAreaStatus = new WebTextArea();
scrollPane = new JScrollPane(textAreaStatus);
textAreaStatus.setBackground(Color.black);
textAreaStatus.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
A:
Have a look at the updatePolicy property of DefaultCaret: it might do what you want
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(ALWAYS_UPDATE);
A nice summary of options by Rob (@camickr)
A:
textArea.setCaretPosition(textArea.getDocument().getLength());
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP/MySQL/MariaDB - Single quotes vs no quotes on TINYINT; two servers with different behaviour
Using Laravel codebase, I have two servers, a DEV env, and a PRODUCTION env, which exhibit different handling of single vs. no quotes in a database query.
MySQL version in development
innobd_version: 5.5.50
protocal_version: 10
version: 5.5.50-0ubuntu0.14.04.1
version_compile_machine: x86_64
version_compile_os: debian-linux-gnu
MariaDB in production
innodb_version: 5.5.61-MariaDB-38.13
protocol_version: 10
version: 5.5.64-MariaDB
version_comment: MariaDB Server
version_compile_machine: x86_64
version_compile_os: Linux
Take this Laravel database query for example:
$records = table::all()->where('field_name', 1)->toArray();
'field_name' is, on both servers, set as TINYINT(1) and will be either a 0 or 1.
One the production server, the above query (no single quotes) works.
However, on the development server, it doesn't (it returns zero results).
On the flip, on the development server, it works if the where criteria (1) is in single quotes:
$records = table::all()->where('field_name', '1')->toArray();
But then this single-quoted version does not work on the production environment.
It's a pain as I have to wrap the statement in a server flag if statement, so it works on both envs.
It's not just this one example; it happens in a few similar places elsewhere on different tables/fields.
I'm guessing it's because one database is MySQL and the other is MariaDB. I'm wondering if I can make them both work consistently. I want the development database (MySQL 5.5.50) to handle it without single quotes. However, I'm not sure where to start looking. I welcome any advice on what could be causing this and how I can make my development server follow consistent behavior to production.
A:
You might try disabling strict mode in your database configuration.
config/database.php
'connections' => [
'mysql' => [
// ...
'strict' => false,
],
],
EDIT: On closer inspection, your field_name queries are not actually being sent to the database.
You are fetching the entire table as a collection, then filtering it afterwards with Laravel's collection methods. This is very inefficient and should be avoided whenever possible.
$records = table::all()->where('field_name', 1)->toArray();
// SQL = SELECT * FROM `table`;
// the ->where() is done with PHP...
You should be writing it like this to ask the database to only return the requested records. See the difference in the SQL?
$records = table::where('field_name', 1)->get()->toArray();
// SQL = SELECT * FROM `table` WHERE `field_name` = 1;
EDIT: You could also consider casting the value in your table's model, so it is always returned from the database as an integer.
https://laravel.com/docs/6.x/eloquent-mutators#attribute-casting
protected $casts = [
'field_name' => 'integer'
];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why Would reinterpret_cast of a Class and of Its Pre-Initialized Member Int Be the Same While Any Other Type of Variable Isnt?
I got this from an online exam (http://www.interqiew.com/tests?type=cpp) and have been stumped for some time.
I just don't get it. It compiles and runs fine. I've modified the code to be more expressive of the weirdness.
CODE:
#include <cstddef>
#include <iostream>
class A{
public:
A( ) : m_x( 3 ) { };
static ptrdiff_t member_offsetA(const A &a){
const char *p = reinterpret_cast<const char*>(&a);
const char *q = reinterpret_cast<const char*>(&a.m_x);
const char *z = reinterpret_cast<const char*>(&a.m_y);
const char *s = reinterpret_cast<const char*>(&a.m_s);
std::cout << q << " VS " << p << " VS " << z << " VS " << s << std::endl << std::endl;
return p-q;
}
static ptrdiff_t member_offsetB(const A &a){
const char *p = reinterpret_cast<const char*>(&a);
const char *q = reinterpret_cast<const char*>(&a.m_x);
const char *z = reinterpret_cast<const char*>(&a.m_y);
const char *s = reinterpret_cast<const char*>(&a.m_s);
std::cout << q << " VS " << p << " VS " << z << " VS " << s << std::endl << std::endl;
return z-s;
}
static ptrdiff_t member_offsetC(const A &a){
const char *p = reinterpret_cast<const char*>(&a);
const char *q = reinterpret_cast<const char*>(&a.m_x);
const char *z = reinterpret_cast<const char*>(&a.m_c);
std::cout << q << " VS " << q << std::endl << " VS " << z << std::endl;
return q-z;
}
private:
int m_x;
int m_c;
char m_y;
std::string m_s;
};
int main(){
A a;
std::cout << ( ( A::member_offsetA( a ) == 0 ) ? 0 : 1 ) << std::endl;
std::cout << ( ( A::member_offsetB( a ) == 0 ) ? 2 : 3 ) << std::endl;
std::cout << ( ( A::member_offsetC( a ) == 0 ) ? 4 : 5 ) << std::endl;
return 0;
}
OUTPUT: Symbols will be represented by unique letters preceded by three X's. So all XXXS's represent the same symbol. Whitespace means nothing was printed there.
XXXA VS XXXA VS VS XXXB
0
XXXA VS XXXA VS VS XXXB
3
XXXA VS XXXA
VS XXXF
5
How does any of this make sense?
Why would the casting for a class and a member int produce the same results? Wouldn't they be different? If they're the same, why would other member values be different?
Also, why would anyone ever use this?
P.S. Paste of actual output:
VS VS �@ VS �����
0
VS VS �@ VS �����
3
VS
VS �
5
A:
I don't see anything strange here. It makes perfect sense.
For normal, non-polymorphic classes the address of an instance of a class will be the same as the address of the first member of that class. That's just what an instance of a class is; it's the sum of all its members laid out sequentially (the instance itself adds nothing, unless it's a polymorphic class, or has non-empty base classes.) This is (not exactly but almost) called an "standard-layout" class in C++ (Note: the actual definition is obviously more complex.)
In the case of the members inside a class (and in fact for all variables,) no two of them can have the same address. And in fact they need 1 or more bytes of memory (you know, to store the bits of their respective values inside them.) So it again makes perfect sense for the addresses for consecutive members be different.
You might want to check out this code (which I believe is more instructive):
(Note: beware that there is "undefined behavior" in my particular use of pointer arithmetic here, so this in not completely correct C++. But to my knowledge it works fine. It's here for demonstration purposes anyways, so don't use this in production!)
#include <cstddef>
#include <iostream>
#include <string>
template <typename T, typename U>
ptrdiff_t Dist (T const * from, U const * to) {
return reinterpret_cast<char const *>(to) - reinterpret_cast<char const *>(from);
}
class A{
public:
A( ) : m_x( 3 ) { };
void printOffsetsAndSizes () const {
std::cout << "A: " << reinterpret_cast<uintptr_t>(this) << " (" << sizeof(*this) << ")" << std::endl;
std::cout << " m_x: " << Dist(this, &m_x) << " (" << sizeof(m_x) << ")" << std::endl;
std::cout << " m_c: " << Dist(this, &m_c) << " (" << sizeof(m_c) << ")" << std::endl;
std::cout << " m_y: " << Dist(this, &m_y) << " (" << sizeof(m_y) << ")" << std::endl;
std::cout << " m_s: " << Dist(this, &m_s) << " (" << sizeof(m_s) << ")" << std::endl;
}
private:
int m_x;
int m_c;
char m_y;
std::string m_s;
};
int main () {
A a;
a.printOffsetsAndSizes ();
return 0;
}
which gives this output on Ideone:
A: 3213332880 (16)
m_x: 0 (4)
m_c: 4 (4)
m_y: 8 (1)
m_s: 12 (4)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scala 2.10, Double.isNaN, and boxing
In Scala 2.10, is someDouble.isNaN expected to box? Running my code calling .isNaN through a decompiler, I still see telltale calls to double2Double in my code. Given the new AnyVal work in 2.10, I'd expect it to be no worse than java.lang.Double.isNaN(someDouble) at runtime with no spurious allocations. Am I missing something?
A:
Unfortunately, isNaN is a method on java.lang.Double, and it is essential to have an implicit conversion to java.lang.Double, so the Scala RichDouble value class cannot reimplement isNaN to be fast, and when you use isNaN you box to java.lang.Double.
Since this leaves only slow or awkward ways to test for NaN, I define
implicit class RicherDouble(val d: Double) extends AnyVal {
def nan = java.lang.Double.isNaN(d)
}
and then I can just use .nan to check.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Perl check if a string contains mysql timestamp
I have a variable $data that may or may not contain a mysql timestamp. I want to check if it actually contains a timestamp or not.
$data = '2015-11-21 13:45:20';
I can probably check it using a big regex like
/2[0-9][0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|2[0-9]|3[0-1]) ([01][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9]/
But is there an easier way ?
A:
You can use the Perl module DateTime::Format::MySQL. Its parse_datetime method will throw an exception if the input format isn't acceptable, or will return a DateTime object if it can be parsed as a MySQL datetime. It seems to be pretty strict, which may be what you want.
use strict;
use warnings;
use DateTime::Format::MySQL;
while(<DATA>){
chomp;
print "$_: ";
my $result = validate_date($_);
print defined $result
? "Recognized format. ($result)\n"
: "Unrecognized format.\n";
}
sub validate_date {
return eval {DateTime::Format::MySQL->parse_datetime(shift)};
}
__DATA__
2015-11-21 13:45:20
2015-11-21 13 : 45 : 20
With a DateTime object, and in particular, with the DateTime::Format::MySQL module it's pretty easy to turn around and output MySQL-ready datetime strings.
On the other hand, if the goal is to accept input, validate it, and then send it out to MySQL, you might consider using the parse_datetime method from DateTime::Format::DateParse to accept as wide a variety of date strings as practical. That module returns a DateTime object. Then you can use the DateTime::Format::MySQL method, format_datetime to convert that DT object to a useful MySQL format. That way you are being liberal in what you accept, but strict in what you output, which is often a reasonable design pattern.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ways to pack (adjacent) elements of a list into 2-tuples
I was wondering if there would be a concise/one-liner way to do the following:
pack :: [a] -> [(a, a)]
pack [] = []
pack [_] = []
pack (x:y:xs) = (x, y) : pack xs
Which is the same as:
pack' xs = [(x, y) | (x, y, i) <- zip3 xs (tail xs) [0..], even i]
I don’t have much against either of these two options, but I was wondering: is there more concise way by combining (,) with some other function?
I had assumed there’d be such a way, but it eludes me. So this is just out of curiosity.
Thanks!
A:
We can easily split the list into two lists with alternating elements with this tidbit (due to HaskellWiki)
foldr (\a ~(x,y) -> (a:y,x)) ([],[])
All that remains is to combine the lists with zip
pack :: [a] -> [(a, a)]
pack = uncurry zip . foldr (\a ~(x,y) -> (a:y,x)) ([],[])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is %$var dereferencing a Perl hash?
I'm sending a subroutine a hash, and fetching it with my($arg_ref) = @_;
But what exactly is %$arg_ref? Is %$ dereferencing the hash?
A:
$arg_ref is a scalar since it uses the $ sigil. Presumably, it holds a hash reference. So yes, %$arg_ref deferences that hash reference. Another way to write it is %{$arg_ref}. This makes the intent of the code a bit more clear, though more verbose.
To quote from perldata(1):
Scalar values are always named with '$', even when referring
to a scalar that is part of an array or a hash. The '$'
symbol works semantically like the English word "the" in
that it indicates a single value is expected.
$days # the simple scalar value "days"
$days[28] # the 29th element of array @days
$days{'Feb'} # the 'Feb' value from hash %days
$#days # the last index of array @days
So your example would be:
%$arg_ref # hash dereferenced from the value "arg_ref"
my($arg_ref) = @_; grabs the first item in the function's argument stack and places it in a local variable called $arg_ref. The caller is responsible for passing a hash reference. A more canonical way to write that is:
my $arg_ref = shift;
To create a hash reference you could start with a hash:
some_sub(\%hash);
Or you can create it with an anonymous hash reference:
some_sub({pi => 3.14, C => 4}); # Pi is a gross approximation.
A:
Instead of dereferencing the entire hash like that, you can grab individual items with
$arg_ref->{key}
A:
A good brief introduction to references (creating them and using them) in Perl is perldoc perfeftut. You can also read it online (or get it as a pdf). (It talks more about references in complex data structures than in terms of passing in and out of subroutines, but the syntax is the same.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Check if a $_SESSION variable is set from Javascript
I'm building a message system to learn how it works, and I've already got
pretty much everything. I can log in and make a post on a board, but now I would like to be able to edit it. The back-end is ready, it receives a POST request
Basically what I need to do is check if the currently logged in user is the author of a certain post from Javascript to show or hide the edit button. I know how to tell if the user is logged in from PHP so that it blocks requests if you aren't the author, but I can't hide or show the buttons as the posts are dinamically generated from a <template> using JS.
Login snippet:
$_SESSION["userid"] = $userid;
Edit check PHP snippet (kinda pseudo-code):
if ($_POST["action"] == "modifypost" && isset($_POST["postid"]) && isset($_POST["content"]))
{
$post = get_post($_POST["postid"]);
if ($post.userid != $_SESSION["userid"])
{
die("you are not allowed");
}
//MySQL queries
}
Post dynamic generation (abbreviated):
function add_post(post) {
var t = document.querySelector('#historypost');
t.content.querySelector(".content").innerHTML = post.content;
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
}
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>, but then the user would be able to manually set that variable from the console and show the buttons.
A:
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>
Yes, this is one correct approach. Basically, use PHP to tell JavaScript which posts actually belong to the current user.
but then the user would be able to manually set that variable from the console and show the buttons
True. There is no way to secure information from user-meddling once you've sent it to the browser. This is because the user is in control of what gets executed in the browser. Instead of thinking of the button visibility as a security feature, think of it as a convenience -- something to make the user experience more pleasing.
Application security is really enforced on the server. Just make sure that one user is not allowed to edit another user's posts, and do not trust what comes from the browser. Verify inputs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are questions about standard vocabularies, data and metadata formats, and ontologies on topic here?
Are questions such as:
What metadata is required to make a specific data product useable (and how should I format it?)
How can I make sure my raster data complies with standard X?
What type of metadata format should I use for data of type Y?
Is there a preferred vocabulary or ontology for data in domain Z?
On topic?
A:
They probably belong to this spectrum of questions that could be on topic on multiple sites. Questions about portability lean more towards the implementation side and are possibly more appropriate for software engineering stackexchange.
Compliance questions, in my opinion, are off-topic here unless they have some clear connection to the "science" part of data science.
Questions like
Is there a preferred vocabulary or ontology for data in domain Z?
are probably also on topic on open data stackexchange.
In general, I think other sites will generate more and better answers. However, at this point it's fair to assume that they will be decided on a case by case basis if posted here first.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can't locate CM.pm in @INC in perl
I am trying to run perl script which contain use CM, use CM_USER and use CM_METRICS statement and I am getting error "Can't locate CM.pm in @INC". I have also tried to install these using CPAN but it also giving me error "cannot install".
A:
You won't be able to install them from CPAN because they don't look like they are on CPAN.
Where did you get this program from? You'll need to ask the author where you can get the modules from.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Zooming an SKNode inconsistent
I have created my own solution for zooming in or out on a specific SKNode without having the zoom the entire scene, and it seems to work mostly how I would expect it to work, with 2 notable exceptions which I am hoping to get input on here. First the code (this control statement is within the touchesMoved method):
if (touches.count == 2) {
// this means there are two fingers on the screen
NSArray *fingers = [touches allObjects];
CGPoint fingOneCurr = [fingers[0] locationInNode:self];
CGPoint fingOnePrev = [fingers[0] previousLocationInNode:self];
CGPoint fingTwoCurr = [fingers[1] locationInNode:self];
CGPoint fingTwoPrev = [fingers[1] previousLocationInNode:self];
BOOL yPinch = fingOneCurr.y > fingOnePrev.y && fingTwoCurr.y < fingTwoPrev.y;
BOOL yUnpinch = fingOneCurr.y < fingOnePrev.y && fingTwoCurr.y > fingTwoPrev.y;
BOOL xPinch = fingOneCurr.x > fingOnePrev.x && fingTwoCurr.x < fingTwoPrev.x;
BOOL xUnpinch = fingOneCurr.x < fingOnePrev.x && fingTwoCurr.x > fingTwoPrev.x;
if (xUnpinch | yUnpinch) {
if (YES) NSLog(@"This means an unpinch is happening");
mapScale = mapScale +.02;
[map setScale:mapScale];
}
if (xPinch | yPinch) {
if (YES) NSLog(@"This means a pinch is happening");
mapScale = mapScale - .02;
[map setScale:mapScale];
}
}
Now the problems:
The pinch and unpinch are not always right sometimes, and I cannot quite put my finger on when this is happening, the pinch will behave as an unpinch and vis a versa.
When the pinching and unpinching is scaling the SKNode correctly, it is rarely as smooth as I would like. There is a bit of jerkiness to it which I find annoying.
Can anyone suggest improvements to this method? Thanks!
A:
This will solve your problem, thanks to Steffen for the hints.
- (void)didMoveToView:(SKView *)view
{
UIPinchGestureRecognizer *precog = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
[self.scene.view addGestureRecognizer:precog];
}
- (void)handlePinch:(UIPinchGestureRecognizer *) recognizer
{
//NSLog(@"Pinch %f", recognizer.scale);
//[_bg setScale:recognizer.scale];
[_bg runAction:[SKAction scaleBy:recognizer.scale duration:0]];
recognizer.scale = 1;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Move the ESXi service console from vmnic0 to vmnic1.123
I have an VMware ESXi 4.0.0 with 2 physical network cards. First one, vmnic0, has only the Service Console and the other one, vmnic1, is a trunk with all VLANs (including the management VLAN used by the Service Console). I would like to free vmnic0 port to be able to connect a network storage and I would like to move the management IP from vmnic0 to vmnic1/VLAN123.
Can I do this remotely? Is it possible from vSphere client? Should I do it from the ESXi console?
A:
Its best if you do this over the console, in case you lose the management network.
When at the console (this is from memory) you press F2, and edit the management network settings. There is a field for vlan and network adapters.
You can do it over the vSphere client too. Under the host configuration, in network settings, add a new service console connection and add it to the vswtich using eth1; ensure you fill in the vlan field.
Connect to the new managment interface, and then under the network settings remove the old service console.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Misunderstanding of Long data type in VBA
From the help for the Overflow Error in VBA, there's the following examples:
Dim x As Long
x = 2000 * 365 ' gives an error
Dim x As Long
x = CLng(2000) * 365 ' fine
I would have thought that, since the Long data type is supposed to be able to hold 32-bit numbers, that the first example would work fine.
I ask this because I have some code like this:
Dim Price as Long
Price = CLng(AnnualCost * Months / 12)
and this throws an Overflow Error when AnnualCost is 5000 and Months is 12.
What am I missing?
A:
2000 and 365 are Integer values. In VBA, Integers are 16-bit signed types, when you perform arithmetic on 2 integers the arithmetic is carried out in 16-bits. Since the result of multiplying these two numbers exceeds the value that can be represented with 16 bits you get an exception. The second example works because the first number is first converted to a 32-bit type and the arithmetic is then carried out using 32-bit numbers. In your example, the arithmetic is being performed with 16-bit integers and the result is then being converted to long but at that point it is too late, the overflow has already occurred. The solution is to convert one of the operands in the multiplication to long first:
Dim Price as Long
Price = CLng(AnnualCost) * Months / 12
|
{
"pile_set_name": "StackExchange"
}
|
Q:
dotnet publish only one project from the solution in VSTS
We are trying to build one project from a Visual Studio solution in VSTS with .NET Core task. We are able to "dotnet build" that project. But when we try to "dotnet publish" it tries to publish all projects from the solution. Even if we use "dotnet custom", it tries to publish all projects.
Is there a way to use .NET Core task to publish only one project or projects that were built? Or should we run a custom command line task?
Reason for this is that we have a project that won't build and we don't need/want to publish it. So we would like to build and publish one project and not all projects.
A:
You can use dotnet publish <Path to .csproj>. This will build and publish only the specified project and projects it depends on.
In order to specify a project in the '.Net Core' task with the command 'publish' you have to uncheck 'Publish Web Projects'.
A:
Another solution would be to set IsPublishable in csproj.
I usually do it in cases where it's a unit test project or else that doesn't need to be published if you run dotnet publish for solution file.
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
<IsPublishable>false</IsPublishable >
<Configurations>prod;stage;dev</Configurations>
<Platforms>AnyCPU</Platforms>
</PropertyGroup>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
xsd to java bean jaxb field name
I have created java beans from the following xsd files
person.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb" elementFormDefault="qualified"
jxb:version="2.0">
<xs:annotation>
<xs:appinfo>
<jxb:globalBindings>
<jxb:serializable uid="1"/>
</jxb:globalBindings>
<jxb:schemaBindings>
<jxb:package name="com.thiyanesh"/>
</jxb:schemaBindings>
</xs:appinfo>
</xs:annotation>
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:long"/>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
team.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb" elementFormDefault="qualified"
jxb:version="2.0">
<xs:import schemaLocation="person.xsd"/>
<xs:annotation>
<xs:appinfo>
<jxb:globalBindings>
<jxb:serializable uid="2"/>
</jxb:globalBindings>
<jxb:schemaBindings>
<jxb:package name="com.thiyanesh"/>
</jxb:schemaBindings>
</xs:appinfo>
</xs:annotation>
<xs:element name="team">
<xs:complexType>
<xs:sequence>
<xs:element ref="person" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The objective is to define Person as separate class and include list of person in Team class.
Now the class Team contains the field
List<Person> person;
Is there a way to give a different name to this field? Say "members".
List<Person> members;
I may not be able to edit the generated class.
A:
This bindings works fine
<bindings version="2.0" xmlns="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:annox="http://annox.dev.java.net"
xmlns:namespace="http://jaxb2-commons.dev.java.net/namespace-prefix">
<bindings schemaLocation="../path/team.xsd">
<bindings node="//xs:element[@name='team']//xs:complexType//xs:sequence//xs:element[@ref='person']">
<property name="members"/>
</bindings>
</bindings>
</bindings>
else
<xs:element name="team">
<xs:complexType>
<xs:sequence>
<xs:element ref="person" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:appinfo>
<jxb:property name="members" />
</xs:appinfo>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TFS 2015 Code Coverage is not displaying
I'm using TFS 2015 (Update 2.1) build process and everything is working as expected except the code coverage part.
Build with VS Test
(Code coverage enabled)
After successful build:
(testcase executed without code coverage)
When I checked log, this is what I found:
Warning: Diagnostic data adapter message: Could not find diagnostic data adapter 'Code Coverage'. Make sure diagnostic data adapter is installed and try again.
I have tried
De-attaching-attaching collection
Re-installed Agent
Have included .runsettings file
but no luck.
A:
Install Visual Studio Enterprise on your build server, assuming you have appropriate licensing. Code coverage is an Enterprise feature.
A:
You can also get the coverage report without having to have Visual Studio Enterprise Installed. But you would need "Visual Studio Test Agent". You can download it here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Substitute on quoted arguments
Looking for a way to use substitute on quoted language objects as expression.
substitute expects to get lazy expression in expr.
To goal is to substitute .expr in expr.template which is a language objects generated dynamically based on metadata.
## data
expr = quote(x <- f(10))
expr.template = quote(g(.expr, flag = TRUE))
## expected output
quote(g(x <- f(10), flag = TRUE))
#g(x <- f(10), flag = TRUE)
## current workaround
h = function(expr, expr.template){
eval(substitute(
substitute(
.expr.template,
list(.expr = expr)
),
list(.expr.template = expr.template)
))
}
h(expr = expr, expr.template = expr.template)
#g(x <- f(10), flag = TRUE)
So I would be surprised if there wouldn't be any more canonical way to deal with it. Base R solution preferred.
A:
Use do.call:
do.call("substitute", list(expr.template, list(.expr = expr)))
## g(x <- f(10), flag = TRUE)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to link a hash link from the URL to Javascript content?
I've once used jQuery UI in order to add the tab feature to one of my project.
Everything was working just fine, and I noticed each tab was bound to a URL hash tag (I do not know you say it in english). As an example, once I clicked on the first tab, #Tab0 was added to my URL.
I want to reproduce this behavior in my current project. But I'm not using jQuery UI tabs, I am porting a desktop application and there are JavaScript buttons which write and replace content inside my page (in the manner of different pages, but without reloading).
How do I proceed to mimic this behavior ? Do I have to manually fetch the tag in the URL and do things accordingly all by JavaScript ?
Thanks,
A:
u could do it this way:
creating an url with hash from current url:
var url = window.location.href + '#Tab0';
reading a hash from current url:
var hash;
if (window.location.href.indexOf('#') > -1)
{
hash = url.split('#')[1];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is allObjects() method in Realm was deprecated?
I'm trying to display list items in a ListView using Realm offline database. I followed some tutorial and he used allObjects() method that cannot be resolved with me!!
Can you help me in this?
Here is my code:
@Override
protected void onResume() {
super.onResume();
Realm.init(getApplicationContext());
RealmConfiguration config = new RealmConfiguration.
Builder().
deleteRealmIfMigrationNeeded().
build();
Realm.setDefaultConfiguration(config);
Realm realm = Realm.getInstance(config);
realm.beginTransaction();
List<Car> cars = realm.**allObjects**(Car.class);
String[] names = new String[cars.size()];
for(int i=0; i<names.length;i++){
names[i]=cars.get(i).getName();
}
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,names);
listView.setAdapter(adapter);
}
A:
realm.beginTransaction();
You don't need that.
List<Car> cars = realm.**allObjects**(Car.class);
realm.allObjects(Car.class) was replaced with realm.where(Car.class).findAll(). Specifically, allObjects was deprecated in 0.90.0, and removed in 0.91.0, see here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AngularJS directives
I've been reading the AngularJS docs and found something that I still don't understand:
For cases where the attribute name is the same as the value you want
to bind to inside the directive's scope, you can use this shorthand
syntax:
...
scope: {
// same as '=customer'
customer: '='
},
...
Looking at the final example (my-tabs/my-pane) the code is this one:
.directive('myPane', function() {
return {
require: '^myTabs',
restrict: 'E',
transclude: true,
scope: {
title: '@'
},
link: function(scope, element, attrs, tabsCtrl) {
tabsCtrl.addPane(scope);
},
templateUrl: 'my-pane.html'
};
});
I've tried to change the '@' by '=' and the example breaks. So what is doing '@'? And why '=' neither '=title' are not working here?
A:
When you use = you are specifying a two-way binding between the property of the parent scope and the one that will be created on the directive's scope. That means that the value of the attribute will usually be an identifier that matches a property on the parent scope.
When you use @ you are specifying a one-way binding. The result will always be a string. Changes to the property on the directive scope will not affect the parent scope (since the model is not a reference to a parent scope property).
In your example the title property is a literal string rather than a reference to a property on the parent scope. When you change the @ to = it breaks because there is no property with the right name on the parent scope.
This is documented under the $compile service.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can the Facebook API be used to create link posts with summaries?
When adding a link post in Facebook, a nice looking description (containing a snippet of text from the linked page) and thumbnail are automatically added to the post.
Is there a way to do this automatically using the Facebook API? I am inclined to think that there is not, because posts added by IFTTT, a popular web application that uses the Facebook API, do not contain descriptions. I am unclear as to whether this is a limitation with the Facebook API, and whether there is any way around it.
A:
Yes, it's possible. You can use the Graph Api Method /profile_id/feed. The method receives the arguments message, picture, link, name, caption, description, source, place and tags. The facebook organize the parameters in a "nice looking summary and thumbnail".
You can get more information in the publishing section in the link http://developers.facebook.com/docs/reference/api/
In c#:
public static bool Share(string oauth_token, string message, string name, string link, string picture)
{
try
{
string url =
"https://graph.facebook.com/me/feed" +
"?access_token=" + oauth_token;
StringBuilder post = new StringBuilder();
post.AppendFormat("message={0}", HttpUtility.UrlEncode(message));
post.AppendFormat("&name={0}", HttpUtility.UrlEncode(name));
post.AppendFormat("&link={0}", HttpUtility.UrlEncode(link));
post.AppendFormat("&picture={0}", HttpUtility.UrlEncode(picture));
string result = Post(url, post.ToString());
}
catch (Exception)
{
return false;
}
return true;
}
private static string Post(string url, string post)
{
WebRequest webRequest = WebRequest.Create(url);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(post);
webRequest.ContentLength = bytes.Length;
Stream stream = webRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse webResponse = webRequest.GetResponse();
StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
return streamReader.ReadToEnd();
}
UPDATE:
Open graph protocol meta tags: http://developers.facebook.com/docs/opengraphprotocol/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove (.unrst) file from the Eclipse/petrel simulation?
I am running my simulations with Eclipse E100, and the run generates a file with extension .unrst which takes a lot of space in the folder
Is there a way to stop the simulation from generating this file
Best Regards
A:
If you don't want unified restart files select summmary, .UNSMRY (unified) or .Snnnn, or non-unified restart (.Xnnnn).
FMTOUT for format and/or UNIFOUT for unification (Details).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Automatically Update Page in Browser when Changes are Made in Visual Studio
Okay I may be crazy, but I could swear that I have seen webpages being worked on in Visual Studio update when changes are made and the file is save the file. NO manual page refresh.
These were not changes made through the debugger. Made in Visual Studio.
Is there something that does that and if so what is it called?
A:
You saw result of Browser Link work. Nothing else can do so
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Почему массив не изменяется?
Да, то, что я хочу, можно реализовать через return в функции, но меня волнует мой вопрос.
Почему arr не меняется при использовании функции?
function filterRange(arr, start, end) {
arr = arr.filter(item => (item >= start && item <= end));
}
let arr = [5, 3, 8, 1];
let filtered = filterRange(arr, 1, 4);
alert( filtered ); // 5, 3, 8, 1
alert( arr ); // 5, 3, 8, 1
A:
function filterRange(arr, start, end) {
// т.к. ссылка на объект является значением, ф-ция получает копию этой ссылки
arr = arr.filter(item => (item >= start && item <= end));
// arr = ... - меняет копию ссылки, из-за этого изменения и не видны снаружи;
// в данном случае ссылке arr присваивается новый массив -
// arr.filter(item => (item >= start && item <= end));
}
let arr = [5, 3, 8, 1]; // arr - ссылка на место в памяти где лежит массив [5, 3, 8, 1];
let filtered = filterRange(arr, 1, 4); // ссылка передается аргументом в функцию;
alert( filtered ); // 5, 3, 8, 1
alert( arr ); // 5, 3, 8, 1
Дело в следующем... Аргументы ф-ции передаются по значению и ф-ция принимает только копию этого значения, а в JavaScript-е ссылки на объекты являются значениями. Т.е. в данном случае, ты перезаписываешь копию ссылки аргумента(массива), из-за этого изменения не видны снаружи. Но если ты изменишь сам объект,а не ссылку (например arr.push(20)), то внешний массив изменится.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
is loading multiple times
I am using ngTemplateOutlet to load . but It loads a template multiple times .It is loading correct template but it executing multiple times loadTemplate() method.
In HTML:
<table>
<thead>
</thead>
<tbody>
<ng-template [ngTemplateOutlet]="loadTemplate()"></ng-template>
</tbody>
</table>
<ng-template #template1>
<tr *ngFor="iteration">
<p>Hiii</p>
</tr>
</ng-template>
<ng-template #template2>
<tr *ngFor="iteration">
<p>Byee</p>
</tr>
</ng-template>
In my component.ts:
@ViewChild('template1') template1: TemplateRef<any>;
@ViewChild('template1') template1: TemplateRef<any>;
loadTemplate(){
if (condition)
return this.template1;
return this.template2;
}
A:
[ngTemplateOutlet]="loadTemplate()"
causes loadTemplate() to be called every time change detection runs.
Rather assign the result of loadTemplate() to a field and use that field in binding
[ngTemplateOutlet]="myTemplate"
then change detection and the ngTemplateOutlet directive can see that there was no change and won't re-initialize the template.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
G1GC remark phase is taking too long
My server application under load some times goes unresponsive and i found the issue to be related to very long "GC Remark". There is no garbage collection tuning implemented. My test server is a 4 core/8 gb/8 GB swap.
This is the log output from gc logs.
2014-04-06T04:39:58.426+0530: 67263.405: [GC remark, 46.7308340 secs]
2014-04-06T04:40:45.167+0530: 67310.146: [GC cleanup 1951M->1750M(2954M), 0.0037930 secs]
2014-04-06T04:40:45.174+0530: 67310.153: [GC concurrent-cleanup-start]
2014-04-06T04:40:45.175+0530: 67310.154: [GC concurrent-cleanup-end, 0.0002800 secs]
2014-04-06T04:40:45.633+0530: 67310.612: [GC pause (young) 2451M->1546M(2954M), 0.0764360 secs]
2014-04-06T04:40:45.815+0530: 67310.794: [GC pause (young) (initial-mark) 1672M->1554M(2954M), 0.0687640 secs]
2014-04-06T04:40:45.884+0530: 67310.863: [GC concurrent-root-region-scan-start]
2014-04-06T04:40:45.912+0530: 67310.891: [GC concurrent-root-region-scan-end, 0.0285320 secs]
2014-04-06T04:40:45.912+0530: 67310.891: [GC concurrent-mark-start]
2014-04-06T04:40:46.919+0530: 67311.898: [GC pause (young) 2590M->1622M(2954M), 0.0752180 secs]
2014-04-06T04:40:47.231+0530: 67312.210: [GC concurrent-mark-end, 1.3191870 secs]
2014-04-06T04:40:47.239+0530: 67312.218: [GC remark, 46.6353020 secs]
In this state, i tried turn off swap, but that doesnt seems to help reduce the remark time. There is another test server which runs 4 gb memory and there things are better and stable.
Any thoughts on how i can improve this situation.
====== EDIT - Adding logs from -XX:+PrintGCDetails =========
2014-04-06T09:45:30.953+0530: 7777.585: [GC remark 2014-04-06T09:45:30.959+0530: 7777.590: [GC ref-proc, 24.9282110 secs], 24.9556400 secs]
[Times: user=24.89 sys=0.06, real=24.96 secs]
2014-04-06T09:45:55.921+0530: 7802.553: [GC cleanup 2053M->1822M(2954M), 0.0039070 secs]
[Times: user=0.01 sys=0.00, real=0.01 secs]
2014-04-06T09:45:55.928+0530: 7802.560: [GC concurrent-cleanup-start]
2014-04-06T09:45:55.929+0530: 7802.560: [GC concurrent-cleanup-end, 0.0003390 secs]
2014-04-06T09:45:56.254+0530: 7802.885: [GC pause (young), 0.0770030 secs]
[Parallel Time: 70.3 ms, GC Workers: 4]
[GC Worker Start (ms): Min: 7802888.9, Avg: 7802889.0, Max: 7802889.0, Diff: 0.1]
[Ext Root Scanning (ms): Min: 22.2, Avg: 24.2, Max: 26.5, Diff: 4.2, Sum: 96.7]
[Update RS (ms): Min: 13.8, Avg: 15.9, Max: 18.2, Diff: 4.4, Sum: 63.7]
[Processed Buffers: Min: 177, Avg: 183.2, Max: 189, Diff: 12, Sum: 733]
[Scan RS (ms): Min: 0.2, Avg: 0.3, Max: 0.3, Diff: 0.1, Sum: 1.2]
[Object Copy (ms): Min: 29.2, Avg: 29.6, Max: 30.4, Diff: 1.2, Sum: 118.4]
[Termination (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.2]
[GC Worker Other (ms): Min: 0.0, Avg: 0.1, Max: 0.1, Diff: 0.1, Sum: 0.3]
[GC Worker Total (ms): Min: 70.0, Avg: 70.1, Max: 70.2, Diff: 0.1, Sum: 280.5]
[GC Worker End (ms): Min: 7802959.0, Avg: 7802959.1, Max: 7802959.1, Diff: 0.1]
[Code Root Fixup: 0.0 ms]
[Clear CT: 0.2 ms]
[Other: 6.5 ms]
[Choose CSet: 0.0 ms]
[Ref Proc: 1.4 ms]
[Ref Enq: 0.0 ms]
[Free CSet: 1.1 ms]
[Eden: 766.0M(766.0M)->0.0B(101.0M) Survivors: 28.0M->46.0M Heap: 2359.1M(2954.0M)->1610.6M(2954.0M)]
[Times: user=0.29 sys=0.00, real=0.07 secs]
2014-04-06T09:45:56.434+0530: 7803.066: [GC pause (mixed), 0.0560090 secs]
[Parallel Time: 50.4 ms, GC Workers: 4]
[GC Worker Start (ms): Min: 7803069.3, Avg: 7803069.3, Max: 7803069.4, Diff: 0.1]
[Ext Root Scanning (ms): Min: 20.9, Avg: 23.2, Max: 26.1, Diff: 5.3, Sum: 92.6]
[Update RS (ms): Min: 1.4, Avg: 4.0, Max: 6.6, Diff: 5.2, Sum: 16.1]
[Processed Buffers: Min: 29, Avg: 38.0, Max: 49, Diff: 20, Sum: 152]
[Scan RS (ms): Min: 0.2, Avg: 0.2, Max: 0.3, Diff: 0.0, Sum: 0.9]
[Object Copy (ms): Min: 22.4, Avg: 22.8, Max: 23.6, Diff: 1.1, Sum: 91.2]
[Termination (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]
[GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.0, Sum: 0.2]
[GC Worker Total (ms): Min: 50.2, Avg: 50.3, Max: 50.3, Diff: 0.1, Sum: 201.0]
[GC Worker End (ms): Min: 7803119.6, Avg: 7803119.6, Max: 7803119.6, Diff: 0.0]
[Code Root Fixup: 0.0 ms]
[Clear CT: 0.1 ms]
[Other: 5.5 ms]
[Choose CSet: 0.0 ms]
[Ref Proc: 1.1 ms]
[Ref Enq: 0.0 ms]
[Free CSet: 0.4 ms]
[Eden: 101.0M(101.0M)->0.0B(934.0M) Survivors: 46.0M->5120.0K Heap: 1727.6M(2954.0M)->1608.3M(2954.0M)]
[Times: user=0.20 sys=0.00, real=0.05 secs]
2014-04-06T09:45:56.612+0530: 7803.244: [GC pause (young) (initial-mark), 0.0612000 secs]
[Parallel Time: 54.2 ms, GC Workers: 4]
[GC Worker Start (ms): Min: 7803247.0, Avg: 7803248.2, Max: 7803252.0, Diff: 5.0]
[Ext Root Scanning (ms): Min: 19.9, Avg: 24.1, Max: 28.7, Diff: 8.8, Sum: 96.3]
[Update RS (ms): Min: 12.4, Avg: 15.0, Max: 17.4, Diff: 5.1, Sum: 60.2]
[Processed Buffers: Min: 48, Avg: 63.8, Max: 79, Diff: 31, Sum: 255]
[Scan RS (ms): Min: 0.0, Avg: 0.1, Max: 0.1, Diff: 0.1, Sum: 0.2]
[Object Copy (ms): Min: 12.3, Avg: 13.5, Max: 16.6, Diff: 4.2, Sum: 54.2]
[Termination (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]
[GC Worker Other (ms): Min: 0.0, Avg: 0.1, Max: 0.1, Diff: 0.1, Sum: 0.2]
[GC Worker Total (ms): Min: 49.1, Avg: 52.8, Max: 54.0, Diff: 5.0, Sum: 211.1]
[GC Worker End (ms): Min: 7803301.0, Avg: 7803301.0, Max: 7803301.1, Diff: 0.1]
[Code Root Fixup: 0.0 ms]
[Clear CT: 0.1 ms]
[Other: 6.8 ms]
[Choose CSet: 0.0 ms]
[Ref Proc: 1.0 ms]
[Ref Enq: 0.0 ms]
[Free CSet: 0.4 ms]
[Eden: 134.0M(934.0M)->0.0B(927.0M) Survivors: 5120.0K->16.0M Heap: 1741.7M(2954.0M)->1618.8M(2954.0M)]
[Times: user=0.22 sys=0.00, real=0.07 secs]
2014-04-06T09:45:56.675+0530: 7803.306: [GC concurrent-root-region-scan-start]
2014-04-06T09:45:56.685+0530: 7803.316: [GC concurrent-root-region-scan-end, 0.0100810 secs]
2014-04-06T09:45:56.685+0530: 7803.316: [GC concurrent-mark-start]
2014-04-06T09:45:57.759+0530: 7804.391: [GC pause (young), 0.0648020 secs]
[Parallel Time: 55.0 ms, GC Workers: 4]
[GC Worker Start (ms): Min: 7804393.8, Avg: 7804393.9, Max: 7804393.9, Diff: 0.1]
[Ext Root Scanning (ms): Min: 21.4, Avg: 23.8, Max: 26.5, Diff: 5.1, Sum: 95.0]
[SATB Filtering (ms): Min: 0.0, Avg: 0.4, Max: 1.7, Diff: 1.7, Sum: 1.7]
[Update RS (ms): Min: 13.3, Avg: 15.4, Max: 18.3, Diff: 5.0, Sum: 61.7]
[Processed Buffers: Min: 110, Avg: 165.8, Max: 224, Diff: 114, Sum: 663]
[Scan RS (ms): Min: 0.3, Avg: 0.4, Max: 0.4, Diff: 0.0, Sum: 1.4]
[Object Copy (ms): Min: 14.4, Avg: 14.8, Max: 15.5, Diff: 1.1, Sum: 59.1]
[Termination (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]
[GC Worker Other (ms): Min: 0.0, Avg: 0.1, Max: 0.1, Diff: 0.1, Sum: 0.3]
[GC Worker Total (ms): Min: 54.7, Avg: 54.8, Max: 54.9, Diff: 0.1, Sum: 219.3]
[GC Worker End (ms): Min: 7804448.7, Avg: 7804448.7, Max: 7804448.7, Diff: 0.1]
[Code Root Fixup: 0.0 ms]
[Clear CT: 0.3 ms]
[Other: 9.6 ms]
[Choose CSet: 0.0 ms]
[Ref Proc: 4.5 ms]
[Ref Enq: 0.0 ms]
[Free CSet: 1.2 ms]
[Eden: 916.0M(927.0M)->0.0B(853.0M) Survivors: 16.0M->25.0M Heap: 2592.4M(2954.0M)->1685.9M(2954.0M)]
[Times: user=0.24 sys=0.00, real=0.07 secs]
2014-04-06T09:45:58.330+0530: 7804.961: [GC concurrent-mark-end, 1.6449220 secs]
2014-04-06T09:45:58.335+0530: 7804.967: [GC remark 2014-04-06T09:45:58.339+0530: 7804.970: [GC ref-proc, 26.3976280 secs], 26.4233450 secs]
[Times: user=26.28 sys=0.14, real=26.42 secs]
==== Edit After adding -XX:+PrintReferenceGC and -XX:+ParallelRefProcEnabled ======
[GC remark :
[GC ref-proc:
[SoftReference, 122658 refs, 11.4784560 secs]
[WeakReference, 714 refs, 0.1420020 secs]
[FinalReference, 32 refs, 0.0145060 secs]
[PhantomReference, 37 refs, 0.0144000 secs]
[JNI Weak Reference, 1.2714530 secs]
, 12.9211700 secs]
, 12.9469960 secs]
Now softreference is taking most of the time. I have found a code section which creates a large number of softreferences per second. I will disable that and see if it helps.
========== EDIT - After Removing softreference from code ==========
After removing soft references by fixing code, things have vastly improved and SoftRefernece processing time is negligible now !!! . One last problem i still see "JNI Weak Reference" time gradually increasing. I will investigate that issue now.
A:
I'm not sure if this is a red-herring, but according to this article the remark phase also does reference processing. So if your application is using huge numbers of soft/weak references, it could inflate the remark phase.
If you add Option -XX:+PrintGCDetails you might get more info in the GC log ...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Current conversations logic for simple messaging system
I am building a simple messaging system with Rails3 that allows users to send private messages to each other. Each set of users can have a single stream of messages between each other (like texting)
I am confused however on the logic that is used to build the view that shows all current conversations going on for a user. This includes conversations that might only include sent messages from myself.
My schema has the following:
create_table "messages", :force => true do |t|
t.integer "from_id"
t.integer "to_id"
t.string "message"
t.datetime "created_at"
t.datetime "updated_at"
end
I would like to emulate something similar to FB messaging that shows a row for each conversation.`
Any ideas would be super helpful.
Thanks!
Danny
A:
There are two sets of messages to consider:
Those where from_id is the current user.
Those where to_id is the current user.
I'd go with a find_by_sql and let the database do all the work:
chatting_with = User.find_by_sql(%Q{
select * from users where id in (
select to_id as user_id from messages where from_id = :the_user
union all
select from_id as user_id from messages where to_id = :the_user
)
}, :the_user => the_user_in_question.id)
An SQL UNION simply does a set-wise union of the two result sets so the above will grab all the users that the_user_in_question has sent messages to and combine that with the users that have sent messages to the_user_in_question; the result will be all the users that are involved in conversations with the_user_in_question as an array of User instances. Since there is an IN on the UNION you can use UNION ALL to avoid a little bit of extra work in the UNION.
You'd probably want to wrap that in a class method on Message:
def self.conversations_involving(user)
User.find_by_sql(%Q{
select * from users where id in (
select to_id as user_id from messages where from_id = :the_user
union all
select from_id as user_id from messages where to_id = :the_user
)
}, :the_user => user.id)
end
And then you could just say things like:
@other_users = Message.conversations_involving(current_user)
in your controller.
You'll want to add indexes to messages.from_id and messages.to_id in your database too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
sysctl vs writing directly to /proc/*
On a typical linux machine you can change kernel configuration by modifying the files located at /proc/*.
For example, for the IPv6 accept_dad parameter of a specific network interface (say, eth0), you'd modify the following file:
/proc/sys/net/ipv6/conf/eth0/accept_dad
But, as I recently discovered, there is the widely spread tool, sysctl, which has the same purpose, and works like so:
sysctl -w net.ipv6.conf.eth0.accept_dad=1
My question is, when should we use which tool? My instinct says that if you know what you're doing, you should write to file directly but, if you would like validations and what not, you should use sysctl.
Since sysctl is yet another layer over something that we can control directly, I think by using it we're exposing ourselves to potential bugs that are otherwise avoided by writing to files directly.
A:
sysctl is a tool for reading and modifying various kernel attributes. It is available in many Unix-like operating systems, including not only Linux, but also OpenBSD and FreeBSD, for example. sysctl is typically available both as a shell command and as a system call.
In Linux, the sysctl mechanism is additionally exposed as part of the procfs virtual filesystem, under /proc/sys.
Note that the sysctl syscall is deprecated in Linux; it is recommended to use /proc/sys instead (either directly or via the sysctl shell command).
References:
Manpage for the sysctl syscall in Linux
Manpage for the sysctl shell command in Linux
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как включить ссылки в TextView?
Всем привет, есть TextView, текст ставится с помощью Html.fromHtml. Проблема в том, что ссылки могут быть как и в HTML тегах, так и просто текстом:
<a href="http://google.com">Google</a>
http://google.com
Включаю ссылки так:
textView.movementMethod = LinkMovementMethod.getInstance()
Ссылки включаются только для первого варианта (в HTML теге). Если использовать Linkify то работает только второй вариантом, если использовать их вместе, то что-то одно.
Как включить ссылки и в HTML и просто текстом?
A:
Html нацелен на обработку тегов и просто url-адреса в тексте не ищет. Но соль в том, что Linkify удаляет все существующие URLSpan'ы, а потом ищет в оставшемся тексте адреса по заданным паттернам.
Варианты навскидку:
обработать текст заранее (обернуть url тегами)
обработать текст после Html.fromHtml спанами самому без Linkify
скопировать спаны из текста, обработанного Html.fromHtml
после обработки Linkify:
TextView tv = findViewById(R.id.tv);
Spanned fromHtml = Html.fromHtml("<a href=\"http://google.com\">Google</a><br>" +
"http://google.com");
SpannableStringBuilder builder = new SpannableStringBuilder(fromHtml);
Linkify.addLinks(builder, Linkify.ALL);
TextUtils.copySpansFrom(fromHtml, 0, fromHtml.length(), URLSpan.class, builder, 0);
tv.setText(builder);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
REST API - design consideration
I've got a question about designing REST API. Consider the following situation: we've got table called banners and table called images. Each banner has got one image and each image belongs to one banner (table images is used to store another images, not only banners, so joining the tables is not the solution).
table Banner table Images
________________________ ______________________
| id | Int | | id | Int |
| title | VARCHAR | | filename | VARCHAR|
|__________|___________| | banner_id | Int |
| article_id| Int |
|___________|________|
I've read some articles about creating REST APIs and according them, I should make this URIs for data retrieving:
1) api/banner/1
2) api/banner/1/image
But I will always need an image with banner, so why is not better to return everything by calling first API route? If I'll do it by this way (two routes), how should I implement the calls from frontend? Should I write two http.get() methods for retrieving banner first and then its associated image? Thanks for answers!
A:
There are a few options for you in this situation:
Offer Both Resources
As you noted, if you offer both resources, you would have to do two GET requests to retrieve all the data you need.
Offer Both Resources, and Embed the Image in the Banner
You can do both - api/banner/1/image can return data about the image, and api/banner/1 can return data about the banner, with the image embedded.
If you use a media type such as HAL it would be considered an 'embedded' resource:
{
"id": 1,
"title": "banner title",
"_embedded": {
"image" : {
"id": 1,
"filename": "some path",
"_links": {
"self": {
"href": "api/banner/1/image"
}
}
}
},
"_links": {
"self": {
"href": "/api/banner/1"
}
}
}
This way you could get all the data you need with a single GET.
Only Offer the Banner Resource
There is no rule that says your database tables have to line up exactly with your API resources.
There's nothing wrong with only offering api/banner/1 and having it return something like:
{
"id": 1,
"title": "banner title",
"imageFileName": "some path"
}
The fact that you happen to store the data fields on separate tables internally in your system is just an implementation detail/
Don't forget Non-GET methods
Although you are currently focussing on the GET method, your resource structure should also take into account the non-GET methods you want to offer, which means you should consider other operations, such as create, update and delete. This will help determine which of the above operations to offer - e.g.
Do you ever create a banner without an image?
If you do, you should offer both resources. But you could still embed the image resource if it exists, to save the second GET request.
If you don't, then there's no problem just offering the banner resource - from the client's perspective, they should never consider the banner without an image
How often do you update the image without updating other properties of the banner?
If the answer is frequently, then it could be helpful to offer the image resource - but again, you could still embed the resource to save the second GET request
Suggestion on your Data Structure
You mention that the image might be used for other types of images, but that a banner could only have one image. If that is the case, I'd suggest reversing the direction of the relationship, e.g.:
table Banner table Images
________________________ ______________________
| id | Int | | id | Int |
| title | VARCHAR | | filename | VARCHAR|
| image_id | Int | |___________|________|
|__________|___________|
Otherwise, how would you handle it if two records in the Image table had the same banner_id?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
two factor authentication for a wifi network?
is it possible to setup two factor authentication for known users of a wifi network? I imagine that this might add security to wifi networks whose keys are stored by an untrusted device or third party smartphone os-maker.
A:
Yes we can apply on Cisco Router(as much as I know) and we have the following options:
OTP using external RADIUS server and RSA tokens
EAP-Chaining using the AnyConnect Agent and Cisco ISE
MAR (machine access restrictions). If the machine had not performed authentication the user will not be authorized
Layer 3 security on the Wireless LAN Controller
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using "e.g." to introduce another clause
I always used e.g. to introduce a non-exhaustive list, as in the following sentence.
He was the school champion of many activities (e.g., chess, badminton, 110m hurdles, and high jump).
Can e.g. be used to introduce a clause?
This can be used by other modules to act accordingly, e.g. field_ui uses it to add operation links to manage fields and displays.
This is what the former CEO's did too, e.g. John Doe did it when he was CEO between 2001 and 2006.
A:
As StoneyB said in his comment:
Yes, it's used exactly like for example. But eg (like for example) is
an adverbial (or adsentential), not a conjunction, so when it
introduces an independent clause it should be preceded by a semicolon.
I always follow it with a comma, but I handwave that in other folks'
writing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
c3js: How to add a vertical line to a vertical bar chart that is not one of the categories of the x-axis?
I have created a histogram of some data, and would like to show a vertical line where the mean of this data is located. I am able to place a line at any of the categories on the bar chart, for example:
The code for doing this is (react-c3js):
<C3Chart
key={foo}
data={{ unload: true,
columns: data.columns,
type: 'bar',
color: (color, d) => someColor
}}
grid={{
x: {
lines: [
{ value: '1332', text: 'mean' },
{ value: d3.mean(dataForHistogram), text: 'median' },
]
},
y: {
lines: [
{ value: 100, text: 'oiweryoqeiuw' },
]
}
}}
axis={{
x: {
unload: true,
show: features ? true : false,
categories,
type: "category",
label: someLabel,
}
}} />
Note that 1332 is not the actual mean - the correct mean is 2092. But this is not a category value, so the line does not display when I use the mean as the value for the line.
How can I place a line representing the mean on such a bar chart?
A:
Someone gave me the following solution, and it works for me. The solution was to change the type of x-axis from category to linear and to specify the x data:
const categories = [1, 2, 3, 4, 5];
const yValues = [10, 8, 6, 3, 7];
const xDataName = 'my-x-data';
const data = {
columns: [
[xDataName, ...categories],
[yData1, ...yValues],
],
};
return (<C3Chart
key={foo}
data={{
x: xDataName,
unload: true,
columns: data.columns,
type: 'bar',
color: (color, d) => someColor
}}
grid={{
lines: {
front: true
},
x: {
lines: [
{ value: d3.mean(yValues), text: 'mean' },
]
}
}}
axis={{
x: {
unload: true,
show: features ? true : false,
categories,
type: "linear",
label: someLabel,
}
}} />)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use variable name to create new variables in PHP?
I'm using Joomla Framework to create component that displays options from a MySQL table.
Because each option has a lot of various parameters they are being set as json arrays in custparams field.
This function extracts these custom parameters from each option based on option id.
JSON data is decoded and written into stdObject:
$_oparams=null;
function _custParamsOpt($pid)
{
$query='SELECT custparams FROM #__mycomponent_options'
.' WHERE id = '.(int)$pid;
$this->_db->setQuery( $query);
$paramdata=$this->_db->loadResult();
if (!empty($paramdata))
{
$custom=json_decode($paramdata);
foreach ($custom as $custom_params)
{
if ($custom_params->pkey=='elemvert') $this->_oparams->elemvert=$custom_params->pvalue;
if ($custom_params->pkey=='elemhor') $this->_oparams->elemhor=$custom_params->pvalue;
if ($custom_params->pkey=='minwidth') $this->_oparams->minwidth=$custom_params->pvalue;
if ($custom_params->pkey=='maxwidth') $this->_oparams->maxwidth=$custom_params->pvalue;
if ($custom_params->pkey=='minheight') $this->_oparams->minheight=$custom_params->pvalue;
if ($custom_params->pkey=='maxheight') $this->_oparams->maxheight=$custom_params->pvalue;
}
return true;
} else {
return false;
}
}
Is it possible to write this data as:
$this->_oparams->$pkey=$custom_params->pvalue;
so I can avoid listing all the parameters?
In the code later I check parameters in this way:
if (!empty($this->_oparams->maxheight)) $htmlout.="\t\t\t\t<input type=\"hidden\" name=\"maxheight".$rowx->id."\" id=\"maxheight".$rowx->id."\" value=\"".$this->_oparams->maxheight."\" />";
A:
I believe this is what you are looking for:
...
foreach ($custom as $custom_params)
$this->_oparams->{$custom_params->pkey} = $custom_params->pvalue;
}
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can this lifting routine be improved, and when is it necessary to swap exercises?
I am focusing mostly on mass. I am 6'4 and weigh about 195 pounds. I'm doing push/pull/legs + rest day, and am trying to increase my weight by about 5lbs every week.
Push
Pushups: 3 sets to failure (currently at 22 per set)
Bench: 5x5 (currently at 135lbs)
Shoulder press: 3x8 (currently at 30lbs)
Tricep pushdown: 3x8 (currently at 160lbs)
Shoulder lateral raises: 3x8 (currently at 20lbs)
Pull
Pullups: 4 sets to failure (currently at 11 per set)
Chinups: 4 sets to failure (currently at 7 per set)
Dumbbell rows: 3x8 (currently at 60lbs)
Lat pulldown: 3x8 (currently at 130lbs)
Bicep curls: 3x8 (currently at 30lbs)
Legs
Squats: 3x8 (currently at 120lbs)
Leg extension: 3x8 (currently at 100lbs)
Leg press: 3x8 (currently at 130lbs)
Please let me know how this program can be improved. I've been at it for a few months (I started legs much more recently though), and I've seen a lot of improvement. Shoulder press, bicep curls, and lateral raises have been harder to increase regularly, but I increase when I can.
Furthermore, when is it necessary to switch up my routine?
A:
You have an alright balance of push to pull exercises, but there are some changes you can make. Big compounds are useful.
Drop the tricep pushdowns and the bicep curls. You're hitting those muscles fine in other push/pull exercises.
Replace chinups (they're extremely similar to pullups) with deadlifts(3x5), and add them to the beginning of pull day. Your workout doesn't really have any posterior chain exercises (lower back->butt->hamstrings), and you'll end up with unbalanced legs.
Replace lat pulldowns with face pulls. They'll balance your front and make sure a bunch of bench pressing doesn't pull your shoulders in and hurt your rotator cuff.
Drop leg press on leg day, move squats to 5x5, and focus on adding weight. They're a good strength foundation, and you can get a lot of mileage out of them by doing them heavy.
Add bridges and abs at 3x15 to leg day. This will round off your posterior chain and core strength is essential to lifting safety. Don't do crunches, they can hurt your back - use an ab wheel (technique!) or leg raises.
Your workout now looks like:
Push
Pushups: 3 sets to failure (currently at 22 per set)
Bench: 5x5 (currently at 135lbs)
Shoulder press: 3x8 (currently at 30lbs)
Shoulder lateral raises: 3x8 (currently at 20lbs)
Pull
Deadlift : 3x5 (start at 95)
Pullups: 4 sets to failure (currently at 11 per set)
Dumbbell rows: 3x8 (currently at 60lbs)
Face pulls: 3x8 (start light)
Legs
Squats: 5x5 (stay at your current weight progression, it's same rep #)
Leg extension: 3x8 (currently at 100lbs)
Glute bridge: 3x8 (no bar to start)
Abs: 3x15 (your pick)
Basically you already have the idea of symmetry in your workout, what's left is to make sure your legs are getting a good portion of the training.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does $\int_0^1 x^n d\alpha(x)$ converge to?
Let $\alpha$ be a monotonically increasing function on $[0,1]$. What does the sequence of Riemann-Stieltjes integrals
\begin{equation*}
\int_0^1 x^n d\alpha(x)
\end{equation*}
converge to as $n \to \infty$?
I know that if $\alpha(x) = x$ then the sequence converges to $0$. More generally, if $\alpha(x)$ is continuous, then the sequence converges to zero. But what about for general monotone functions $\alpha(x)$?
A:
Write this integral (with $0 < \epsilon < 1$) as
$$\int_0^1 x^n \, d\alpha =\int_0^{1-\epsilon}x^n \, d\alpha + \int_{1-\epsilon}^{1}x^n \, d\alpha $$
Considering the first integral on the RHS, we have
$$0 \leqslant \int_0^{1-\epsilon}x^n \, d\alpha \leqslant (1-\epsilon)^n[\alpha(1) - \alpha(0)] \\ \implies \lim_{n \to \infty}\int_0^{1-\epsilon}x^n \, d\alpha = 0 $$
Considering the second integral, we have for all $n > 1/\sqrt{\epsilon}$
$$\int_{1-\epsilon}^{1}x^n \, d\alpha \geqslant \int_{1-1/n^2}^{1}x^n \, d\alpha \geqslant \left(1 - \frac{1}{n^2} \right)^n[\alpha(1) - \alpha(1- 1/n^2)] \\ \implies \liminf_{n \to \infty}\int_{1-\epsilon}^{1}x^n \, d\alpha \geqslant \alpha(1) - \alpha(1-),$$
since $1 - 1/n \leqslant (1- 1/n^2)^n \leqslant 1$ using the Bernoulli inequality, and, hence, $(1-1/n^2)^n \to 1$.
We also have
$$\int_{1-\epsilon}^{1}x^n \, d\alpha \leqslant \alpha(1) - \alpha(1-\epsilon) \leqslant \alpha(1) - \alpha(1-)$$
Thus,
$$ \alpha(1) - \alpha(1-) \leqslant \liminf_{n \to \infty}\int_{1-\epsilon}^{1}x^n \, d\alpha \leqslant \limsup_{n \to \infty}\int_{1-\epsilon}^{1}x^n \, d\alpha \leqslant \alpha(1) - \alpha(1-),$$
and it follows that
$$ \lim_{n \to \infty}\int_{0}^{1}x^n \, d\alpha =\lim_{n \to \infty}\int_{1-\epsilon}^{1}x^n \, d\alpha = \alpha(1) - \alpha(1-)$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
BarChart with ScalingFunctions -> "Log", Fixed axis
I want to make an animated BarChart. In this I want to plot
different tables which range from $10^{-60}$ to $1$.
For example:
{0.1,0.2,10^-3,10^-16,0.01,10^-20}
and the next data set goes to:
{0.11,0.19,10^-2,10^-12,0.0001,10^-10}
However, I can't set the BarChart with ScalingFunctions->"Log" to only
start if a number for the chart is higher than $10^{-12}$.
Does anyone know a way to fix this?
P.S.: I already tried PlotRange->{10^-12,1}. Doesn't work though.
A:
I'm not too sure what you mean, but you seem to want to not draw the bars if they're too short. So - just an idea - you could try drawing the bars yourself:
cef[{{xmin_, xmax_}, {ymin_, ymax_}}, y_, ___] :=
If[y > 10^-12,
Rectangle[{xmin, ymin}, {xmax, ymax}],
Rectangle[{xmin, ymin}, {xmin, ymin}] (* zero height *)]
Manipulate[
BarChart[data[[x]],
ChartLabels -> Placed[N@data[[x]], Top],
ScalingFunctions -> "Log",
ChartElementFunction -> cef],
{x, 1, 2, 1}]
Because the < 10^-12 bars are drawn with zero height (for testing), they show up as labels but can't be seen.
With a better idea of what your current code is like, more might be possible...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to put an HTML form next to a text?
Here is my code:
Topic one: <h:form> <h:commandButton value="+" /> <h:commandButton value="-" />
</h:form>
I want the + and - buttons to be on same line next to the the text Topic one:.
A:
Use a css class like this on your form:
.your-class {
display: inline;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Decorating parse tree using attribute grammar
Given the following attribute grammar for type declarations, I need to be able to produce a parse tree for any given string, for example "A, B : C;", and then decorate the tree.
I can generally do this for simple attribute grammars and when its obvious what the attributes are, but I can not decipher what out_tab and in_tab are. Yes, this is my homework and I am not asking for the solution, I am asking for guidance on what these attributes mean and possible examples to assist me.
decl -> ID decl_tail
decl.t := decl_tail.t
decl_tail.in_tab := insert(decl,in_tab, ID.n, decl_tail.t)
decl.out_tab := decl_tail.out_tab
decl_tail -> , decl
decl_tail.t := decl.t
decl.in_tab := decl_tail.in_tab
decl_tail.out_tab := decl.out_tab
decl_tail -> : ID ;
decl_tail.t := ID.n
decl_tail.out_tab := decl_tail.in_tab
A:
Several years after, I hope you finished well your home work :)
about your exercise:
decl.t and decl_tail.t are synthetized atributes that copy the Type name (ID.n) and pass it for each parent production in the parsing tree
when a production decl -> ID decl_tail is reached, the in_tab attributte keeps a kind of list of relationship between identifiers and types (it is not clear the type of in_tab but we can assume a list of tuples (identifier; type)). This attribute is inherited, so the list will start to be constructed in the top most production (leftmost identifier), and continue constructing it from left to right and finish it in the rightmost identifier.
Then the list is finished to be constructed when decl_tail -> : ID; is reached so a synthesised attribute (out_tab) is used to synthesise the result again to the starting symbol.
this drawing was the best I could do for drawing the decorated tree and graph dependence:
Blue arrows are the synthetizing of the t attribute, the green arrows are how the in list is constructed and the red arrows are how the result is synthesized to the initial symbol
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# Unmanaged application crash when using Enterprise Library
I have a C# library DLL which is loaded from an unmanaged process. So far everything is good. Now I wanted to incorporate the Enterprise Library 5.0 with its logging capabilities. I added these references:
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.EnterpriseLibrary.Logging.dll
...and all the using statements required.
Here is an excerpt from the class:
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity.Configuration;
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode,Pack=2)]
unsafe public static class DLLDispatch
{
private static IConfigurationSourceBuilder LoggingBuilder = new ConfigurationSourceBuilder();
...
}
The problem is that when this field is defined the unmanaged processes crashes. If it is commented out, this crash does not happen. And here is the windows application log for this crash:
**Sig[0].Name=Application Name
Sig[0].Value=terminal64.exe
Sig[1].Name=Application Version
Sig[1].Value=5.0.0.507
Sig[2].Name=Application Timestamp
Sig[2].Value=003f5e00
Sig[3].Name=Fault Module Name
Sig[3].Value=clr.dll
Sig[4].Name=Fault Module Version
Sig[4].Value=4.0.30319.237
Sig[5].Name=Fault Module Timestamp
Sig[5].Value=4dd2333e
Sig[6].Name=Exception Code
Sig[6].Value=c00000fd
Sig[7].Name=Exception Offset
Sig[7].Value=000000000007382a**
I searched the web for the exception code c00000fd and found it to be a stackoverflow :-) exception.
I played around a bit and this crash occures everytime there is an instance involved from the enterprise library. If nothing is used of that library then there is no crash. What is going on here? Is it becasue the class is in unsafe context or what else can it be?
Thanks in advance.
A:
I found the solution to this problem. One has to put a app-config file in the unmanaged application folder with this content:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="Unmanaged application startup folder" />
</assemblyBinding>
</runtime>
</configuration>
With this information the CLR can bind assemblies and searches in the correct folder. It was not clear to me that a config file is also useful for unmanaged applications.
Thanks, Juergen
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to CoffeeScript AngularJS module to load with ng-app in JSFiddle
I'm playing around with Coffeescript and AngularJS, trying to use the new "controller as" syntax. Despite varied attempts and searching Google, I can't get it to work - the controller reference in my html doesn't find the Coffeescript class for the controller.
I suspect I am doing something wrong or just misunderstanding things but if anyone has a working example, it would be very helpful.
Here's a little jsfiddle showing what I am trying to do: http://jsfiddle.net/G2r4p/ (the controller in this example is just an empty dummy controller so I can test the syntax).
When I run this example in my browser I get:
Error: [ng:areq] Argument 'AppController' is not a function, got undefined
at hasOwnPropertyFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:60:12)
at assertArg (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:1187:11)
at assertArgFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:1197:3)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:5547:9)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:5060:34
at forEach (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:203:20)
at nodeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:5047:11)
at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:4607:15)
at compositeLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:4610:13)
at publicLinkFn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.js:4516:30)
Thanks
A:
JS Fiddle is the culprit. Your syntax is correct and works fine as is when I tried it in JS Bin. It looks like JS Fiddle is processing something out of order, compared to JS Bin, which doesn't suffer from this issue.
Check out the working JS Bin example: http://jsbin.com/akABEjI/1/edit
You might also be interested in my blog post that takes the AngularJS Todo app and converts it to CoffeeScript: "Writing AngularJS controllers with CoffeeScript classes." Ultimately your sample is similar to what I end up with in my final example.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add pagination in photo gallery?
My HTML Code is like this :
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
My Javascript Code is like this :
htmlData = '';
htmlData = 'Photos<a href="#" id="hotel_photo" data-hotel-code="nases">(Click to View)</a><br><br>';
htmlData += '<div class="imageHotel"></div>';
$('#myModal').find('.modal-body').html(htmlData);
$(".imageHotel").hide();
$(document).on("click", "#hotel_photo", function(event){
$(".imageHotel").toggle();
event.preventDefault();
htmlData += '<div id="gallery_hotel">';
htmlData = '<img id="largeImage" src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_01_large.jpg" />';
htmlData += '</div>';
htmlData += '<div id="thumbs_hotel">';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_01_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_02_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_03_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_04_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_05_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_01_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_02_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_03_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_04_thumb.jpg" />';
htmlData += '<img src="http://www.workshop.rs/demo/gallery-in-4-lines/images/image_05_thumb.jpg" />';
htmlData += '</div>';
$('.imageHotel').html(htmlData);
// bind the click event
$('#thumbs_hotel').off().on('click', 'img', function () {
console.log($(this).attr('src'));
$('#largeImage').attr('src',$(this).attr('src').replace('thumb','large'));
});
});
Demo is like this : https://jsfiddle.net/oscar11/10td0yww/5/
I want add pagination in my photo gallery. So the images shown only 5 pictures per page. for example, there are 10 pictures, then there will be 2 page
Any solution to solve my problem?
Thank you very much
A:
I have used owl carousel for this.
$("#thumbs_hotel").owlCarousel({
items: 5, // number of images to be moved
dots: true
});
I have prevented swipe/touch/drag event for owl carousel by adding following code:
$(".item").on("touchstart mousedown", function(e) {
// Prevent carousel swipe
e.stopPropagation();
})
Also I have added css for navigation dots. You can change it according to requirement.
.owl-carousel .item {
margin: 3px;
}
.owl-dot {
display: inline-block;
}
.owl-dots span {
background: none repeat scroll 0 0 #869791;
border-radius: 20px;
display: block;
height: 12px;
margin: 5px 7px;
opacity: 0.5;
width: 12px;
}
Please refer the fiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Replace characters and keep only one of these characters
Can someone help me here? I dont understand where's the problem...
I need check if a String have more than 1 char like 'a', if so i need replace all 'a' for a empty space, but i still want only one 'a'.
String text = "aaaasomethingsomethingaaaa";
for (char c: text.toCharArray()) {
if (c == 'a') {
count_A++;//8
if (count_A > 1) {//yes
//app crash at this point
do {
text.replace("a", "");
} while (count_A != 1);
}
}
}
the application stops working when it enters the while loop. Any suggestion? Thank you very much!
A:
If you want to replace every a in the string except for the last one then you may try the following regex option:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", " ");
somethingsomething a
Demo
Edit:
If you really want to remove every a except for the last one, then use this:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", "");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Generating different randoms valid for a day on different independent devices?
Let me describe the system. There are several mobile devices, each independent from each other, and they are generating content for the same record id.
I want to avoid generating the same content for the same record on different devices, for this I though I would use a random and make it so too cluster the content pool based on these randoms.
Suppose you have choices from 1 to 100.
Day 1
Device#1 will choose for the record#33 between 1-10
Device#2 will choose for the record#33 between 40-50
Device#3 will choose for the record#33 between 50-60
Device#1 will choose for the record#55 between 40-50
Device#2 will choose for the record#55 between 1-10
Device#3 will choose for the record#55 between 10-20
Device#1 will choose for the record#11 between 1-10
Device#2 will choose for the record#22 between 1-10
Device#3 will choose for the record#99 between 1-10
Day 2
Device#1 will choose for the record#33 between 90-100
Device#2 will choose for the record#33 between 1-10
Device#3 will choose for the record#33 between 50-60
They don't have access to a central server.
Data available for each of them:
IMEI (unique per mobile)
Date of today (same on all devices)
Record id (same on all devices)
What do you think, how is it possible?
ps. tags can be edited
A:
I agree with AakashM and Frustrated. First can you guarantee that the number of devices is greater than the range of generated data? In fact to be "Random" you really need to have twice the generated content as devices, otherwise at least one device will have to "randomly choose" between one choice. That stated since the IMEI is the only unique data based on the device you will have to use that in your algorithm. The other problem (I suspect) is that the device IDs are not necessarily evenly distributed so any potential mapping of a device ID to a data block would potentially lead to overlap (unless you have a very large range of data to select from) or the values generated would not be evenly distributed across the pool of devices.
That said here is a rough algorithm:
Create a mapping of the IMEI to an integer (i.e. some kind of hash)
Rotate that integer based on the date and the size of possible values generated in step
Map the number resultant from 2 to a range of data values based on the ratio of IMEIs to value range created by step #1.
Use the standard random number to select something from that range
A simple example using the IMEI as a single byte and a data range of 0->2559:
Mapping is direct based on IMEI, so base = IMEI
Date translation is based on #of days since epoch. For this example say 700 then base = (9(original base: Mapped IMEI)+700(# of days)) % 255(range of mapped IMEI value) = 199
Data range is 10 times mapped value range, so each block may use 10 values, resultant data range from 2 becomes 1990 ->1999 (inclusive).
Select a standard random value in the block data range (i.e. 4, as chosen by fair dice roll) value = 1990+4=1994.
Finally if you want the ranges to differ based on the record you could use that as a second offset as was done in step #2.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Google Drive API Manifest Permissions
this isn't really a big problem. I've got an Android App that stores user's passwords on a SQLite Database. So last week I launched an update that allows the user to export those passwords to their Google Drive. To do this, I've used the Google Drive Android API. I didn't add any special permission to the Application Manifest (AndroidManifest.xml) and it works fine (tested on KitKat4.4). But one of my friends told me that it might not work on Android 6.0+, because I should always ask for permissions. But I checked some samples and none of them had those permissions on the Manifest. Do you guys think it's necessary to add permissions? Perhaps INTERNET or GET_ACCOUNTS?
A:
If you are using the Google Drive Android API you don't need INTERNET or GET_ACCOUNTS permissions.
The API automatically handles previously complex tasks such as offline access and syncing files. This allows you to read and write files as if Drive were a local file system.
Check the official Quickstart and the demos sample on GitHub. None of them is having special permissions in the AndroidManifest.xml.
BUT if you are using the Google Drive REST API for Android then you need INTERNET permission for sure.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Parse: Facebook login not creating new PFUser
I've been trying to integrate Facebook login and Parse, so that a new PFUser is created upon logging in. I have created a Facebook login button, and when I press it the standard Facebook login/asking for permissions screen appears. When I accept the login I am redirected back to the initial screen, and the log shows that the user has cancelled the Facebook login. When I check my data on the Parse website, there are no PFUsers.
As far as I can tell I have followed the exact instructions laid out by Parse (https://parse.com/docs/ios/guide#users) and Facebook.(https://developers.facebook.com/docs/ios/getting-started). I am using XCode 6.3.2. I have added integrated Parse (ParseFacebookUtilsV4 v1.7 & ParseUI v1.1) and Facebook (FBSDKCoreKit v4.2 &FBSDKLoginKit v4.2) in Cocoapods, and have linked the following libraries:
libsqlite3.dylib
libz.dylib
Accounts.framework
AudioToolbox.framework
CFNetwork.framework
CoreGraphics.framework
CoreLocation.framework
CoreLocation.framework
MobileCoreService.framework
QuartzCore.framework
Security.framework
Social.framework
StoreKit.framework
SystemConfiguration.framework
libPods-xxx.a (being the name of my project)
My code is as follows:
//Appdelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("xxxxxxxx",
clientKey: "xxxxxxxxxx")
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
func application( application: UIApplication,
openURL url: NSURL,
sourceApplication: String,
annotation: AnyObject?) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application,
openURL: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
//Facebook analytics
func applicationDidBecomeActive(application: UIApplication!) {
FBSDKAppEvents.activateApp()
}
And the View controller in which the login in placed:
//OnboardingRootViewController.swift
import Foundation
import UIKit
class OnboardingRootViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func fbLoginClick(sender: AnyObject) {
var permissions = ["public_profile", "email", "user_likes"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
println("User signed up and logged in through Facebook!")
} else {
println("User logged in through Facebook!")
}
} else {
println("Uh oh. The user cancelled the Facebook login.")
}
}
}
}
So, can anyone be of any help? Again, the Facebook login at least appears to work, when the IBAction fbLoginClick is invoked, but the "Uh oh. The user cancelled the Facebook login." message is shown in the log, and no new PFUser is created in Parse. I've seen multiple other similar questions, but none with any real answers so I'm sure an answer to this question would be appreciated by many, especially as this is using the exact code shown in the login tutorials created by Parse and Facebook!
Edit: If no one is able to help, I'd still appreciate help with the following: I've been told that I should check which error message is returned by loginInBackgroundWithReadPermissions, unfortunately without further explanation. Was this person simply referring to the "Uh oh. The user cancelled the Facebook login." message, or is it possible to retrieve any information through the NSError?
Edit #2:
I added the following line of code to see what the NSError returns:
println("write failure: (error?.localizedDescription)")
And get the following message in the log:
Uh oh. The user cancelled the Facebook login.
write failure: nil
So I guess that didn't really get me any further...
Edit #3: Like seriously, I'll paypal 10$ to anyone that can help me
A:
This code will work if you set up the frameworks correctly and follow the steps of Parse's Facebook setup guide (https://parse.com/docs/ios/guide#users-facebook-users). Make sure your syntax is the same as the functions I have and try getting rid of any unnecessary code that isn't included below.
AppDelegate.swift
import UIKit
import CoreData
import Parse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//X's replace my actual Parse information
Parse.setApplicationId("XXXXXXXXXXXXXXXXXXXXXX", clientKey: "XXXXXXXXXXXXXXXXXXXXXX")
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
/*
func application(application: UIApplication, url: NSURL, sourceApplication: NSString, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(
application,
openURL: url,
sourceApplication: sourceApplication as String,
annotation: annotation)
}*/
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject?) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application,
openURL: url,
sourceApplication: sourceApplication,
annotation: annotation)
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
let permissions = [ "email","user_birthday", "public_profile", "user_friends"]
@IBAction func loginButtonPressed(sender: AnyObject) {
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
println("User signed up and logged in through Facebook!")
} else {
println("User logged in through Facebook!")
}
} else {
println("Uh oh. The user cancelled the Facebook login.")
}
}
}
}
The @IBAction is for a simple UIButton I put in the center of the blank viewcontroller in my Main.storyboard
Objective-C Bridging Header:
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>
#import <Parse/Parse.h>
Hope this solves your problem!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
python: library for generalized suffix trees
I need python library that can construct suffix trees and especially generalised suffix trees. Could you suggest me some libraries. Thanks.
A:
See the following libraries.
suffixtree
Python-Suffix-Tree
SuffixTree
SuffixTree (same name different project, supports generalized suffix trees)
pysuffix (This is suffix arrays)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there way to formalize the idea that a category can be "cocomplete from the inside"?
Let $\mathrm{KSet}$ denote the category of all countable sets, including the finite ones. Then $\mathrm{KSet}$ is finitely complete. Furthermore, $\mathrm{KSet}$ admits all countable colimits, or, less formally, it is "cocomplete from the inside." Is there way to formalize this idea (that a category can be "cocomplete from the inside") using structuralist language?
A:
Let $\mathcal{S}$ be a category with pullbacks. An $\mathcal{S}$-indexed category $\mathbb{C}$ is a pseudofunctor $\mathcal{S}^\mathrm{op} \to \mathfrak{CAT}$, and $\mathbb{C}$ is said to be $\mathcal{S}$-cocomplete if the following conditions are satisfied:
For each object $X$ in $\mathcal{S}$, the category $\mathcal{C}^X = \mathbb{C} (X)$ has finite colimits.
For each morphism $f : X \to Y$ in $\mathcal{S}$, the functor $f^* : \mathcal{C}^Y \to \mathcal{C}^X$ preserves finite colimits.
For each morphism $f : X \to Y$ in $\mathcal{S}$, the functor $f^* : \mathcal{C}^Y \to \mathcal{C}^X$ has a left adjoint, say $\Sigma_f : \mathcal{C}^X \to \mathcal{C}^Y$.
The functors $\Sigma_f : \mathcal{C}^X \to \mathcal{C}^Y$ satisfy the Beck–Chevalley condition with respect to pullback squares in $\mathcal{S}$.
Observe that there is an obvious $\mathcal{S}$-indexed category $\mathbb{S}$ defined by $X \mapsto \mathcal{S}_{/ X}$. $\mathbb{S}$ automatically satisfies the last two conditions, and $\mathbb{S}$ is $\mathcal{S}$-cocomplete precisely when it is an extensive category with (pullbacks and) pullback-stable coequalisers. In particular, the category of countable sets is such a category.
We can dualise the above to obtain the notion of an $\mathcal{S}$-complete $\mathcal{S}$-indexed category. $\mathbb{S}$ is $\mathcal{S}$-complete if and only if $\mathcal{S}$ is a locally cartesian closed category; and if $\mathcal{S}$ also has finite colimits, then it is also $\mathcal{S}$-cocomplete.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jquery text reveal with prompt text change
I'm creating a FAQ page where questions are listed but the explanations are hidden - click on the question to show the explanations. Pretty straight forward stuff.
I want to add a little text prompt (in a <span>) next to the question that says "more" when the explanation is hidden, and "less" when the explanation is display. Can't figure out how to do this.
Tried using some If/else statements, but couldn't get them working. Is there an easier way to do this?
Here's my current script, sans the "more/less" text change:
$(document).ready(function() {
$('.faqtitle').click(function () {
$(this).next('p').animate({
height: "toggle",
opacity: "toggle"
}, 400);
});
});
... and here's the fiddle displaying generally what I'm working with:
http://jsfiddle.net/V5LDQ/
Thanks!
A:
How about this:
$(document).ready(function() {
$('.faqtitle').click(function () {
$(this).next('p').animate({
height: "toggle",
opacity: "toggle"
}, 400);
var expand = $(this).find('span');
if (expand.html() == "more") {
expand.html("less");
} else {
expand.html("more");
}
});
});
Working fiddle here.
Edit:
Here is a nice simple way to incorporate some css fade for that text change. This is using the jQuery fadeIn and fadeOut methods. Additional documentation can be found here.
var expand = $(this).find('span');
expand.fadeOut(500, function() {
if (expand.html() == "more") {
expand.html("less");
} else {
expand.html("more");
}
expand.fadeIn(500);
});
Working fiddle with transitions here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clone content JQUERY
I found some code, I modified the same but now I want to clone the content that i type in the input from the original div in cloned elements
<button type="button" id="addmore" >Add More</button>
<button type="button" id="rmvbtn" >Remove</button>
<div class="dynamic-wrapper">
<div class="datagrid">
<table>
<thead>
<tr>
<th>Item</th>
<th>UM</th>
</tr>
</thead>
<tbody>
<tr>
<td><p><strong>1</strong></p>
</td>
<td>
<div class="dynamic-row">
<input type="text" name="chpob1" id="chpob1" />
</div>
</td>
</tr>
</tbody>
</table></div></div>
The Jquery is here !
http://jsfiddle.net/MetCastle/6uhQt/
Hope you can help me, thanks
A:
Something like that?
$(document).ready(function() {
var increment = 2;//First clone line number
$('#addmore').on('click', function(){
var original = $('.dynamic-row:eq( 0 )').closest('tr');
var cloneDiv = original.clone();
//Increment line number
$('strong', cloneDiv).html(increment++);
original.closest('table').append(cloneDiv);
});
$('#rmvbtn').on('click', function(){
if(increment > 2){
$('.dynamic-row:last').closest('tr').remove();
//decrease line number
increment--;
}
});
});
JSFIDDLE HERE
|
{
"pile_set_name": "StackExchange"
}
|
Q:
¿Como ejecutar la acción del botón BACK con cualquier otro botón en Android?
¿Cómo puedo realizar la misma acción del botón back, pero hacerlo con cualquier otro botón de la interfaz? por ejemplo, digamos que tengo una actividad y desde ahí entro a otra actividad que se queda en segundo plano, al momento de presionar el botón de back me regresa a la actividad anterior, pero yo quiero hacer eso sin presionar el botón back, quiero que eso lo haga un botón el cual yo hice en la aplicación.
A:
En caso de que quieras realizar la acción en un activity, ya tienes tu función de onBackPressed presente en tu código. Ahora es momento de pasarla a otro botón. Asi que hacemos lo siguiente:
Button MyOnBackButton = (Button) mMainView.findViewById(R.id.myid);
MyOnBackButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
//Añade más funcionalidades
}
});
En caso de que quisieses añadir alguna funcionalidad extra al método, deberías realizar lo siguiente:
Haz un @Override al metodo de onBackPressed() en tu Activity de la siguiente manera:
@Override
public void onBackPressed()
{
// Añade más funciones si fuese necesario
super.onBackPressed(); // Invoca al método
}
Finalmente, en caso de que quieras realizar esta acción desde un Fragment tendrás que instanciar tu contexto(activity) y llamar el método desde ahí. Siendo algo como esto:
mActivity.onBackPressed();
Ya esta! Copia este código a tu app y todo debería funcionar correctamente.
Un saludo!
A:
llama al método de onBackPressed(); :)
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.