Q:

Format is not working in an old SQL Server version

I am using format in a stored procedure. My problem is that on the server the SQL Server version is old, and format() does not work.
My use:
FORMAT([Data], 'dd.MM.yyyy')

where data is: 2008-10-31 00:00:00.000
How can I use convert() to obtain the same result?

A:

That is the format mysteriously called "104".  You can use:
select convert(varchar(10), data, 104)

The mysteries of the format codes are explained in the documentation.
You can use this in any version of SQL Server.  format() is much saner but only available since SQL Server 2012.


Q:

how to sort a list of lists of items bases on the total sum of some item's attrinutes in LINQ

The problems is I have a class A which has an attribute Count of int. Then there is B which is a List of Lists of A(List<List<A>>). Now I want to sort B based on the sum of Count ranging over all elements of A in each sublist in B. How should I write this in linq.
B.OrderBy(element => (how can I sum the Count for each A here)).ToList()

A:

Try using the following:
B.OrderBy(element => element.Sum(a => a.Count)).ToList();

What's happening here is that for each sublist List<A> of B, a sum of the Count attribute of each A object is being computed. B is then ordered by that sum.


Q:

Распарсить текстовый файл

Есть текстовый файл куда записываются логи, его строки имеют вид
INFO  10-04 22:09:10 DataLayer              11         Log                            - userId = 1050.
Нужно каким-то образом разбить эти строки на элементы стрингового массива, чтобы каждый элемент этого массива содержал нужную часть данных. И выглядел примерно так:
["Info"]["10-04 22:09:10"]["DataLayer"]["11"]["Log"]["- userId = 1050."] где [] - это каждый элемент массива, попробовал через Split(" ") - выдало 61 элемент, с кучей элементов содержащих просто пробелы. А мне нужно именно выделить слова, все усложняется тем, что в строке много пробелов, и разбивать по пробелам не правильно, так как есть обычные фразы, где пробел идет не в качестве разделителя столбиков, а как просто речевой пробел. Как это можно решить ?

A:

У метода String.Split есть несколько перегрузок. В частности, кроме сепаратора, он принимает количество возвращаемых строк и опцию, исключающую пустые строки.
string text = @"INFO  10-04 22:09:10 DataLayer              11         Log                            - userId = 1050.";
var result = text.Split(new char[] { ' ' }, 7, StringSplitOptions.RemoveEmptyEntries);

Этот код даст почти то, что вам нужно. Только дата и время окажутся в разных элементах массива. Полагаю, это не станет проблемой для их использования.


Q:

.htaccess issue, existing .php files and search.php

I'm new to playing with .htaccess for nicely formatted urls and I'm just not sure I'm doing it right.
My current .htaccess file looks like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^search/(.*) search.php?query=$1 [L]
RewriteRule !\.(gif|jpg|ico|css|js|txt|xml|png|swf)$ index.php

What I want is for mysite.com/home/56/page-title to go to index.php where I filter out the number and load the correct index page, which works fine.
Before that, I want to check if the url is pointing at search.php, and if so redirect to mysite.com/search/the-search-term, this also works fine.
What isn't working is if I try to visit a specific .php file say mysite.com/control_panel.php - it just takes me to index.php, but I thought that the following line stopped that from happening?
RewriteCond %{REQUEST_FILENAME} !-f

If someone could explain it to me that would be great :)
Thanks!

A:

1. Order of rules matters
2. RewriteCond directives will only be applied to the ONE RewriteRule that follows it. If you need to apply the same conditions to multiple rules you have to write them multiple times or change the rewrite processing logic (multiple approaches available).
Try this one:
RewriteEngine On

RewriteRule ^search/(.*) search.php?query=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.(gif|jpg|ico|css|js|txt|xml|png|swf)$ index.php [L]


Q:

MediaCodec decode time calculation

What would be the best way to calculate the decode time of a frame decoded by mediacodec? the execution time of the code below is clearly not the correct time. Is there any way to know how long each frame/frames took to decode?
Thanks.
startTime...

dequeueInputBuffer();

getInputBuffer();

//   copy frame to input buffer

queueInputBuffer();

dequeueOutputBuffer();

releaseOutputBuffer();

stopTime...

exectime = startTime - StopTime

A:

It's difficult to get a meaningful measurement of the time required to decode a single frame, because you'll be measuring latency as well as throughput.  Data has to be passed from the app to the mediaserver process, into the driver, decoded, and then the decoded data has to make the same journey in reverse.  There can be additional pipelining in the driver itself.
You can get a reasonable approximation by decoding a few hundred frames and then dividing the total time by the number of frames.
What is it you're trying to accomplish?


Q:

setuptools does not distribute my data files

I have the following in setup.py:
from setuptools import setup
# ...
setup(
    name='xml-boiler',
    version='0.0.1',
    url='https://github.com/vporton/xml-boiler',
    license='AGPLv3',
    author='Victor Porton',
    author_email='porton@narod.ru',
    description='Automatically transform between XML namespaces',

    packages=find_packages(),
    package_data={'': ['*.ttl', '*.xml']},
    scripts=['bin/boiler'],
    data_files = [
        ('/etc/xmlboiler', ['etc/config-cli.ttl'])
    ],
    test_suite="xmlboiler.tests",

    cmdclass={'build_py': MyBuild},
)

But after I run python setup.py build, the build directory does not contain any *.xml or *.ttl files.
What is my error?
I also want to distribute all files from xmlboiler/core/data/assets/ and
xmlboiler/core/data/assets/.

I don't understand how it works:
package_data={'': ['*/.xml', '*/.ttl', '*/.net', 'data/assets/*', 'data/scripts/*.xslt', 'xmlboiler/doc/*.html', 'xmlboiler/doc/*.css']},

included xmlboiler/core/data/scripts/section.xslt but not xmlboiler/tests/core/data/xml/simple.xml. Why?!

A:

package_data is a mapping of package names to files or file globs. This means that
package_data = {'', ['*.xml', '*.ttl']}

will include every file ending with .xml or .ttl located in any package directory, for example xmlboiler/file.xml, xmlboiler/core/file.ttl etc. It will, however, not include file xmlboiler/core/data/interpreters.ttl because it is located in data which is not a package dir (not containing an __init__.py file). To include that, you should use the correct file path:
package_data = {'xmlboiler.core', ['data/interpreters.ttl']}

To include every .ttl file under xmlboiler/core/data:
package_data = {'xmlboiler.core', ['data/*.ttl', 'data/**/*.ttl']}

This will include every .ttl file in data directory (glob data/*.ttl) and every .ttl file in every subdirectory of data (glob data/**/*.ttl).
To include every .ttl and .xml file in every package:
package_data = {'', ['*.xml', '**/*.xml', '*.ttl', '**/*.ttl']}

I also want to distribute all files from xmlboiler/core/data/assets/

Same approach for data/assets, but omit the file extension in globs:
package_data={
    'xmlboiler.core': ['data/assets/*', 'data/assets/**/*'],
}


Q:

Keyboard input and score. Python turtle

I have found a "flappy game" project and I am modifying it to my liking.
I would like to know how I can control the definition "tap" with the keyboard and not with the mouse (I have tried the online code "onkey" and it did not work) and I would like to know if I can add a score.
Next I attach the code that I have in possession at the moment and I would appreciate some feedback.
from random import *
from turtle import *
from freegames import vector

bird = vector(0, 0)
balls = []

def tap(x, y):
    "Move bird up in response to screen tap."
    up = vector(0, 30)
    bird.move(up)

def inside(point):
    "Return True if point on screen."
    return -200 < point.x < 200 and -200 < point.y < 200

def draw(alive):
    "Draw screen objects."
    clear()

    goto(bird.x, bird.y)

    if alive:
        dot(10, 'green')
    else:
        dot(10, 'red')

    for ball in balls:
        goto(ball.x, ball.y)
        dot(20, 'black')

    update()

def move():
    "Update object positions."
    bird.y -= 5

    for ball in balls:
        ball.x -= 3

    if randrange(10) == 0:
        y = randrange(-199, 199)
        ball = vector(199, y)
        balls.append(ball)

    while len(balls) > 0 and not inside(balls[0]):
        balls.pop(0)

    if not inside(bird):
        draw(False)
        return

    for ball in balls:
        if abs(ball - bird) < 15:
            draw(False)
            return

    draw(True)
    ontimer(move, 50)

setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()

I've tried all kinds of functions and none has worked.

A:

I would like to know how I can control the definition "tap" with the
  keyboard and not with the mouse

That should be as simple as replacing:
onscreenclick(tap)

with
onkey(tap, "Up")
listen()

and dropping the x and y arguments to tap().  I've reworked your code below to make this change as well as eliminate:
from freegames import vector

and make it run just with what's available in turtle.  I also changed the logic of keeping vectors and having the default turtle draw dots in their locations to instead making the balls and bird all turtles and just moving them as needed.  Since turtles aren't garbage collected normally, I keep a list of balls that have gone off screen to reuse again:
from random import randrange
from turtle import Turtle, Screen

BIRD_RADIUS = 10
BALL_RADIUS = 20
CURSOR_SIZE = 20

WINDOW_WIDTH, WINDOW_HEIGHT = 420, 420
GALLERY_WIDTH, GALLERY_HEIGHT = WINDOW_WIDTH - BALL_RADIUS, WINDOW_HEIGHT - BIRD_RADIUS

def click():
    "Move bird up in response to screen key click."

    bird.forward(min(BIRD_RADIUS * 3, WINDOW_HEIGHT/2 - bird.ycor()))  # flying higher

def is_ball_inside(turtle):
    "Return True if point on screen."

    x = turtle.xcor()

    return -GALLERY_WIDTH/2 < x

def is_bird_inside(turtle):
    "Return True if point on screen."

    y = turtle.ycor()

    return -GALLERY_HEIGHT/2 < y < GALLERY_HEIGHT/2

def draw(is_alive):
    "Draw screen objects."

    if not is_alive:
        bird.color('red')

    screen.update()

def move():
    "Update object positions."

    if not is_bird_inside(bird):
        draw(False)  # flew or fell out of gallery
        return

    bird.backward(BIRD_RADIUS/2)  # falling to earth

    for ball in balls:
        ball.forward(3)

    for ball in balls:
        if ball.distance(bird) < (BIRD_RADIUS + BALL_RADIUS) / 2:
            draw(False)
            return

    while balls and not is_ball_inside(balls[0]):
        ball = balls.pop(0)
        ball.hideturtle()

        spare_balls.append(ball)  # reduce, reuse, recycle

    if randrange(10) == 0:
        ball = spare_balls.pop() if spare_balls else Turtle("circle", visible=False)
        ball.shapesize(BALL_RADIUS / CURSOR_SIZE)
        ball.setheading(180)
        ball.penup()
        ball.goto(GALLERY_WIDTH/2, randrange(BALL_RADIUS - GALLERY_HEIGHT/2, GALLERY_HEIGHT/2 - BALL_RADIUS))
        ball.showturtle()

        balls.append(ball)

    draw(True)

    screen.ontimer(move, 50)

screen = Screen()
screen.setup(WINDOW_WIDTH, WINDOW_HEIGHT + 10)  # little bit added for title bar

bird = Turtle("circle", visible=False)
bird.shapesize(BIRD_RADIUS / CURSOR_SIZE)
bird.color("green")
bird.setheading(90)
bird.penup()
bird.showturtle()

balls = []
spare_balls = []

screen.tracer(False)

screen.onkey(click, "Up")
screen.listen()

move()

screen.mainloop()

To make the turtle window the keyboard listener, you need to touch it with the mouse, to make it active, before hitting the up arrow key.
Before adding the current score to the window, you need to define how one scores.  (Is it the number of ball successfully dodged?)  Here I would use an additional, invisible turtle stationed in a fixed position that just does undo() and write() to update the scrore.


Q:

entire  element that contains  and  as a clickable link

[SOLVED] The answer: finally noticed that  closes before the  tags (check initial html code in the question), and that was the cause of the problem! Thank you all for your help!! This happens when you are tired and try to change someone else's code :) – dev101

I have searched, I have tried, but this one is giving me a headache. I know how to make a regular li element clickable as a block hyperlink, but when I put a  tag inside li, only the portion around  inside the ** div ** appears as a link, not the entire li wrapper. Can you help?
html code

link_title (some text)

after much trial and error the only thing that was acceptable from a design point of view is just a regular hover highlight (no link functionality) like this:
css code
div.category ol li,div.category ul li{
    display:inline-block;
    height: 100%;
    width: 100%;
}
div.category ol li:hover,div.category ul li:hover{
    display:inline-block;
    height: 100%;
    width: 100%;
    background-color:#EEE;
}

No matter what I try,  elements are always breaking in new row or hags somewhere, and only part behind  is clickable inside wrapper div (or ol/ul element). Any idea?
Thanks
dev101

edited code to remove div.category but still doesn't work:
.category ul,.category ol{
    list-style: none;
    border: none;
    margin: 0px;
}
.category ul li,.category ol li{
    display:inline-block;
    height: 100%;
    width: 100%;
}
.category ul li:hover,.category ol li:hover{
    background-color:#EEE;
}
.category ul li a,.category ul li a:visited,.category ol li a,.category ol li a:visited{
    display:block;
    height: 100%;
    width: 100%;
}
/* tried to left/right align span - still breaks into new non-clickable line */
.category span{
float:left;
}

A:

I am somewhat confused on what you really want here...
I think I know what you are trying to get at. However, your HTML doesn't match the CSS. Where is the div with the class category?

I am assuming what you really want is to put the span INSIDE the anchor tag, that way it will be a part of the link. You can still manipulate the appearance of the span itself if you want since it is its own element. If you DON'T want the span inside the link, then you will have to remove the span from being inline with the link, with position absolute most likely. Otherwise the span will block the anchor tag.
If you want the entire LI to be clickable you can put padding on the anchor tag that will make it cover the dimensions of the li element. It also depends on where you want the text for the link to be positions, of course. So, let's say if your li element is 200x200, you want the text from the anchor tag to be on the top left; put padding like this...

a.category {
    padding: 0 100% 100% 0;
// percentage of 100% to cover the entire area to the right and to the bottom
}

Alternatively you can use JS to make the LI itself the link w/o use of anchor tag in the html, but this is probably not as efficient as just using HTML and CSS.

Also, it is redundant in most cases to repeat attributes that are unchanged between pseudo-states. If the width and/or height does not change from the default state to the hover state, it's not necessary to put them in the hover state.


Q:

How can I make rbenv install certain gems automatically?

I always want bundler and gem-ctags to be installed in any Ruby I have installed.  Is there a way to make rbenv / ruby-build install them automatically?
RVM has @global gemsets; is there an equivalent in rbenv?

A:

Use rbenv Plugins
By default, rbenv doesn't use gemsets. People who love rbenv probably just hack their GEM_PATH and GEM_HOME when they want different gems, but there are also some plugins that automate some of this behavior. Two that I know of are:

rbenv-vars by Sam Stephenson (the author of rbenv)
rbenv-gemset by Jamis Buck

Use Bundler's --path Flag
Of course, you can also just use bundler with a --path flag to install bundled gems to a unique directory instead of using gemsets. The bundle-install(1) docs say:

--path=<path>
The location to install the gems in the bundle to. This defaults to the gem home,
  which is the location that gem install installs gems to. This means that, by
  default, gems installed without a --path setting will show up in gem list. This
  setting is a remembered option.

Consider the "Batteries-Included" RVM Instead
The argument for rbenv is that is simpler and does less under the hood than RVM. I'd argue that if you need to add ruby-build, rbenv-gemset, and other plugins to get the functionality you need, then you may as well use RVM in the first place.
This isn't a critique of rbenv, or praise for RVM. I'm just pointing out that if you want a tool that gives you most of RVM's functionality, you might was well just use the tool that gives you want you want "out of the box" rather than bolt the functionality on post facto.
You can certainly do what you need to do with rbenv, one way or another. I'd just suggest that you not put yourself in a position where you have to fight your tools to get things done.


Q:

Can others read my DNS entries?

Suppose I define an A record in my DNS for host foo.example.com. If nobody knows about the existence of foo.example.com, but do about example.com, could someone somehow query the DNS records of example.com to return that name foo.example.com?

A:

The answer is it depends.  If the user can guess the name, like www, then yes they can.  If you use more esoteric names the user would only be able to get arbitrary records if they were able to do what's called a zone transfer, which sends the entire domain's data.
Most nameservers disallow zone transfers by default.  You can test yours here:
https://tools.digitalpoint.com/zone-transfer?domain=example.com

A:

From end-user perspective of view, no. DNS will only return results for specific Hostname (or IP address for reverse-lookup).
Yet, many DNS servers support the feature known as Zone Transfer, that basically can dump all zone file data to another machine.
By doing so, the server can save some load by letting all other DNS servers have the full zone file instead of delegating the resolve request to it.
In reality, most DNS Administrators will not allow Zone Transfer for obvious (security) reasons.
If you want to try it yourself, use nslookup (in Windows):
//#requesting for google.com dns server
set q=ns
google.com

#response is: primary name server = ns1.google.com

server ns1.google.com
ls -d google.com //#this is the zone transfer request

More in Wikipedia


Q:

Pattern matching in rust and mutability

Let's say that I have an Option<String> and want to pattern match to get a mutable reference to the String. I can do the following (_a needs to be mutable):
  let mut _a: Option<String> = Some(String::from("foo"));
  if let Some(ref mut aa) = _a {
    aa.push_str("_");
    println!("aa: {:?}", aa)
  }

Now let's say that I have two Option<String> values that I want to pattern match over.
  let _b: Option<String> = Some(String::from("bar"));
  let _c: Option<String> = Some(String::from("baz"));
  if let (Some(ref mut bb), Some(ref mut cc)) = (_b, _c) {
    bb.push_str("_");
    cc.push_str("_");
    println!("bb: {:?}, cc: {:?}", bb, cc);
  }

Strangely, I can use ref mut in the patterns, even though neither _b nor _c are mutable, and I can mutate the strings.  Why is that allowed here in this case? I'd expect this not to compile unless both _b and _c are declared as mutable similar to the first example above.
I think what may be happening is that a tuple is constructed in the pattern match, i.e. (_b, _c), and then some compiler magic allows the ref mut on the pattern that is "bound" to this tuple. Is that correct?
Rust version:
rustc 1.41.1 (f3e1a954d 2020-02-24)

A:

The mut isn't necessary if the value is wrapped in a tuple, because the tuple is a new value (playground):
let a = Some(String::from("foo"));
if let (Some(mut aa),) = (a,) {
    aa.push_str("_");
    println!("aa: {:?}", aa)
}


Q:

Synchronous buck using BJT's in stead of MOSFETS

Recently I came across a schematic of a synchronous buck converter using normal transistors in stead of MOSFETS, like this:

I was always under the impression that when the top switching device turns off, the inductor generates a large negative voltage because it wants to resist the change in flow of current. That's why the reverse biased freewheel diode is there in a asynchronous buck regulator, so the current can keep flowing.
How does the above circuit work then? The bottom PNP transistor, taking the place of the freewheel diode, cannot conduct current in that direction afaik. Current can flow emitter to ground but not from ground to emitter, can it ?
I built the circuit and it appears to work, measuring point before the inductor, where both emitters meet (excuse the poor quality):

Although I'm not sure what I'm seeing here. There appears to be a dip below ground on the negative cycle. At first I thought this was the inductor's negative voltage spike, somehow being cut off by the transistor. But the same is happening on the positive cycle, with a little 'bulge' above VCC.
Could anyone enlighten me about how this works and what is happening?

A:

Current can flow emitter to ground but not from ground to emitter, can
  it ?

Collector and emitter can work in reverse. It's an NPN or a PNP so junctions are somewhat interchangeable but you don't get great β but you do usually get quite low saturation voltages.
On the other hand, the circuit has poor efficiency because the top transistor (NPN) is an emitter follower and will always drop pretty much 0.7 volts or greater unless the base drive is lifted above the incoming power rail.
I would never sanction using this circuit - MOSFETs are far more suited to synchronous buck conversion (generalism alert!).


Q:

Wait for jQuery show() to finish before continuing function?

I can't make my div visible with the jquery show() until my function is over! It actually works in IE/FF but not in Chrome. How can I make sure my element is visible before continuing with my function?
Here's my code:
function doOperation(){
    $("#progressbar_area").show();
    (...)
}

A:

Add a callback to show:
$("#progressbar_area").show(speed, function() {});

The callback function will be called when the animation is complete.


Q:

Is "This question requires developer only knowledge" the same thing as developer intent?

The question I have in mind, in particular, is this one. There are arguments being made that this question is off topic because it requires developer insight in order to have a 100% authoritative answer. Does this fall under the category of developer intent or not?

A:

This is not developer intent.
As we have discussed before, answerability is a horrible metric for whether or not a question should be considered on-topic or not. In this case, without scouring the game code, there is no way to prove anything that those answering the question are saying, fair enough. However, this doesn't suddenly make it about developer intent. The question asks about a game mechanic, and how it works. It does not ask why it works, nor does it ask what the developer was thinking when implementing it.
Sure we can't prove anything beyond a reasonable doubt, but we can make a reasonable assessment based on experience, and the knowledge we can uncover. But that does not make it off-topic.


Q:

jQuery is adding styles to every class, when I said not to

I have set a data attrabute called "sel", and the following jQuery asks for the data-sel that has a value of 'true', but it's adding it to every class, even the ones that don't have 'data-sel'
jQuery:
var selTrue = $(".slide").data("sel", 'true');
$(selTrue).css({'display': 'inline-block'});

HTML:

1

2

3

4

How do I prevent if from applying to to every class?
Trying to solve:
• I tried this:
$(".slide").not(selTrue).css({'display': 'none'});

still didn't solve my problem

Fiddle

A:

In order to select against your data attribute you need to use
$(".slide[data-sel='true']").css({'display': 'inline-block'});

what you're doing is actually selecting all elements with the slide class, and then setting their data-sel attribute.
here's the documentation
http://api.jquery.com/attribute-equals-selector/


Q:

How can I use an NSPredicate to select an exact phrase from an array?

I am using an NSPredicate to filter an NSDictionary by a list of states and countries.
All the data are stored in a comma separated array: @"Alabama", @"Alaska", @"Arizona", @"Arkansas", @"California", @"Colorado", etc
However, there are 2 situations where duplicates are occurring. The state "New Mexico" contain the word "Mexico", and "Arkansas" contains the word "Kansas.
Here's the basic code I'm using to define the predicate.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Location contains[c] %@", @"Kansas"];

How can I make sure "Kansas" doesn't return objects with "Arkansas"?
Using BEGINSWITH or LIKE doesn't work because the list begins with some other state.
Thanks!

A:

Let's see if I understand correctly. You have a dictionary, where there is a key "Location" whose object is a string with comma separated state names. Sounds like you need a regular expression to match.
NSString* expr = [NSString stringWithFormat:@"^%1$@.*|.*, %1$@.*", @"Kansas"]
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"Location MATCHES[c] %@", expr];

Now, here is how it would behave for different examples:
@{@"Location": @"Kansas, Arkansas, Alabama"} //Pass
@{@"Location": @"Alabama, Kansas"} //Pass
@{@"Location": @"Arkansas, Alabama"} //Fail

The regular expression ^%1$@.*|.*, %1$@.* tests if the word provided is either at the start of the string or followed by characters and ", ", which puts it in the middle. %1$@ takes the first param, so that it can be used multiple times instead of prividing the same string several times.


Q:

Is it possible to deploy Nuxt SSR application on AWS?

I'm new to AWS. I can't find any explanation on how to deploy Nuxt SSR app on AWS although I could find ones on how to deploy static Nuxt app there. Is it possible to deploy Nuxt SSR app on AWS? I have spent long enough time already so please let me ask for your help. Thanks.

A:

Yes, you can deploy just about anything on AWS if you configure the compute resources correctly. Static websites can be served from S3 directly, but for those with a dynamic backend you'll need to use something like EC2 or Lambda. I found this guide for using Lambda and Serverless Framework to deploy a Nuxt SSR app:  https://dzone.com/articles/a-crash-course-on-serverless-side-rendering-with-v
You could also use an EC2 instance as your compute engine, but to do that you'll need to install all the dependencies and manage the host operating system and the web server. Hope that helps!


Q:

How can I rewrite links with JavaScript or jQuery and a regular expression?

Looking to modify Yahoo Answers links to remove some parts, saving just the qid and replacing index with answer.
So this:
http://answers.yahoo.com/question/index;_ylt=AhT5ZZwbMiGWdQZDSxD1ML305nNG;_ylv=3?qid=20121004094847AAjekoj

becomes this:
http://answers.yahoo.com/question/answer?qid=20121004094847AAjekoj

I know there are ways to rewrite links with .htaccess but in this case, it would need to be a Greasemonkey script since the task would be done on sites I visit, and not my websites.

A:

In General, this should do it (Complete GM script):
// ==UserScript==
// @name     _Replace yahoo-answers links
// @include  http://answers.yahoo.com/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change introduced
    in GM 1.0.   It restores the sandbox.
*/
var targLinks   = $("a[href*='question/index']");
targLinks.each ( function () {
    if (/\bqid=\w+/i.test (this.href) ) {
        var newHref = this.href

        var newPath = this.pathname.replace (/\/question\/index.+$/, "/question/answer");
        var newURL  = this.protocol + "//"
                    + this.host
                    + newPath
                    + this.search
                    + this.hash
                    ;
        this.href   = newURL;
    }
} );


Q:

Can not register handler for SIGTRAP

I am trying to register a handler for the SIGTRAP caused by calling int3 in child, but it does not work. Changing SIGTRAP to SIGCHLD works.
#include <signal.h>
#include <wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void child();
void parent(pid_t pid);
void sigtrap_handler(int sig);

int main(){
    pid_t pid = fork();
    if(pid == 0){
        child();
    } else {
        parent(pid);
    }
}

void child(){
    sleep(1);
    asm("int3");
    exit(EXIT_SUCCESS);
}

void parent(pid_t pid){
    signal(SIGTRAP, sigtrap_handler);
    int status;
    do{
        waitpid(pid, &status, WUNTRACED | WCONTINUED);
    } while(!WIFEXITED(status) && !WIFSIGNALED(status));
    exit(EXIT_SUCCESS);
}

void sigtrap_handler(int sig){
    printf("Process %d received sigtrap %d.\n", getpid(), sig);
}

A:

Only the parent process has registered a signal handler for SIGTRAP but not the child process. So when you raise SIGTRAP in child process, the parent process process is not aware of it.
SIGCHLD works (i.e. received by parent) because when the child process terminates (or stops), the signal SIGCHLD is sent to the parent process. But in case of SIGTRAP (or any other signal), it's not sent to the parent process. SIGCHLD is special in the sense, it's sent by default to the parent process on termination whereas other signals are not.
If you add a handler in child process, you'll see the handler getting invoked:
void child(){
    signal(SIGTRAP, sigtrap_handler);
    sleep(1);
    asm("int3");
    exit(EXIT_SUCCESS);
}

By the way, printf() is not an async-signal-safe function, so you can't safely call it in a signal handler.


Q:

Unable to get CDI working in Weblogic 12c, hibernate 5.2.4, hibernate-validator/cdi 5.3.1

My env:
weblogic 12c
with jpa2.1 patch that sets: SET PRE_CLASSPATH=%MW_HOME%\oracle_common\modules\javax.persistence_2.1.jar;%MW_HOME%\wlserver\modules\com.oracle.weblogic.jpa21support_1.0.0.0_2-1.jar
my-ear/APP-INF/lib contains:
hibernate-release-5.2.4.Final/lib/required/*.jar
hibernate-validator-5.3.1/dist/*.jar and hibernate-validator-5.3.1/dist/lib/required/*

my persistence.xml:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
  http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
  version="2.1">
<persistence-unit name="myPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>myDataSource</jta-data-source>

I am able to use persistence.xml and entityManager gets injected into my session bean without any issues. However when I add beans.xml (to use CDI) in one of the ejb-jar/META-INF I get:
org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001435 Normal scoped bean class org.hibernate.validator.internal.engine.ValidatorImpl is not proxyable because it has no no-args constructor - ValidatorBean [id=org.hibernate.validator.internal.cdi.ValidatorBean_default].

My weblogic-application.xml contains:
<prefer-application-packages>
 <package-name>antlr.*</package-name>
 <package-name>org.hibernate.*</package-name>
 <package-name>org.hibernate.validator.*</package-name>
 <package-name>org.hibernate.validator.internal.cdi.*</package-name>
 <package-name>javax.validation.*</package-name>
 <package-name>javax.validation.spi.*</package-name>
<package-name>javax.validation.bootstrap.*</package-name>

Complete stacktrace:
Exception 0 :
org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001435 Normal scoped bean class org.hibernate.validator.internal.engine.ValidatorImpl is not proxyable because it has no no-args constructor - ValidatorBean [id=org.hibernate.validator.internal.cdi.ValidatorBean_default].
    at org.jboss.weld.util.Proxies.getUnproxyableClassException(Proxies.java:214)
    at org.jboss.weld.util.Proxies.getUnproxyableTypeException(Proxies.java:180)
    at org.jboss.weld.util.Proxies.getUnproxyableTypesExceptionInt(Proxies.java:195)
    at org.jboss.weld.util.Proxies.getUnproxyableTypesException(Proxies.java:169)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:151)
    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:388)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:371)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:379)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:110)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.initCdi(CDIAppDeploymentExtension.java:76)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.activate(CDIAppDeploymentExtension.java:49)
    at weblogic.application.internal.flow.AppDeploymentExtensionFlow.activate(AppDeploymentExtensionFlow.java:37)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
    at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:61)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:587)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:339)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:846)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1275)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:442)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:176)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)

    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:398)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:371)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:379)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:110)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.initCdi(CDIAppDeploymentExtension.java:76)
    at com.oracle.injection.integration.CDIAppDeploymentExtension.activate(CDIAppDeploymentExtension.java:49)
    at weblogic.application.internal.flow.AppDeploymentExtensionFlow.activate(AppDeploymentExtensionFlow.java:37)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
    at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:61)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:587)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:150)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:116)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:339)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:846)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1275)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:442)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:176)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:548)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)

What am I missing? How do I get beans.xml/CDI working in this environment?

A:

I installed Weblogic patches 17754607 and 23744018 (Weblogic Server 12.1.3.0.161018).
and removed:
hibernate-validator-5.3.1/dist/*.jar from my-ear/APP-INF/lib.
The Oracle provided validation jars worked fine - and I am now able to use CDI.


Q:

Car suddenly stops accelerating and overheat indicator comes on

Vehicle: Skoda Fabia TDI 1.2L diesel
While driving back home, the car suddenly stopped accelerating and the RPM was stuck at 1000, even when I applied more gas.
Immediately after, the overheat icon started blinking.
I pulled the car over to check if there was any coolant left in the reservoir but it was totally empty and the radiator was still spinning.
I let the car cool down for a bit and filled the reservoir with water. Within a couple of minutes, the radiator stopped spinning. I assumed that this indicated the engine cooled down enough. I drove for a minute or 5 and pulled it over again to check the coolant reservoir, to see it's empty again. The car hasn't moved since then.
What I've noticed is that whenever I shut down the engine, the radiator keeps running for far too long. The Engine Fault indicator is always active and the service center says it's probably some wiring issue and that the problem is resolved. However, it keeps returning.
Can some one help me understand what exactly happened here:
1) Why did the car suddenly stop accelerating?
2) How to overcome the heating issue ?
3) What can I do about the engine fault indicator ?

A:

Seems you have some serious overheating issues with your car.

Engine goes into limp mode with reduced power. Modern engines do this when there is a serious issue, it allows you to find a safe parking spot.
Could be a coolant leak or a broken water pump. The water pump is a service item, how old is your car en when was the pump last changed for a new one?
See item 1, as long as the engine has overheating issues you will have a warning sign. A cooling fan that is constantly running is a side effect of the overheating issues and may also be caused by the limp mode.

In any case i'd suggest to have a mechanic check your cooling system for leaks and correct operation.


Q:

How do I access hash data in sinatra?

I am attempting to access hash data in sinatra:
require 'rubygems'
require 'sinatra'

class List
   def self.items
   return items = {

   :something1 =>  { :attribute1 => "somestring1", :attribute2 => "somestring2" },
   :something2 =>  { :attribute1 => "somestring3", :attribute2 => "somestring4" }

   }
   end
end

list = List.items

get '/' do
   list.each do |name, meta|
      "#{name}
#{meta[:attribute1]}
#{meta[:attribute2]}

"
   end
end

I expected sinatra to print the hash data of each hash. However, it printed just the hashes instead (probably because I called list.each). The console prints the expected result when I use puts.
To clarify, the desired result is:
something1
somestring1
somestring2

something2
somestring3
somestring4

How do I make sinatra print just the variables?
Thanks!

A:

Try this:
get '/' do
   s = ''
   list.each do |name, meta|
      s << "#{name}
#{meta[:attribute1]}
#{meta[:attribute2]}

"
   end
   return s
end

A:

Use map instead of each, and then join the result to return a string:
get '/' do
  list.map do |name, meta|
    "#{name}
#{meta[:attribute1]}
#{meta[:attribute2]}

"
  end.join
end

each returns the array you call it on. map will return a new array, transforming each entry in the Enumerable according to your block.


Q:

Does this algorithm cover all cases for finding minimum coin change for a sum?

I am trying to solve the minimum coin change problem. The question is:
Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm} valued coins, what is the minimum number of coins to make the change?
My algorithm suggested is:
Starting with an array arr[1..V],where V is the value:

For all the denominations,initialise arr[d]=1 as this is the base case. If the value == demoniation of a coin,only 1 coin is required and hence it is the least
For all values from i : 1...V:
  compute the minimum no of coins required to make change for a value of 'i'.
2.1. This can be done by :
   For all j: 1....(i-1)
         arr[i]=min(arr[i],arr[j]+arr[i-j]);
return arr[V];

Is this logic flawed or does it cover all cases?
Most DP solutions have used a 2-D array and I don't understand why they would use O(n^2) memory space,if this exists and is correct.
Thank u.

A:

How about cases whre some value V cant be obtained?
i.e. we have coins {5,6,7,8,9} and we cant make values 1,2,3,4, You should initialize all value != demoniation cells to infinity constant or something similar.
Now for the reason most people use O(n^2) memory:
This problem comes with various flavors, most common one being you can only use each coin once, in this case using state dp[i][j] - min coins that sum to j after considering first i coins seem to be easier to understand for most people even though this can also be done with O(n) memory (just looping backwards)


Q:

Copying tables between databased with different authentication DB2

Hey StackOverflow community,
My question is as follows:
I have a table, say USER_ADDR with a bunch of columns in one database, say DB001
I need to copy the contents of this table(based on a criteria) to a similar table USER_ADDR (same name, yes) in another database DB002 with a different userID and pwd.
I need to do this in a stored procedure that will be executed using a .net framework.
I tried this:
INSERT INTO "DB002".USER_ADDR (--column names--)
SELECT *
FROM "DB001".USER_ADDR
WHERE ID = "APPLICATION_NO_IN";

I get:

0: Error occurred: [IBM][DB2/NT64] SQL0204N  "DB002.USER_ADDR" is an undefined name.  LINE NUMBER=15.  SQLSTATE=42704 : -204: IBM.Data.DB2: 42704

What am I doing wrong?
Thanks in advance
Vashist

A:

i'm deleting my other answer after seeing the additional info about your use case. Load is mainly for bulk loads of large numbers of records.
in this case i'd recommend you do something like open connection1 in .Net to your data source, select the data and hold it in a .Net DataTable. If required, you can do that select in a stored proc that returns either individual column values for a single row or return a cursor (rowset) that contains all the columns (and rows). Then in .Net open connection2 and insert the data from the DataTable to your destination. Again, that can be done with a stored proc.


Q:

How do Linux binary installers (.bin, .sh) work?

Some software (for ex. the NetBeans IDE) ship the Linux installers in .sh files. Curious about how exactly they 'package' a whole IDE into a 'shell script', I opened the file in an editor. I saw some plain text shell scripting code and then some random gibberish, which I reckon is 'binary' or non-plain text.
I am wondering how they mix plain shell scripts and then probably call the 'non-readable' stuff, which would be the binaries.
Any insight on this?

A:

Basically, it's a shell script prepended to a compressed archive of some sort, such as a tar archive. You use the tail or sed command on yourself (the $0 variable in Bourne shell) to strip off the shell script at the front and pass the rest to your unarchiver.
For example, create the following script as self-extracting:
#!/bin/sh -e
sed -e '1,/^exit$/d' "$0" | tar xzf - && ./project/Setup
exit

The sed command above deletes all lines from the first line of the file to the first one that starts with "exit", and then passes the rest on through. If what starts immediately after the "exit" line is a tar file, the tar command will extract it. If that's successful, the ./project/Setup file (presumably extracted from the tarball) will be executed.
Then:
mkdir project
echo "#!/bin/sh" > project/Setup
echo "echo This is the setup script!" >> project/Setup
chmod +x project/Setup
tar czf - project >> self-extracting

Now, if you get rid of your old project directory, you can run self-extracting and it will extract that tar file and run the setup script.

A:

You might want to check out makeself.sh
From the authors' notes.

makeself.sh is a small shell script that generates a self-extractable tar.gz archive from a directory. The resulting file appears as a shell script (many of those have a .run suffix), and can be launched as is. The archive will then uncompress itself to a temporary directory and an optional arbitrary command will be executed (for example an installation script).
Makeself archives also include checksums for integrity self-validation (CRC and/or MD5 checksums).
The makeself.sh script itself is used only to create the archives from a directory of files. The resultant archive is actually a compressed (using gzip, bzip2, or compress) TAR archive, with a small shell script stub at the beginning. This small stub performs all the steps of extracting the files, running the embedded command, and removing the temporary files when it's all over. All what the user has to do to install the software contained in such an archive is to "run" the archive [that is execute the script]
I am trying to keep the code of this script as portable as possible, i.e it's not relying on any bash-specific features and only calls commands that are installed on any functioning UNIX-compatible system. This script as well as the archives it generates should run on any Unix flavor, with any compatible Bourne shell, provided of course that the compression programs are available.

Finally, the makeself package itself comes as a self-extracting script called makeself.run.

A:

Add a Binary Payload to your Shell Scripts


Q:

How execute sqlite query?

windows 10, emacs 26.1
I has file my_test.sql. This file content SQLite query. Is it possible to execute this sql query and get results?

I has sqlite db file test.db
It has table notification_invoice
I create file my_test.sql with one sql query:
select * from notification_invoice order by notificationDate

So here my steps:

Open my_test.sql

M-x sql-set-product RET sqlite
sql-product-interactive

in the sql-mode buffer) to call sql-send-buffer

As you can see I not get sql result.
What is wrong with my steps?

A:

Open my_test.sql (this buffer is in sql-mode; aka "SQL")
M-x sql-set-product RET sqlite
C-cTAB to call sql-product-interactive to connect to the database (this new buffer is in sql-interactive-mode; aka "SQLi")
C-cC-b (in the sql-mode buffer) to call sql-send-buffer, sending the whole buffer as a query

Use C-hm in the sql-mode buffer to see the other sql-send-* commands and key bindings for sending queries.


Q:

Imagem não consegue ser carregada na aplicação

A imagem aparece normal ao rodar no "ionic serve" mas quando rodo em um device ionic run android --device ela não consegue ser carregada, estranho que eu coloquei um alt na tag img e só consegue ser exibido o alt, já tentei tirar mas não aparece nada.
A minha tag está assim :

O que poderia estar causando o mau carregamento da imagem? Tenho outra como background que é bem mais pesada e aparece normalmente.

A:

Voce deve colocar a imagem direto da pasta assets, se me recordo bem.
Tenta assim:

ou assim:

Quando o ionic compila a app ele joga para a pasta build e o acesso é feito por la, ao usar o ../ ele perde a referencia da pasta correta.


Q:

What is the common name of the content injection pattern in CMS

What is common name for the patterns in CMS contents? Like:
Hello {{FIRSTNAME}}
Your order was sent to:
{{ADDRESS}}

Are these

variables
patterns
blocks
placeholders
macros
or what

A:

I think it depends on the system and your environment.
In a programming environment I would name them variables and all around is the template.
But placeholder is also okay, especially if you talk to non-programmers.
HTH.


Q:

Is it possible to extract same field with two different name through regex?

I am trying to extract few fields from log file using regex. my regex is working fine. I just want that one of the extracted field associate with two different name.
My Regex Demo
In above example, I want that extracted field "cms_relative_time" is also named as "relative time". that means, both relative_time and cms_relative_time should refer to same value.
first of all,I am not sure if its possible in regex. I tried few things like copy the same code and replace name but its not working.
(?P<cms_relative_time>\d+\.\d+)(?P<relative_time>\d+\.\d+)

A:

You may put a named capturing group inside another:
(?P<relative_time>(?P<cms_relative_time>\d+\.\d+))
|                 |                             ||
|                 |---------- Group 2 ----------||
|------------------ Group 1 ---------------------|

See your updated demo.


Q:

C++ friend function

I'm making chess game for my uni and I have to use at least one friend function.
So here is my BoardField class header:
#include "Game.h"

class BoardField {
private:
    ChessPiece m_piece;
    SDL_Rect m_field;

public:
    BoardField();

    friend void Game::init_board_fields();
};

Partial Game class header:
class Game {
private:
    //members
    ...

    //methods
    ...
public:
    void init_board_fields();
    ...
};

And the method:
void Game::init_board_fields()
{
    int field_width = m_window_props.w / 8;
    int field_height = m_window_props.h / 8;
    int field_index = 0;

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            BoardField field;
            // here I get the error that member m_field is inaccessible
            field.m_field = { j * field_width, i * field_height, field_width, field_width };
            m_board_fields[field_index++] = field;
        }
    }
}

So I get this error (look for comment in last code block).
Do I poorly understand friend? Does this keyword allow access to private members/methods or does something else?

A:

I simply want to say that a friend method c++ is not part of any class. This being said, your friend method is not part of the class BoardField but it is trying to access its private member(Which is wrong).
Game class header has to be implemented in Game.cpp not in BoardField class.
You are getting the error because you are trying to access a private member of BoardField class through a method declared in Game class.Here I am leaving out the friend concept.
A proper way to use friend concept in your case would be to make your BoardField Class a Friend of Game Class. This way, Game class will have access to everything in class BoardField. This will eventually work in what your are trying to do.
You simply have to declare : friend BoardField in your Game class.
class Game {
private:
    //members
    ...

    //methods
    friend BoardField;
    ...
public:
    void init_board_fields();
    ...
};


Q:

Postfix security: Accepting emails for and sending emails from my domains only

I have a virtual server running Debian Wheezy, and I am trying to configure it as a Postfix mail server. I haven't found though any easy to follow tutorial on how to secure Postfix... and my mail.log file is already full of requests from spammers for sure, since my server is only a few weeks old, and I haven't configured it yet.
So, I am looking for the proper Postfix configuration to accept emails going to my domains or going to other domains only if they are coming from my domains. I don't want Postfix to relay emails from joeblow@NotMyDomain1.com to MrSmith@NotMyDomain2.com.
Also, I would like my SMTP server to require a secure authentication to send emails.
However, let's say I own domains abc.com, def.com and xyz.com, then I want all emails coming from these domains to be relayed by my server if proper authentication is given, and I want all emails going to these domains to be relayed by the server.
And I don't want to restrict emails relaying by network address, since I may be on any network with my laptop, and I want to be able to send emails from it.
I have ssh access to my server, and I have Webmin on it. I don't mind using shell commands, but it would be nice to have a web interface to manage all this and more on my server... if anyone has a suggestion.

A:

You can do this mixing hash tables or regex tables containing your domains and tune the parameters mynetworks, relaydomains and smtpd_sender_restrictions permitting only your networks.
Take a look here: http://www.postfix.org/postconf.5.html#mynetworks


Q:

How to remove duplicate characters in string?

I have a string that looks like this: some, , , , text
I need it to look like this: some, text
There is unknown number of such commas, it may be 2, it may be 10
I tried recursive approach but it did not work as expected:
<xsl:template name="remove-duplicate">
        <xsl:param name="text" />
        <xsl:param name="remove" />

        <xsl:value-of select="$text" />
        <xsl:if test="contains($text, $remove)">
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="$text" />
                <xsl:with-param name="replace" select="$remove" />
                <xsl:with-param name="by" select="''" />
            </xsl:call-template>
            <xsl:call-template name="remove-duplicate">
                <xsl:with-param name="text" select="$text" />
                <xsl:with-param name="remove" select="$remove" />
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

Calling the template:
    <xsl:call-template name="remove-duplicate">
        <xsl:with-param name="text" select="string(.)" />
        <xsl:with-param name="remove" select="' ,'" />
    </xsl:call-template>

The string-replace-all was stolen from this question: XSLT string replace

A:

How about:
<xsl:value-of select="translate(normalize-space(translate($yourString, ', ', ' …')), ' …', ', ')"/>

Note that this assumes your string does not contain any whitespace characters other than spaces.
If this assumption is not true, try the solution posted here: https://stackoverflow.com/a/38177946/3016153


Q:

Jenkins user is gone after macOS update

I'm running Jenkins as a CI server on a Mac. It was running fine on macOS 10.12 with the typical setup with user jenkins.
Today I upgraded macOS to 10.13 (High Sierra). Jenkins could not start after the upgrade process completed. Furthermore, there was no user jenkins on the system. All Jenkins files are there, but there is no jenkins user in Settings -> Users & Groups. If I try to use jenkins user in Terminal, for instance if I try to change file ownership to jenkins with chown, I get:
chown: jenkins: illegal user name

How do I fix this?

A:

You Jenkins configuration still exist under Library/LaunchDaemons/org.jenkins-ci.plist but after the updating for the OS to High Sierra, the Jenkins user got disappear.
So, first you have to create the jenkins user manually from System Preferences/Users & Groups

Account name: jenkins, Full name: Jenkins

After that you have to setup the jenkins configuration to this new user created

sudo chown -R jenkins /Users/Shared/Jenkins
sudo chown jenkins /var/log/jenkins

Finally unload and load jenkins server

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo launchctl load /Library/LaunchDaemons/org.jenkins-ci.plist

Enter to http://localhost:8080 in Safari and you will be able to see you jenkins server

A:

I've managed to re-create jenkins user by extracting the script commands that create it from Jenkins installation. I ran this script in particular:
JENKINS_HOMEDIR="/Users/Shared/Jenkins"
DEFAULTS_PLIST="/Library/Preferences/org.jenkins-ci.plist"

if dscl . -list /Users/jenkins; then
    echo 'jenkins user already exists, attempting to change the shell to /bin/bash'
    # Will fail if UserShell is not /usr/bin/false, but that's ok.
    # Then we will assume an admin has changed it.
    dscl . -change /Users/jenkins UserShell /usr/bin/false /bin/bash
else
    echo 'No jenkins user found, creating jenkins user and group'

# Find free uid under 500
    uid=$(dscl . -list /Users uid | sort -nrk 2 | awk '$2 < 500 {print $2 + 1; exit 0}')
    if [ $uid -eq 500 ]; then
        echo 'ERROR: All system uids are in use!'
        exit 1
    fi
    echo "Using uid $uid for jenkins"

    gid=$uid
    while dscl -search /Groups gid $gid | grep -q $gid; do
        echo "gid $gid is not free, trying next"
        gid=$(($gid + 1))
    done
    echo "Using gid $gid for jenkins"

    dscl . -create /Groups/jenkins PrimaryGroupID $gid

    dscl . -create /Users/jenkins UserShell /bin/bash
    dscl . -create /Users/jenkins Password '*'
    dscl . -create /Users/jenkins UniqueID $uid
    dscl . -create /Users/jenkins PrimaryGroupID $gid
    dscl . -create /Users/jenkins NFSHomeDirectory "$JENKINS_HOMEDIR"

    dscl . -append /Groups/jenkins GroupMembership jenkins
fi

# identify the real default group name for user jenkins
groupid=`dscl . read /Users/jenkins PrimaryGroupID | awk '{print $2}'`
gname=`id -n -g $groupid`

echo "Using jenkins:${gname} as file owner and group for jenkins daemon files"

find "$JENKINS_HOMEDIR" \( -not -user jenkins -or -not -group ${gname} \) -print0 | xargs -0 chown jenkins:${gname}

# Add defaults for heap sizing
arch=$(uname -m)
if [ $arch = 'x86_64' ]; then
    defaults write $DEFAULTS_PLIST heapSize 512m
    defaults write $DEFAULTS_PLIST permGen 512m
    defaults write $DEFAULTS_PLIST minHeapSize 256m
    defaults write $DEFAULTS_PLIST minPermGen 256m
else
    # i386
    defaults write $DEFAULTS_PLIST heapSize 128m
    defaults write $DEFAULTS_PLIST permGen 128m
    defaults write $DEFAULTS_PLIST minHeapSize 64m
    defaults write $DEFAULTS_PLIST minPermGen 64m
fi

defaults write $DEFAULTS_PLIST httpPort 8080

# Set tmpdir
JENKINS_TMPDIR="$JENKINS_HOMEDIR/tmp"
defaults write $DEFAULTS_PLIST tmpdir $JENKINS_TMPDIR
mkdir -p $JENKINS_TMPDIR
chown jenkins:${gname} $JENKINS_TMPDIR

# Create log directory, which can be written by Jenkins daemon
mkdir -p /var/log/jenkins
chown jenkins:${gname} /var/log/jenkins


Q:

Função intrínseca para converter numérico para string

Estou a tentar saber se existe alguma função intrínseca do COBOL para converter um data numérico para string sem precisar usar a cláusula REDEFINES:
(    PIC S9(04) COMP)

Se sim, ela é mais onerosa que usa o REDEFINES?

A:

Não, não tem função intrínseca. REDEFINES, diretamente, não faz nada para você.
Se quiser os números:
01  O-CAMPO COMP PIC 9(4).

01  O-NUMERO PIC 9(4).

MOVE O-CAMPO TO O-NUMERO
DISPLAY O-NUMERO

X'000F' -- 0015

Note que, PIC 9(4) normalmente é 0-9999. É possível utilizar todos os bits: faz O-NUMERO PIC 9(5).
Ou, em Hex:
01  O-CAMPO COMP PIC 9(4).
01  FILLER REDEFINES O-CAMPO.
    05  O-CAMPO-HIGH PIC X.
    05  O-CAMPO-LOW  PIC X.

01  HEX-SUBSCRIPT COMP PIC 9(4) VALUE ZERO.
01  FILLER REDEFINES HEX-SUBSCRIPT.
    05  FILLER PIC X.
    05  HEX-SUBSCRIPT-LOW PIC X.

01  HEX-IN-TEXT.
    05  HEX-IN-TEXT-HIGH PIC XX.
    05  HEX-IN-TEXT-LOW PIC XX.

01  HEX-DIGIT-TABLE.
    05  FILLER PIC X(32)
               VALUE '000102030405060708090A0B0C0D0E0F'.
    05  FILLER PIC X(32)
               VALUE '101112131415161718191A1B1C1D1E1F'.
    05  FILLER PIC X(32)
               VALUE '202122232425262728292A2B2C2D2E2F'.
    05  FILLER PIC X(32)
               VALUE '303132333435363738393A3B3C3D3E3F'.
    05  FILLER PIC X(32)
               VALUE '404142434445464748494A4B4C4D4E4F'.
    05  FILLER PIC X(32)
               VALUE '505152535455565758595A5B5C5D5E5F'.
    05  FILLER PIC X(32)
               VALUE '606162636465666768696A6B6C6D6E6F'.
    05  FILLER PIC X(32)
               VALUE '707172737475767778797A7B7C7D7E7F'.
    05  FILLER PIC X(32)
               VALUE '808182838485868788898A8B8C8D8E8F'.
    05  FILLER PIC X(32)
               VALUE '909192939495969798999A9B9C9D9E9F'.
    05  FILLER PIC X(32)
               VALUE 'A0A1A2A3A4A5A6A7A8A9AAABACADAEAF'.
    05  FILLER PIC X(32)
               VALUE 'B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF'.
    05  FILLER PIC X(32)
               VALUE 'C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF'.
    05  FILLER PIC X(32)
               VALUE 'D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF'.
    05  FILLER PIC X(32)
               VALUE 'E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF'.
    05  FILLER PIC X(32)
               VALUE 'F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF'.
01 FILLER REDEFINES HEX-DIGIT-TABLE.
    05 HEX-DIGITS  PIC X(2) OCCURS 256.

    MOVE O-CAMPO-HIGH TO HEX-SUBSCRIPT-LOW
    MOVE HEX-DIGITS ( HEX-SUBSCRIPT + 1 ) TO HEX-IN-TEXT-HIGH
    MOVE O-CAMPO-LOW TO HEX-SUBSCRIPT-LOW
    MOVE HEX-DIGITS ( HEX-SUBSCRIPT + 1 ) TO HEX-IN-TEXT-LOW
    DISPLAY HEX-IN-TEXT

X'000F' -- 000F

COBOL é uma linguagem antiga. Ela não foi projetada para funções. Até 1989 ela não tinha funções. A partir de 1989 há uma lista limitada de funções intrínsecas (intrinsic). Elas são parte da linguagem e exclusivamente processadas pelo compilador (auxiliado por várias rotinas de tempo de execução, principalmente). Não existem funções definidas pelo usuário. Haverá mais funções intrínsecas na próxima versão do standard COBOL.
Funções definidas pelo usuário existirão em COBOL no futuro. Se quiser usá-las agora, veja o GNU COBOL (pesquise por ele no SourceForge).
Então, sinto muito, mas você vai ter de se virar sem funções.
REDEFINES não faz o que você parece achar que faz. Ele somente permite um outro "mapeamento" de uma armazenagem previsamente definida. O conteúdo da armazenagem não é afetado de maneira alguma, e retém o valor original até que você use o item do REDEFINES como alvo (target) de uma instrução.
Em COBOL, você tem que codar na mão. O que expliquei acima é uma maneira. Em termos de velocidade de execução e linhas de código de PROCEDURE, é uma boa maneira. Ela requer que uma tabela seja definida no WORKING-STORAGE (ou possivelmente no LOCAL-STORAGE).
O COBOL (padrão) não pode manipular bytes individuais em binário. A técnica é redefinir (REDEFINES) um um campo binário de dois bytes com um VALUE nicial de ZERO, e então colocar um byte individual no byte de menor ordem, e usar o campo binário como subscript. Como você quer converter X'00' para "00", e zero não é um subscript válido, mas precisa ser a primeira entrada da tabela, você precisa deslocar a referência do subscript em um ( HEX-SUBSCRIPT + 1 ). Se preferir, você pode usar ADD/COMPUTE para incrementar o valor do subscript em um.


Q:

Name variable with a variable

I am trying to get out of this, variables Car1 Car2, Car3, Car4 to be pushed to an array. But I can't seem to figure out how to increment a variable within a for loop. Any ideas?

function get_info() {
    n = 0;
    for (var option_post in postvalues) {
    n++;
        var pair = postvalues[option_post];
        var string_pair = pair.concat(": ")
        var new_postvalues = (string_pair.concat(document.getElementsByName(pair)[0].value));
        //Set up cars
        var make.concat(n) = document.getElementById("make").value;
        var year.concat(n) = document.getElementById("year").value;
        var model.concat(n) = document.getElementById("model").value;
        var car.concat(n) = "Make: ".concat(make.concat(n)).concat("-Model: ").concat(model.concat(n)).concat("-Year:").concat(year.concat(n)); // combine
    }
    cars.push(car1, car2, car3, car4);
}

A:

There is no reason to create a new identifier on each loop iteration, especially since you are looking to collect the values into an array.
function get_info() {
    var cars = [], car;
    for (var i = 0; i < postvalues.length; i++) {
        // ...

        // create a car
        car = "Make: " + document.getElementById('make' + i).value
            + "-Model: " + document.getElementById('model' + i).value
            + "-Year: " + document.getElementById('year' + i).value;

        // append it to the end of your array
        cars.push(car);
    }

    return cars;
}


Q:

How to copy from Storage to FileSystemStorage in Codenameone and display in BrowserComponent

I've been reading a lot of StackOverflow posts that discuss copying data from FileSystemStorage to Storage in CodenameOne, such as described in this answer from Shai, as seen below:

InputStream stream =
FileSystemStorage.getInstance().openInputStream(i);
OutputStream out =
Storage.getInstance().createOutputStream("MyImage");
Util.copy(stream, out);
Util.cleanup(stream);
Util.cleanup(out);`

I've been trying to do the reverse: save from Storage to FileSystemStorage in order to show a PDF in the BrowserComponent (while using iOS), but have not been able to do so. I need to show the PDF within the app (so I don't want to use Display.getInstance().execute()).
Basically, I'm trying to dynamically populate a Container with whatever files the user selects-- I am using the FileChooser library for CN1 from Steve Hannah. (Disclaimer: I have made slight modifications to this library as it used in the app I'm working on-- HOWEVER, when I choose images with this library and pull them from Storage to an Image via InputStream, they display perfectly in an ImageViewer so I know that all files are being saved correctly in Storage.)
Here is my code (with help from Steve Hannah's comment on GitHub):
        //fileLocation and fileName are slightly different but both end with file extension
        File file = new File(fileToUpload.getFileName());
        FileSystemStorage fss = FileSystemStorage.getInstance();
        InputStream is = Storage.getInstance().createInputStream(fileToUpload.getLocation());
        OutputStream os = fss.openOutputStream(file.getAbsolutePath());
        Util.copy(is, os);
        ToastBar.Status status = ToastBar.getInstance().createStatus();
        String message = file.exists() + "  " + file.isFile() + file.getAbsolutePath();
        status.setMessage(message);
        status.setExpires(3000);
        status.show();
        NativeLogs.getNativeLogs();
        if (Display.getInstance().getPlatformName().equals("ios")) {
            //Log.p("in ios !!!!");
            BrowserComponent browserComponent = new BrowserComponent();
            browserComponent.setURL(file.getPath());
            horizontalContainer.add(browserComponent);
        }

The ToastBar displays true and true for file.exists() and file.isFile().
I stipulate iOS because as far as I've seen while researching previewing PDFs within an app, I've seen that Android needs to have a different implementation, like adding a NativeInterface with an Android library. I also saw in different answers on the Google Group that this functionality (using browserComponent to view PDFs) is only available for iOS and not on the simulator. In the simulator, I see a blank space. My iPhone just freezes and/or crashes after displaying the ToastBar (and I work on a Windows machine, so not much ability to see native logs....)
What can I do to access the file and show it in the BrowserComponent?
Thank you!

A:

Simple solution -- the file had a space in it (eg. "Test page.pdf") and didn't show! When I used files that didn't have spaces this worked and after removing spaces in the file names, thankfully everything worked. I'll have to add code to handle this scenario.
Thanks for your help!


Q:

BackgroundWorker alternatives for Windows Forms

Is it possible to do something like this in a Windows Forms app?
I'm trying to find other ways of updating the UI instead of using the BackgroundWorker all the time. Maybe something like this?:
public List<String> results = new List<String>();

private void button1_Click(object sender, EventArgs e)
{
    When(SomeLongRunningMethod("get") == true)
    {
        // LongRunningMethod has completed.
        // display results on Form.
        foreach(string result in results)
        {
            this.Controls.Add(new Label() { Text = result; Location = new Point(5, (5 * DateTime.Now.Millisecond)); });
        }
    }
}

public void SomeLongRunningMethod(string value)
{
    if(value == "get")
    {
        // Do work.
        results.Add("blah");
    }
}

The above basically says, "Do this and when you're done, add the results to the form."

A:

I recommend you use async/await with Task.Run. Note that returning the results is cleaner:
private void button1_Click(object sender, EventArgs e)
{
  var results = await Task.Run(() => SomeLongRunningMethod("get"));
  foreach(string result in results)
  {
    this.Controls.Add(new Label() { Text = result; Location = new Point(5, (5 * DateTime.Now.Millisecond)); });
  }
}

public List<string> SomeLongRunningMethod(string value)
{
  var results = new List<string>();
  if(value == "get")
  {
    // Do work.
    results.Add("blah");
  }
  return results;
}

I have a series of blog posts on my blog that describe how Task.Run acts as a replacement for BackgroundWorker.


Q:

JSON Exception when trying to retrieve object string

I'm trying to retrieve the "Maxspeed" string from the JSON below.
It iterates through the array, but when it reaches the "tag" object and tries to retrieve the "maxspeed" value, it returns an exception(below).
Would anyone know why this is happening?
Any help would be appreciated.
Thanks.
Exception:
org.json.JSONException: No value for maxspeed

Java:
JSONObject parentObject = new JSONObject(result);

                JSONArray speedJSON = parentObject.getJSONArray("elements");

                for (int i = 0; i < speedJSON.length(); i++) {

                    JSONObject element = (JSONObject) speedJSON.get(i);

                    if (!element.isNull("tags")) {
                        //JSONObject tags = (JSONObject) speedJSON.getJSONObject(i).get("tags");
                        String maxspeed = element.getString("maxspeed");
                        txtSpeed.setText(maxspeed+" here");
                    } else {
                        //Your error handling here...
                    }
                }
                //txtSpeed.setText(""+);
                this.progressDialog.dismiss();

JSON:
{
  "version": 0.6,
  "generator": "Overpass API",
  "osm3s": {
    "timestamp_osm_base": "2015-03-16T20:10:02Z",
    "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
  },
  "elements": [

{
  "type": "node",
  "id": 768053039,
  "lat": 54.9526671,
  "lon": -7.7273348
},
{
  "type": "node",
  "id": 768053040,
  "lat": 54.9498094,
  "lon": -7.7176056
},
{
  "type": "node",
  "id": 768053041,
  "lat": 54.9497066,
  "lon": -7.7173174
},
{
  "type": "node",
  "id": 768053043,
  "lat": 54.9495658,
  "lon": -7.7170937
},
{
  "type": "node",
  "id": 768053044,
  "lat": 54.9495035,
  "lon": -7.7169816
},
{
  "type": "node",
  "id": 791492493,
  "lat": 54.9494183,
  "lon": -7.7168205
},
{
  "type": "node",
  "id": 795319854,
  "lat": 54.9510427,
  "lon": -7.7218262
},
{
  "type": "node",
  "id": 795320324,
  "lat": 54.9509153,
  "lon": -7.7213706
},
{
  "type": "node",
  "id": 1922546572,
  "lat": 54.9502165,
  "lon": -7.7190169
},
{
  "type": "node",
  "id": 1922546679,
  "lat": 54.9504739,
  "lon": -7.7199078
},
{
  "type": "node",
  "id": 1922546692,
  "lat": 54.9500860,
  "lon": -7.7185174
},
{
  "type": "node",
  "id": 1922602861,
  "lat": 54.9517250,
  "lon": -7.7241644
},
{
  "type": "node",
  "id": 1922622063,
  "lat": 54.9514357,
  "lon": -7.7231690
},
{
  "type": "node",
  "id": 2673934802,
  "lat": 54.9498543,
  "lon": -7.7177617
},
{
  "type": "way",
  "id": 64273241,
  "nodes": [
    768053039,
    1922602861,
    1922622063,
    795319854,
    795320324
  ],
  "tags": {
    "highway": "secondary",
    "maxspeed": "60",
    "name": "Port Road",
    "oneway": "no",
    "ref": "R229"
  }
},
{
  "type": "way",
  "id": 64887990,
  "nodes": [
    795320324,
    1922546679,
    1922546572,
    1922546692,
    2673934802,
    768053040,
    768053041,
    768053043,
    768053044,
    791492493
  ],
  "tags": {
    "highway": "secondary",
    "maxspeed": "60",
    "name": "Port Road",
    "oneway": "no",
    "ref": "R229"
  }
}

  ]
}

A:

You are trying to get maxspeed from the element, but it's not there. It is inside tags object in the element.
You need something like this
if (!element.isNull("tags")) {
    JSONObject tags = element.getJSONObject("tags");
    String maxspeed = tags.getString("maxspeed");
    txtSpeed.setText(maxspeed+" here");
} else {
    //Your error handling here...
}


Q:

Symfony2 - MopaBootstrapBundle - how to remove form styling, but still use Collection type

All I want is nice Collection type with add and remove buttons and I tried using BraincraftedBootstrapBundle, but I really hated, that it styled my forms and if I configured it not to style, then I wasn't able to use collection type functionality it provided. I decided to try MopaBootstrapBundle instead, but I am facing similar problem. My form is styled according to bundle and if I configure not to style:
mopa_bootstrap:
    form:
        templating: false

My form is unstyled again as I want it, but then collection type is not working. The things I do not like is that form are getting form-horizontal, inputs - form-controls and labels - form-labels classes. Any ideas what am I missing?
I would like bundle not to style my form fields except collection type.

A:

You can overwrite the default style of mopaBootstrap.
In your conf do:
mopa_bootstrap:
    form:
        templating: YourBundle:Form:fields.html.twig

Then in your custom fields.html.twig use only the collection_widget block (https://github.com/phiamo/MopaBootstrapBundle/blob/master/Resources/views/Form/fields.html.twig):
{% block collection_widget %}
{% spaceless %}
{% if prototype is defined %}
    {% set prototype_markup = form_row(prototype) %}
    {% set data_prototype_name = form.vars.form.vars.prototype.vars.name|default('__name__') %}
    {% set data_prototype_label = form.vars.form.vars.prototype.vars.label|default('__name__label__') %}
    {% set widget_form_group_attr = widget_form_group_attr|merge({
        'data-prototype': prototype_markup,
        'data-prototype-name': data_prototype_name,
        'data-prototype-label': data_prototype_label
    })|merge(attr) %}
{% endif %}
{# Add row by default use attr.class to change#}
{% if 'collection' in form.vars.block_prefixes and attr.class is defined %}
    {% set widget_form_group_attr = widget_form_group_attr|merge({'class': widget_form_group_attr.class|default('row') ~ ' ' ~ attr.class}) %}
{% endif %}
{# collection item adds class {form_id}_form-group  too #}
{% set widget_form_group_attr = widget_form_group_attr|merge({'id': 'collection' ~ id ~ '_form_group', 'class': widget_form_group_attr.class ~ ' collection-items ' ~ id ~ '_form_group'}) %}

<div {% for attrname,attrvalue in widget_form_group_attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>
{# Add initial prototype form #}
{% if form.vars.value|length == 0 and prototype is defined %}
    {% for name in prototype_names %}
        {{ prototype_markup|replace({'__name__': name})|raw }}
    {% endfor %}
{% endif %}
{{ block('form_widget') }}
</div>
{% endspaceless %}
{% endblock collection_widget %}

Something like this should do the trick.


Q:

Stretch image on top of a button in order to push view controller

I have this image which is UIButton:

I want to add some kind of gesture (pan gesture) to slide it to the right and I want the image to stretch to the right also like this:

It's very similar to the iPhone's "Slide to unlock" methods but without the same image that moves around from left to right.
Is it possible to do that?
EDIT:
I've added a UIPanGestureRecognizer to my button like this:
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(buttonDidDragged:)];
[self.buttonAbout addGestureRecognizer:panGesture];

self.buttonFrame = self.buttonAbout.frame;

Also I saved the button frame into a CGRect.
Now this is the 'buttonDidDragged' methods, but I also have a problem, the button seems to go to the right but the image remains the same image. it will not stretch.
- (IBAction)buttonDidDragged:(UIPanGestureRecognizer*)gesture
{
    CGPoint translation = [gesture translationInView:self.view];

//    gesture.view.center = CGPointMake(gesture.view.center.x + translation.x, gesture.view.center.y);

    NSLog(@"%f",gesture.view.frame.origin.x + gesture.view.frame.size.width);
    gesture.view.frame = CGRectMake(gesture.view.frame.origin.x,
                                    gesture.view.frame.origin.y,
                                    gesture.view.frame.size.width + translation.x,
                                    gesture.view.frame.size.height);

    UIButton *button = (UIButton*)gesture.view;
    UIImage *buttonImage = [UIImage imageNamed:@"about_us_button.png"];
    buttonImage = [buttonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 80, 0, 0)];
    [button setImage:buttonImage forState:UIControlStateNormal];
    [button setImage:buttonImage forState:UIControlStateHighlighted];

    if (gesture.state == UIGestureRecognizerStateEnded)
    {
        [UIView animateWithDuration:0.5
                              delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             CGPoint finalPoint = CGPointMake(self.buttonFrame.origin.x + (self.buttonFrame.size.width / 2),
                                                              self.buttonFrame.origin.y + (self.buttonFrame.size.height / 2));
//                             gesture.view.center = finalPoint;
                             button.frame = newFrame; // This is where you change the frame of the button to make it stretch.
                         } completion:nil];
    }

    [gesture setTranslation:CGPointMake(0, 0) inView:self.view];
}

A:

Do like this,
In .h
CGSize dragViewSize;

then,
-(IBAction)buttonDidDragged:(UIPanGestureRecognizer*)gesture
{
    CGPoint translation = [gesture translationInView:self.view];

    if (gesture.state == UIGestureRecognizerStateBegan) {

        dragViewSize = gesture.view.frame.size;

    } else if (gesture.state == UIGestureRecognizerStateChanged) {

        CGRect _rect = gesture.view.frame;
        _rect.size.width=dragViewSize.width+translation.x;
        gesture.view.frame = _rect;

    }
    else if (gesture.state == UIGestureRecognizerStateEnded) {

    }
}

Its working fine... hope it will helps you...


Q:

How to make HTML5 app installable on Android Market and Apples AppStore?

I have simple question. I have HTML5 app and I want it to be installable as an ordinary native app. I know there is Titanium Developer and others, but they seem too complicated for this simple task. Is there some simple tool for this problem ?

A:

use phonegap, very very easy,
look at http://www.phonegap.com/start/
you will be given "assets" folder for HTML,CSS,Javascript . Just use those and run.


Q:

Transfomation of impedance using a balun

I need to convert 75 ohms balanced impedance to 50 ohms unbalanced impedance using a balun. How do I do that? I am new to this and don't really understand the concept of a:1 voltage and current baluns.

A:

To clarify your confusion, some transformers have isolated primary and secondary windings. Some don't and have only one winding with a third tap-off point. These are cheaper to manufacture and can be used where isolation is not required. In power transformers they're often used to step the mains down say, from 230 V to 115 V or similar.

simulate this circuit – Schematic created using CircuitLab
In your case you have a balanced signal which should feed into a balanced load. The balun provides such a load and the two halves of the balanced signal contribute to driving the unbalanced output. Notice that since you only have half the voltage on the output it will be able to deliver more current so its output impedance will be lower than the balanced signal.
I hope that helps.


Q:

Grub loading Error 22, on trying to boot second hand Dell 1950 server

I bought a Dell PE 1950 on Ebay, the post runs through showing the SAS 5 controller and two hard drives, but then it hangs at Grub loading ... Error 22.
I want to put Windows web server 2008 on it, but it will not boot from CDROM (the disk is fine tried it on aother machine). It will boot to an Ubuntu 8 disk. ANy clues appreciated.

A:

The server comes with a CD-drive, not a DVD-drive. Since Windows 2008 is shipped on a DVD that won't work.
I doubt it will even run, so why don't you try to install Server 2003? Or if you really want 2008 you could PXE-boot it.


Q:

Matlab get actual value of 'xTick'

I'm using Matlab to plotting data and trying to deal with the ticks/tick labels.
What I intend to do
Draw a graph with dynamic tick labels so I can find out the timestamp of a specific point on the graph. Thus the timestamp (xTickLabel) should only come from the data source.
What I achieved
Now I can:
Draw a graph with dynamic tick labels, but the labels are not fine enough: those labels are one-second per tick.
Here's the code of plotting:
fig = figure;
x = M(:, 1);

% convert the x (time) value from unix time to matlab time
x = (x / 86400 / 1000) + datenum(1970,1,1);
y1 = M(1:end, 2);
y2 = M(1:end, 3);
y3 = M(1:end, 4);

plot(x, y1, x, y2, x, y3);

xlim([x(1), x(end)]);

set(gca, 'XTick', x);
grid on;

datetick('x','yyyy-mm-dd HH:MM:SS.FFF', 'keeplimits', 'keepticks');
xticklabel_rotate;

hleg1 = legend('x', 'y', 'z');
% zoomAdaptiveDateTicks('on');

The code works fine and can plot the graph with every timestamp comes from the source data without enable the zoomAdaptiveDateTicks('on'), the original graph is displayed as below:

and if zoomAdaptiveDateTicks('on') is enabled, the graph will have dynamic tick labels, but the labels are one-second per tick with regardless of the zoom scale.

My Question
How can I make the graph with both fine-enough and dynamic tick labels?
I tried to find out the tick label values but no luck, is there any other way to do this?
Thanks,
And for your reference, here's the code of zoomAdaptiveDateTicks(link)
 function zoomAdaptiveDateTicks(varargin)
% ZOOMADAPTIVEDATETICKS - Make date ticks adapt to zooming
%
% zoomAdaptiveDateTicks('on')
% Turns on the automatic adaptation of date ticks
% to user zooming for the current figure window
%
% zoomAdaptiveDateTicks('off')
% Turns off the automatic adaptation of date ticks
% to user zooming for the current figure window
%
% zoomAdaptiveDateTicks('demo')
% Opens a demo figure window to play with

if (nargin>0)
   switch varargin{1}
      case 'demo'
         % Create demo values
         dates = floor(now) - linspace(1169,0,15000)';
         values= randn(15000,1);
         % Show data with date ticks
         figure
         plot(dates,values)
         datetick('x')
         zoomAdaptiveDateTicks('on')
      case 'on'
         % Define a post zoom callback
         set(zoom(gcf),'ActionPostCallback', @adaptiveDateTicks);
      case 'off'
         % Delete the post zoom callback
         set(zoom(gcf),'ActionPostCallback', '');
      otherwise
         figure(gcf)
   end
end

function adaptiveDateTicks(figureHandle,eventObjectHandle)

% Resetting x axis to automatic tick mark generation
 set(eventObjectHandle.Axes,'XTickMode','auto')

% get and set the tick length
% a = get(eventObjectHandle.Axes, 'XTick');
% minimum = min(a);
% maximum = max(a);

fprintf('minimum :%s, maximum:%s \n', num2str(minimum), num2str(maximum));
% set(eventObjectHandle.Axes, 'XTick'
%set(eventObjectHandle.Axes, 'TickLength', 0.5*(get(eventObjectHandle.Axes, 'TickLength')))

% using automaticallly generate date ticks
datetick(eventObjectHandle.Axes,'x','keeplimits')

Please feel free to ask if I didn't explain the question clearly.

A:

The problem seems to be with xticklabel_rotate, since it freezes the labels.
So I thought maybe I should do something like this in the callback:
   set(gca,'XTickLabelMode','auto');
   xticklabel_rotate;

But this didn't work... Then I noticed line 35 in xticklabel_rotate.m:
% Note : you can not RE-RUN xticklabel_rotate on the same graph.

You should try rotateXLabels instead of xticklabel_rotate.

As per ss1271's comment, the following code was able to achieve the desired result. The required modification is replacing the duo zoomAdaptiveDateTicks('on') & xticklabel_rotate with rotateXLabels(gca, 90):
close all force; clear variables; clc;

M = [(1:1000)',randn(1000,3)]; ...' //This is just to fix SO formatting

fig = figure(1337);
x = M(:, 1);

% convert the x (time) value from unix time to matlab time
x = (x / 86400 / 1000) + datenum(1970,1,1);
y1 = M(:, 2);
y2 = M(:, 3);
y3 = M(:, 4);

plot(x, y1, x, y2, x, y3);

xlim([x(1), x(end)]);

set(gca, 'XTick', x);
grid on;

datetick('x','yyyy-mm-dd HH:MM:SS.FFF','keepticks','keeplimits');

rotateXLabels(gca, 90);

hleg1 = legend('x', 'y', 'z');


Q:

qooxdoo destruct , dispose

Could any one please give a full example of how dispose and destruct are working in qooxdoo 1.6 ? , I can't find any good example in the qooxdoo demos or documentation.
thanks in advise .

A:

Disposal and destruction are in reality the two sides of the same coin: Disposal is the act of destructing objects. Their difference might become clearer to you by thinking of __destruct() as an onDispose() method.
As a rule of thumb, any class that creates QX objects is responsible for their proper destruction. Normally this is done the class' destructor, but may happen at any time depending on your business logic.
Disposal is done via the (ex.)
this._disposeObjects("_buttonOk", "_buttonCancel");
this._disposeArray("_children");
this._disposeMap("_registry");

calls. Some classes may provide explocit methods for their destruction, as in qx.ui.core.Widget

A:

You don't need to implement dispose if you work with object. Only destruct is needed, and not for everything (see above to catch which one you should delete, which one you don't need to)
It will looks like this :
qx.Class.define("q.view.Home"),{
    extend : qx.ui.core.Widget,
    construct:function(){
        this.base(arguments);
    },
    members:{
        __qooxdoo_object:null
    },
    destruct:function(){
        this._disposeObjects("__qooxdoo_object");
    }
});

As simple as this.
On the memory management link : this is extremely important : "qx.disposerDebugLevel" : "2"
It will automatically report (on firebug for example) object who are not properly destroyed.
So you will be able to know exactly what you should delete, what is deleted in a proper way.
Also, imagine this, you got a container (Composite for example, or anything) with 5 children and you want to empty the content but not the container, you should do like that :
(according container is the parent element of all children)
var childrenList = container.removeAll();
for(var i=0; i<childrenList.length; ++i){
  childrenList[i].dispose();
}

If you only dispose objet for some reason i don't know the Widget class (in qooxdoo framework) sometimes raise error. If you only removeAll, it will not dispose children but only remove them.
If you do both (dispose and removeAll), you will have no problem and children properly disposed.


Q:

Extract Text between two strings (Command Line)

I'm trying to extract song names from a json file from the Spotify API. The word "name" occurs for both artists and songs, and I'm trying to extract song names.
I tried using grep, but I'm not sure how to look for patterns of strings before and after the desired text (the song name). In this case, the song name is after "name", but before "popularity". In the case of artists' names, the name is after "name" and before "type".
How would I extract the text between the two words?
{
  "tracks" : [ {
    "album" : {
      "album_type" : "album",
      "artists" : [ {
        "external_urls" : {
          "spotify" : "https://open.spotify.com/artist/13ubrt8QOOCPljQ2FL1Kca"
        },
        "href" : "https://api.spotify.com/v1/artists/13ubrt8QOOCPljQ2FL1Kca",
        "id" : "13ubrt8QOOCPljQ2FL1Kca",
        "name" : "A$AP Rocky",
        "type" : "artist",
        "uri" : "spotify:artist:13ubrt8QOOCPljQ2FL1Kca"
      } ],
      "available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TH", "TR", "TW", "US", "UY" ],
      "external_urls" : {
        "spotify" : "https://open.spotify.com/album/1E1eyI5uGllppJZCxNoF9w"
      },
      "href" : "https://api.spotify.com/v1/albums/1E1eyI5uGllppJZCxNoF9w",
      "id" : "1E1eyI5uGllppJZCxNoF9w",
      "images" : [ {
        "height" : 640,
        "url" : "https://i.scdn.co/image/b0dad68115b71ec6c81240eac982da7d14676e6d",
        "width" : 640
      }, {
        "height" : 300,
        "url" : "https://i.scdn.co/image/342fd8bf9219b2369394bc6adf57a69b3fecc0f7",
        "width" : 300
      }, {
        "height" : 64,
        "url" : "https://i.scdn.co/image/79d71b48c2fd180c7506a2db2e13ed0a7c8107a2",
        "width" : 64
      } ],
      "name" : "LONG.LIVE.A$AP (Deluxe Version)",
      "type" : "album",
      "uri" : "spotify:album:1E1eyI5uGllppJZCxNoF9w"
    },
    "artists" : [ {
      "external_urls" : {
        "spotify" : "https://open.spotify.com/artist/13ubrt8QOOCPljQ2FL1Kca"
      },
      "href" : "https://api.spotify.com/v1/artists/13ubrt8QOOCPljQ2FL1Kca",
      "id" : "13ubrt8QOOCPljQ2FL1Kca",
      "name" : "A$AP Rocky",
      "type" : "artist",
      "uri" : "spotify:artist:13ubrt8QOOCPljQ2FL1Kca"
    }, {
      "external_urls" : {
        "spotify" : "https://open.spotify.com/artist/3TVXtAsR1Inumwj472S9r4"
      },
      "href" : "https://api.spotify.com/v1/artists/3TVXtAsR1Inumwj472S9r4",
      "id" : "3TVXtAsR1Inumwj472S9r4",
      "name" : "Drake",
      "type" : "artist",
      "uri" : "spotify:artist:3TVXtAsR1Inumwj472S9r4"
    }, {
      "external_urls" : {
        "spotify" : "https://open.spotify.com/artist/17lzZA2AlOHwCwFALHttmp"
      },
      "href" : "https://api.spotify.com/v1/artists/17lzZA2AlOHwCwFALHttmp",
      "id" : "17lzZA2AlOHwCwFALHttmp",
      "name" : "2 Chainz",
      "type" : "artist",
      "uri" : "spotify:artist:17lzZA2AlOHwCwFALHttmp"
    }, {
      "external_urls" : {
        "spotify" : "https://open.spotify.com/artist/2YZyLoL8N0Wb9xBt1NhZWg"
      },
      "href" : "https://api.spotify.com/v1/artists/2YZyLoL8N0Wb9xBt1NhZWg",
      "id" : "2YZyLoL8N0Wb9xBt1NhZWg",
      "name" : "Kendrick Lamar",
      "type" : "artist",
      "uri" : "spotify:artist:2YZyLoL8N0Wb9xBt1NhZWg"
    } ],
    "available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TH", "TR", "TW", "US", "UY" ],
    "disc_number" : 1,
    "duration_ms" : 233786,
    "explicit" : true,
    "external_ids" : {
      "isrc" : "USRC11201220"
    },
    "external_urls" : {
      "spotify" : "https://open.spotify.com/track/4XoP1AkbOurU9CeZ2rMEz2"
    },
    "href" : "https://api.spotify.com/v1/tracks/4XoP1AkbOurU9CeZ2rMEz2",
    "id" : "4XoP1AkbOurU9CeZ2rMEz2",
    "name" : "F**kin' Problems",
    "popularity" : 80,
    "preview_url" : "https://p.scdn.co/mp3-preview/1649b7c26c8bcfa8b252601cf428844cec9a8446?cid=8897482848704f2a8f8d7c79726a70d4",
    "track_number" : 7,
    "type" : "track",
    "uri" : "spotify:track:4XoP1AkbOurU9CeZ2rMEz2"
  }, {

A:

I guess with a little research you can find lots of solutions to your problem.
For instance if you always have the type of structure you quoted
grep name filename  | cut -c15- | rev | cut -c 3- | rev

would work. You can probably find more neat and robust solutions but in your case this works.
EDIT
Given you new file you can use
grep name filename | rev | cut -c 3- | cut -f1 -d'"' | rev